how to create a gui in java

how to create a gui in java

To create a GUI (graphical user interface) in Java, you can use the javax.swing package, which provides a set of classes for creating graphical components such as windows, buttons, labels, and text fields.

Here is an example of how you can create a simple GUI with a window, a label, and a button in Java:

‮efer‬r to:lautturi.com
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SimpleGUI {
  public static void main(String[] args) {
    // Create the window
    JFrame frame = new JFrame("Simple GUI");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 100);
    frame.setLocationRelativeTo(null);  // Center the window

    // Create the label
    JLabel label = new JLabel("Hello, World!");
    label.setHorizontalAlignment(SwingConstants.CENTER);  // Center the label

    // Create the button
    JButton button = new JButton("Click me");
    button.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        label.setText("Button clicked!");
      }
    });

    // Add the label and button to the window
    Container contentPane = frame.getContentPane();
    contentPane.add(label, BorderLayout.CENTER);
    contentPane.add(button, BorderLayout.SOUTH);

    // Show the window
    frame.setVisible(true);
  }
}

This code creates a JFrame object called frame that represents the main window of the GUI. It sets the default close operation to EXIT_ON_CLOSE, which means that the program will terminate when the window is closed. It also sets the size and position of the window.

It creates a JLabel object called label that displays the text "Hello, World!". It sets the horizontal alignment of the label to SwingConstants.CENTER to center the text.

It creates a JButton object called button that displays the text "Click me". It adds an ActionListener to the button using the addActionListener method. The ActionListener defines an actionPerformed method that is called when the button is clicked. In this case, the method sets the text of the label to "Button clicked!".

It adds the label and button to the content pane of the window using the add method and specifying the layout as BorderLayout.CENTER and BorderLayout.SOUTH, respectively.

Created Time:2017-11-01 12:05:16  Author:lautturi