制作applet

时间:2018-03-01 19:44:31

标签: java applet

我有问题,我没有得到我的结果,为什么?

public class cycle extends JApplet implements ActionListener {

  Panel panel = new Panel();
  JButton left = new JButton("left");
  JButton right = new JButton("right");
  Container c = getContentPane();

  public void frame() {
    Panel panel = new Panel();
    JButton left = new JButton("left");
    JButton right = new JButton("right");
    c.add(left);
    c.add(right);
  }

  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setTitle("Move the ball");
    f.setSize(500, 500);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
  }

}

1 个答案:

答案 0 :(得分:1)

以这种方式更改您的代码:

  • Button添加到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
  • 正如下面 Andrew Thompson的评论所建议的那样:不要混合使用Swing& AWT组件。 (小组应该是JPanel