Programmer's Blog

Programmer's reference

Category Archives: Swing

[javax.swing] add and show object to Jframe

JFrame frame1 = new JFrame("Frame");
JButton button = new JButton("OK");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame1.getContentPane().add(button);
frame1.pack();
frame1.setVisible(true);

[javax.swing] set position of JFrame

JFrame frame = new JFrame("Frame");

frame.setLocation(x,y);
e.g.
frame.setLocation(500,500);

[javax.swing] Add actionListener to JButton

The following example is to set listener when the JButton is pressed

The java.awt.ActionEvent and java.awt.ActionListener is needed for this action.

The action of the listener will be executed in the function “actionPerformed” at event e.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

JButton button = new Jbutton();
button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

        /*Action Here*/
        System.out.println("Hey");
       }
 });