java how to make a gui

w‮tual.ww‬turi.com
java how to make a gui

To create a graphical user interface (GUI) in Java, you can use the javax.swing package and the javax.swing.JFrame class. The JFrame class represents a top-level window with a title and a border. You can add components, such as buttons, labels, and text fields, to the JFrame to create the GUI.

Here is an example of how to create a simple GUI with a button and a label in Java:

import javax.swing.*;
import java.awt.event.*;

public class Main {
    public static void main(String[] args) {
        // create a JFrame
        JFrame frame = new JFrame("My GUI");
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        // create a button and add an action listener
        JButton button = new JButton("Click me!");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // code to be executed when the button is clicked
            }
        });

        // create a label
        JLabel label = new JLabel("Hello, World!");

        // add the button and label to the JFrame
        frame.add(button);
        frame.add(label);
    }
}

In this example, a new JFrame object is created and initialized with a title and a size. The setDefaultCloseOperation method is used to specify that the program should exit when the JFrame is closed. The setVisible method is used to make the JFrame visible on the screen.

A new JButton object is then created and initialized with a label. An ActionListener is added to the button using the addActionListener method. The ActionListener is an interface that defines a single method, actionPerformed, which is called when the button is clicked. The ActionListener can be implemented as an anonymous inner class or a separate class that implements the ActionListener interface.

A new JLabel object is then created and initialized with a string.

The button and label are then added to the JFrame using the add method.

This example will create a JFrame with a button and a label, as shown in the following screenshot:

[Insert screenshot]

You can use the javax.swing package and the JFrame class to create a GUI in your Java applications. You can add various components, such as buttons, labels, text fields, and panels, to the JFrame to create a more complex GUI. You can also use layout managers, such as FlowLayout, GridLayout, and BorderLayout, to control the layout of the components in the JFrame.

Created Time:2017-11-03 23:27:14  Author:lautturi