Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a GUI in Java [closed]

I have used Java for some time, but I have never created a GUI - always CLI. How does one create a GUI in Java? Can you suggest a good tutorial/reference?

I'm looking to create a simple GUI that has two long text areas and some buttons.

like image 306
Amir Rachum Avatar asked Feb 25 '11 14:02

Amir Rachum


People also ask

How do you make a JFrame close itself?

You do this with a simple method call on your JFrame object, like this: myJFrame. setDefaultCloseOperation(WindowConstants. EXIT_ON_CLOSE);

Can you make a GUI with Java?

The Java language provides a set of user interface components from which GUI forms can be built. The IDE's GUI Builder assists you in designing and building Java forms by providing a series of tools that simplify the process.

How do you exit a frame in Java?

We can close the AWT Window or Frame by calling dispose() or System. exit() inside windowClosing() method.


1 Answers

Here's a simple example

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

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;

public class Foo{

  public static void main(String[] args) {

    JFrame f = new JFrame("A JFrame");
    f.setSize(250, 250);
    f.setLocation(300,200);
    final JTextArea textArea = new JTextArea(10, 40);
    f.getContentPane().add(BorderLayout.CENTER, textArea);
    final JButton button = new JButton("Click Me");
    f.getContentPane().add(BorderLayout.SOUTH, button);
    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            textArea.append("Button was clicked\n");

        }
    });

    f.setVisible(true);

  }

}
like image 158
Bala R Avatar answered Nov 07 '22 15:11

Bala R