Image Credit: Wikipedia
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainWindow extends JFrame
implements ActionListener {
public MainWindow() {
// create GUI
}
@Override
public void actionPerformed(ActionEvent e) {
// handle events
}
public static void main(String[] args){
// start program
}
}
// sets the size of this window
this.setSize(new Dimension(200, 100));
// tell the program to exit when this window is closed
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set the layout manager
this.setLayout(new GridBagLayout());
// Create the constraints for the GridBagLayout manager
GridBagConstraints gbc = new GridBagConstraints();
Image Credit: Oracle
Uses Rows & Columns
Image Credit: Oracle
Can Grow to Fit Screen
Image Credit: Oracle
// set the constraints for the label
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
// add a label
this.add(new JLabel("Hello World!"), gbc);
// reset the constraints for the button
gbc.gridx = 0;
gbc.gridy = 1;
// create a button
JButton button = new JButton("Close");
// set the button's command:
button.setActionCommand("close");
// send the clicked event to this object
button.addActionListener(this);
// add the button
this.add(button, gbc);
Specified by ActionListener
interface
@Override
public void actionPerformed(ActionEvent e) {
if ("close".equals(e.getActionCommand())) {
// close button was clicked, so exit the application
System.exit(0);
}
}
Use a Thread!
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MainWindow().setVisible(true);
}
});
}