更新 GridLayout 中的网格
我有一个通过 JPanel 中的 GridLayout 布局的对象数组。我需要能够在数组的索引中重新创建对象,并更新 GridLayout 来反映这一点。到目前为止,我无法找到“刷新”或重绘 GridLayout 的方法。是否可以在不创建整个 GridLayout 或 JPanel 的情况下刷新 GridLayout?假设我无权访问 JFrame。
import javax.swing.*;
import java.awt.*;
public class Test
{
public static void main(String args[])
{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5,5));
JLabel[][] labels = new JLabel[5][5];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
labels[j][i] = new JLabel("("+j+", "+i+")");
panel.add(labels[j][i]);
}
}
labels[0][0] = new JLabel("Hello World");
//Without doing it this way (cause my objects can't do this)
//labels[0][0].setText("Hello World!");
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
}
I have an array of objects laid out through a GridLayout in a JPanel. I need to be able to recreate the object in an index in the array and have the GridLayout update to reflect this. As of yet, I cannot find anyway to "refresh" or redraw the GridLayout. Is it possible to refresh a GridLayout without creating the entire GridLayout or JPanel? Assume I do not have access to JFrame.
import javax.swing.*;
import java.awt.*;
public class Test
{
public static void main(String args[])
{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5,5));
JLabel[][] labels = new JLabel[5][5];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
labels[j][i] = new JLabel("("+j+", "+i+")");
panel.add(labels[j][i]);
}
}
labels[0][0] = new JLabel("Hello World");
//Without doing it this way (cause my objects can't do this)
//labels[0][0].setText("Hello World!");
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不明白为什么你不能只更新标签上的文字。
为什么需要“重新创建对象”?这毫无意义。但如果你确实需要这样做,那么代码将类似于:
I don't understand why you can't just update the text on the label.
Why do you need to "recreate the object"? It makes no sense. But if you really need to do this then the code would be something like: