Description:
- The frame has an event listener which will trigger when a user click the close button.
- The label also has an event listener which will trigger when a user click on it.
- I extend/inherit the Jframe base class to create a window.
- In the main method, I set several options for the frame.
- I add event listeners to the frame and the label which both will trigger a popup message .
Comparing C# against Java:
- In c#, I use an event delegate to build event notifications. In Java,I register event listener with the event publisher object, and that object will call a specific predefined method in the event listener when the event occurs.
package myfirst;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/**
*
* @author chien
*/
public class Myfirst {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
SimpleFrame frame = new SimpleFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3, 1));
// Add a window listner for close button
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
JOptionPane.showMessageDialog(null, "Close window", "alert", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
});
// This is an empty content area in the frame
JLabel jlbempty = new JLabel("http://proexper.blogspot.com");
jlbempty.addMouseListener
(
new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
JOptionPane.showMessageDialog(null, "Click the label", "alert", JOptionPane.ERROR_MESSAGE);
}
}
);
jlbempty.setSize(50, 20);
jlbempty.setBorder(BorderFactory.createLineBorder(Color.yellow));
frame.getContentPane().add(jlbempty, BorderLayout.CENTER);
frame.setVisible(true);
}
}
class SimpleFrame extends JFrame
{
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
public SimpleFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
}
0 comments:
Post a Comment