1 回答

TA貢獻1712條經(jīng)驗 獲得超3個贊
您JLabel在寫作時聲明匿名:
subPanel1.add(new JLabel("Random word here"));
您需要將其設置為變量:
JLabel label = new JLabel("Random word here");
subPanel1.add(label);
現(xiàn)在你有你button自己的ActionListener:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = names[(int) (Math.random() * names.length)];
((JButton) e.getSource()).setText(name);
}
});
而且您正在設置JButton的文本,而不是標簽,因此我們需要將其更改為:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = names[(int) (Math.random() * names.length)];
label.setText(name);
}
});
那應該做你想做的事,我沒有嘗試過,但它在我的腦海中有效。
附加提示:
不要調(diào)用
setPreferredSize()
,而是覆蓋getPreferredSize()
方法:我應該避免在 Java Swing 中使用 set(Preferred|Maximum|Minimum)Size 方法嗎?不要在代碼中間留下太多空間并正確縮進。
添加回答
舉報