// David Greenstein
// March 12, 2013
// HelloSwing.java
// A JFrame that shows a button that says
// "Click Me!". When the button is clicked, an informational
// dialog box appears to say Hello from Swing.
import javax.swing.*; // Swing GUI classes are defined here.
import java.awt.event.*; // Event handling class are defined here.
public class HelloSwing implements ActionListener
{
JFrame frame;
public static void main(String[] args)
{
HelloSwing hs = new HelloSwing();
hs.Run();
}
public void Run()
{
frame = new JFrame("HelloSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// This method is called by the system before the applet
// appears. It is used here to create the button and add
// it to the "content pane" of the JApplet. The applet
// is also registered as an ActionListener for the button.
JButton bttn = new JButton("Click Here, MV Java Students!");
bttn.addActionListener(this);
frame.add(bttn);
frame.setSize(500, 500); // explicitly set size in pixels
frame.setVisible(true); // set to false to make invisible
} // end Run()
public void actionPerformed(ActionEvent evt)
{
// This method is called when an action event occurs.
// In this case, the only possible source of the event
// is the button. So, when this method is called, we know
// that the button has been clicked. Respond by showing
// an informational dialog box. The dialog box will
// contain an "OK" button which the user must click to
// dismiss the dialog box.
String title = "YIKES!"; // Shown in title bar of dialog box.
String message = "Ouch, don't click so hard next time!";
JOptionPane.showMessageDialog(null, message, title,
JOptionPane.INFORMATION_MESSAGE);
} // end actionPerformed()
} // end class HelloSwing
Back to Lesson 24 Examples
Back to Java Main Page