swing Basics Adding JButtons (Hello World Pt.2)


Example

Assuming that you have successfully created a JFrame and that Swing has been imported...

You can import Swing entirely

import javax.Swing.*;

or You can import the Swing Components/Frame that you intend to use

import javax.Swing.Jframe;
import javax.Swing.JButton;

Now down to adding the Jbutton...

public static void main(String[] args) {
    
    JFrame frame = new JFrame(); //creates the frame
    frame.setSize(300, 300);
    frame.setVisible(true);

    //////////////////////////ADDING BUTTON BELOW//////////////////////////////
    JButton B = new JButton("Say Hello World");
    B.addMouseListener(new MouseAdapter() {
        
        public void mouseReleased(MouseEvent arg0) {
            System.out.println("Hello World");
        }
        
    });
    B.setBounds(0, 0,frame.getHeight(), frame.getWidth());
    B.setVisible(true);
    frame.add(B);
    ////////////////////////////////////////////////////////////////////////////
}

By Executing/Compiling this code you should get something like this...

Final Product

When the button is clicked... "Hello World" should also appear in your console.