JAVA BASIC BUTTON

Now that you have created your window, lets add something to it.

  1. Create a JButton (above the main method, not inside)
     public static JButton button;
    
  2. Instantiate in the main method

    • JButton takes a String argument of the text

      button = new JButton("BUTTON");
      
  3. Set the button's bounds (X, Y, Width, Height)
       button.setBounds(20,20,200,100);
    
  4. Set the action listener

    • Action listeneners can be a bit difficult to understand
    • To add functionality to a button give it a new action listener, then define what it does under actionPerformed

      button.addActionListener(new ActionListener() {
      
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Button Clicked!!!");
            }
      
      });
      
  5. Add the button to the frame
     frame.add(button);
    
  6. Test your app. Try adding more buttons and play around a bit :D

results matching ""

    No results matching ""