Search code examples
javaapplet

Making an applet


I have the problem that I am not getting my results, why?

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.
  }

}

Solution

  • Change your code this way:

    • Add the Buttons to your JPanel
    • Add the Panel to the ContentPane
    • Add your cycle object to the JFrame

    Here is the modified code

    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.
      }
    
    }
    

    Also:

    • I would suggest you rename your class Cycle, it is a Java convention to start with an upper case.
    • Use WindowConstants.EXIT_ON_CLOSE instead of JFrame.EXIT_ON_CLOSE
    • As suggested below in the comments by Andrew Thompson: Don't mix Swing & AWT components. (The Panel should be a JPanel)