【发布时间】:2016-04-26 12:48:38
【问题描述】:
我们希望能够更改 JLabel 数组上的文本/图像,但我们无法理解为什么它不起作用。
import java.awt.*;
class layoutWindow extends JFrame implements ActionListener {`
String[] classStrings = { "EN1A", "EN2A", "EN3A", "EN1B", "EN2B", "EN3B",
"ES1A", "ES2A", "ES3A", "ES1B", "ES2B", "ES3B", "H1", "H2", "H3",
"N1A", "N1B", "N1C", "N1D", "N1E", "N2A", "N2B", "N2C", "N2D",
"N2E","N3A","N3B","N3C","N3D","S1A","S1B","S2A","S2B","S3A","S3B" };
String[] FormationStrings = { "3-3-3", "3-3-2", "2-4-2", "4-4", "2-2-2-2","3-4-3" };
// Create the combo box, select item at index 4.
JLabel[] deskLabels = new JLabel[96];
JComboBox classList = new JComboBox(classStrings);
JComboBox formationList = new JComboBox(FormationStrings);
JButton seatbButton = new JButton(" randomize");
JButton backButton = new JButton("back");
JButton groupButton = new JButton("Make groups");
JLabel classLabel = new JLabel("choose class");
JLabel formationLabel = new JLabel("choose formation");
JPanel layoutPanel = new JPanel(new GridLayout(8, 12, 1,15));
JPanel top = new JPanel(new GridLayout(1, 2, 15,1));
public layoutWindow() {
super("layout Example");
setExtendedState(JFrame.MAXIMIZED_BOTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
Container contentArea = getContentPane();
top.setVisible(true);
layoutPanel.setVisible(true);
int i = 1;
for (JLabel label : deskLabels) {
label = new JLabel();
if ((i % 12) != 100) {
label.setText("" + i);
layoutPanel.add(label);}
else {
label.setText(" ");
layoutPanel.add(label);
}
i++;
}
top.add(backButton);
top.add(classLabel);
top.add(classList);
top.add(formationLabel);
top.add(formationList);
top.add(seatbButton);
contentArea.add("North", top);
contentArea.add("Center", layoutPanel);
setContentPane(contentArea);
formationList.addActionListener(this);
classList.addActionListener(this);
backButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent event) {
String string = (String) formationList.getSelectedItem();
if(string == "4-4"){
deskLabels[5].setText("aasdggnmh");
}
}
}
布局任务窗口
public class layouttaskwindow {
public static void main(String[] args) {
layoutWindow win = new layoutWindow();
}
}
我们不明白为什么这不起作用。我们使用 for 循环从数组中创建所有标签,但是当我们尝试更改它们时它不起作用。我们试图在 ActionEvent 中更改它但我们没有得到回应,有人可以解释一下如何解决这个问题吗?
【问题讨论】:
-
您能解释一下您预计会发生什么吗?这段代码有几个错误,但不清楚你指的是什么问题。我的第一个猜测是这一行:deskLabels[5].setText("aasdggnmh");我希望这会引发 NPE,因为您从未将任何内容放入deskLabels。
-
我想要发生的事情是让我在 JLabel 数组中的标签对命令做出反应,现在它根本没有。