按以下方式更改代码:
-
添加
Button
s到您的
JPanel
-
添加
Panel
到
ContentPane
-
添加您的
cycle
对象到
JFrame
这是修改后的代码
public class cycle extends JApplet implements ActionListener {
private JPanel panel;
private JButton left;
private JButton right;
private Container c = getContentPane();
public cycle() {
panel = new JPanel();
left = new JButton("left");
right = new JButton("right");
panel.add(left);
panel.add(right);
c.add(panel);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setTitle("Move the ball");
f.setSize(500, 500);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.add(new cycle());
f.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
也:
-
我建议你重新命名你的班级
Cycle
,以大写开头是Java惯例。
-
使用
WindowConstants.EXIT_ON_CLOSE
而不是
JFrame.EXIT_ON_CLOSE
-
如以下意见所示:
安德鲁·汤普森
:请勿混用Swing和;AWT组件。(面板应为
面板
)