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.
You do this with a simple method call on your JFrame object, like this: myJFrame. setDefaultCloseOperation(WindowConstants. EXIT_ON_CLOSE);
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.
We can close the AWT Window or Frame by calling dispose() or System. exit() inside windowClosing() method.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With