1 //Import the required libraries
2 import javax.swing.*;
3 import java.awt.*;
4 import java.awt.event.*;
5
6
7 public class Greeting
8 {
9
10 /* Declare the objects and variables that
11 we want to access across multiple methods */
12 static JLabel label;
13 static JButton btnClick;
14
15 private static void guiApp()
16 {
17 //Create and setup the window
18 JFrame frame = new JFrame("Simple GUI");
19 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20
21 //Usually a JPanel is used as the container for our widgets
22 JPanel panel = new JPanel();
23 label = new JLabel("Text me!");
24 btnClick = new JButton("Send text!");
25 panel.add(btnClick);
26 panel.add(label);
27 frame.add(panel);
28 frame.setSize(250,100);
29 frame.setVisible(true);
30
31 //Create a new ButtonHandler instance
32 ButtonHandler onClick = new ButtonHandler();
33 btnClick.addActionListener(onClick);
34 }
35
36 /* Create custom event handler -
37 this is what will happen when the button is clicked */
38 private static class ButtonHandler implements ActionListener
39 {
40
41 public void actionPerformed(ActionEvent e)
42 {
43 label.setText("Hello World");
44
45 }
46 }
47 public static void main(String[] args)
48 {
49 /* Schedule a job for the event-dispatching thread. C
50 reating and showing this application's GUI. */
51 javax.swing.SwingUtilities.invokeLater(new Runnable()
52 {
53 public void run()
54 {
55 guiApp();
56 }
57 });
58 }
59
60 }