我们希望能够更改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
中更改它但我们没有得到回应,有人可以解释一下这是怎么回事解决了吗?
答案 0 :(得分:1)
我也认为(就像Hackerdarshi说的那样,我没有阅读帖子,但看起来不错)问题是由foreach循环引起的。不确定,但我认为Java没有给你正确的参考。所以要修复它你可以试试这个:
for (int i = 0; i < deskLabels.length; i++) {
deskLabels[i] = new JLabel();
if ((i % 12) != 100) deskLabels[i].setText("" + i);
else deskLabels[i].setText(" ");
layoutPanel.add(deskLabels[i]);
}
正如伯杰所说的另一个问题是:string == "4-4"
不深入(for more read this):当你使用==时,你通常会按值进行比较。但是Strings是Object,所以在一个对象上调用==会比较它的引用而不是它的值。在Java中,字符串是特殊的。因此,它取决于他们如何初始化==返回的内容。所以只需使用
string.equals("4-4")
如果要比较String的值