我需要在整个程序中更新不同标签的文本。
示例:如果我的网格布局是(12,12)并且我需要更改(2,5)标签的文本,我该怎么办?
甚至可能是一种擦除标签并在同一位置添加新标签的方法。
答案 0 :(得分:1)
创建JLabel
JLabel[][] labels = new JLabel[12][12];
// populate and add to container with GridLayout(12, 12)
...
// change property
JLabel label = labels[2][5];
label.setText(..)
“甚至可能是一种擦除标签并在同一位置添加新标签的方法。”
不需要,只需更改现有属性
即可<强>更新强>
请参阅此处的示例。密切关注方法createButtonsPanel
。它是我从网格访问标签的地方。
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestLabelGrid {
public TestLabelGrid() {
JLabel[][] labelGrid = createLabelGrid(6, 6);
JPanel labelPanel = createPanel(labelGrid);
JPanel buttonPanel = createButtonsPanel(labelGrid);
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(2, 1));
frame.add(labelPanel);
frame.add(buttonPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createPanel(JLabel[][] labels) {
int rows = labels.length;
int cols = labels[0].length;
JPanel panel = new JPanel(new GridLayout(rows, cols));
for (JLabel[] rowOfLabels: labels) {
for (JLabel label : rowOfLabels) {
panel.add(label);
}
}
return panel;
}
private JLabel[][] createLabelGrid(int rows, int cols) {
JLabel[][] labels = new JLabel[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
labels[i][j] = new JLabel("( " + i + " , " + j + " )");
}
}
return labels;
}
private JPanel createButtonsPanel(final JLabel[][] labels) {
int rows = labels.length;
int cols = labels[0].length;
JButton[][] buttons = new JButton[rows][cols];
JPanel panel = new JPanel(new GridLayout(rows, cols));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
String text = "( " + i + " , " + j + " )";
JButton button = new JButton(text);
buttons[i][j] = button;
final int jTemp = j;
final int iTemp = i;
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JLabel label = labels[iTemp][jTemp];
label.setForeground(Color.BLUE);
}
});
panel.add(button);
}
}
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new TestLabelGrid();
}
});
}
}
答案 1 :(得分:0)
您可以保存对每个标签的引用,或perhaps use container.getComponents(),但我不确定该方法是否对数组中组件的顺序有任何保证。
要交换组件,您可以在GridLayout的每个位置添加一个容器,并更改该位置的容器所包含的组件。