Create a New Jbutton on Jframe Using Java

JButton is a part of the Swing components thus will be used with JFrame. By reading this article, you will learn how to create a simple JButton inside a JFrame with Java programming language.

Steps

  1. Create a new Java file using your preferred text editor or IDE and import a few classes. In this article, we will name the class JColorButtonOne. Firstly, import all classes from the Swing and AWT packages like this:
    • import java.awt.*;
    • import javax.swing.*;
  2. Declare JColorButtonOne class and variables. Declare and initialize variables for size, container and a button.
    • public class JColorButtonOne extends JFrame { private final int SIZE = 200; private Container con = getContentPane(); private JButton button = new JButton("Button");
  3. Create a constructor. Inside the constructor, set the size of the frame by passing the previously declared variable into the setSize method for width and height. Afterwards, set the layout, tweak background and foreground color and add a button to the previously declared container.
    • public JColorButtonOne() { super("Button"); setSize(SIZE, SIZE); con.setLayout(new FlowLayout()); con.add(button); con.setBackground(Color.BLACK); button.setBackground(Color.ORANGE); button.setForeground(Color.WHITE); }
  4. Prepare program for execution. Add the infamous public static void main(String[] args) to make the class executable. Inside the method create an instance of the created JColorButtonOne class and set the default closing operation to EXIT_ON_CLOSE. Lastly, make the frame visible.

Tips

  • Then type in this line to run the program if there is no error after the above action : java JColorButtonOne
  • Every time you make a change in your .java file you need to compile the program again or else you will still using the old version of the java code instead of the new one.
  • You will need to compile the program first using this line on the cmd.exe command prompt : javac JColorButtonOne.java.
  • For JButton Frame 1:
    • JButton startButton = new JButton("Start");//The JButton name.
    • add(startButton);//Add the button to the JFrame.
    • startButton.addActionListener(this);//Reads the action.

Sources and Citations