MyFrame.java
package swing; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.SimpleDateFormat; import java.util.Date; public class MyFrame extends JFrame { JLabel timeLabel= new JLabel("00:00:00"); JButton button=new JButton("显示时间"); public MyFrame(String title){ super(title); //内容面板 Container contentPane=getContentPane(); contentPane.setLayout(new FlowLayout()); //向内容面板添加控件 contentPane.add(button); contentPane.add(timeLabel); //创造监听器对象 //把监听器注册给按钮 button.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { //当按钮被点击时,Swing框架会调用监听器的actionPerformed()方法 System.out.println("按钮被点击...."); showTime(); } }); } public void showTime(){ SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss"); String timestr=sdf.format(new Date()); timeLabel.setText(timestr); System.out.println("时间已更新"); } } package swing; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.SimpleDateFormat; import java.util.Date; public class MyFrame extends JFrame { JLabel timeLabel= new JLabel("00:00:00"); JButton button=new JButton("显示时间"); public MyFrame(String title){ super(title); //内容面板 Container contentPane=getContentPane(); contentPane.setLayout(new FlowLayout()); //向内容面板添加控件 contentPane.add(button); contentPane.add(timeLabel); //创造监听器对象 //把监听器注册给按钮 button.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { //当按钮被点击时,Swing框架会调用监听器的actionPerformed()方法 System.out.println("按钮被点击...."); showTime(); } }); } public void showTime(){ SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss"); String timestr=sdf.format(new Date()); timeLabel.setText(timestr); System.out.println("时间已更新"); } }
SwingDemo.java
package swing; import javax.swing.*; public class SwingDemo { private static void createGUI(){ //JFrame指一个窗口,构造方法的参数为窗口标题 MyFrame frame=new MyFrame("swing demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置窗口的其它参数,如窗口大小 frame.setSize(400,300); //显示窗口 frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { createGUI(); } }); } }