我正在尝试将事件监听器添加到我的“播放”按钮,但每当我在播放按钮中添加一个按钮消失或我得到并且错误时。
package hamster.race;
import java.awt.*;
import javax.swing.*;
public class HamsterRace extends JFrame {
public HamsterRace(){
super("HamsterRace");
setLookAndFeel();
setSize(350*3, 100*5);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flo = new FlowLayout();
setLayout(flo);
setVisible(true);
JButton Play = new JButton("Play");
add(Play);
add(Play);
}
private void setLookAndFeel() {
try{
UIManager.setLookAndFeel{
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
};
}catch (Exception exc) {
//ignore error
}
}
public static void main(String[] args) {
HamsterRace frame = new HamsterRace();
}
}
答案 0 :(得分:1)
首先,变量名不应以大写字母开头。
JButton Play = new JButton("Play");
add(Play);
add(Play);
您只有一个组件。您不能两次添加相同的组件。
所以基本代码是:
//setVisible(true);
JButton play1 = new JButton("Play1");
add(play1);
JButton play2 = new JButton("Play2");
add(play2);
pack();
setVisible(true);