JFrame显示刷新

 1 import java.awt.BorderLayout;
 2 import java.awt.Font;
 3 import java.awt.event.ActionEvent;
 4 import java.awt.event.ActionListener;
 5 import javax.swing.JButton;
 6 import javax.swing.JFrame;
 7 import javax.swing.JLabel;
 8 import javax.swing.JPanel;
 9 
10 /**
11  * 主要是怎样刷新显示
12  * @author Administrator
13  *
14  */
15 public class TestPanel extends JFrame{
16     private ShowPanel panel;
17     public TestPanel() {
18         panel = new ShowPanel();
19         add(panel);
20         panel.ShowOne();
21     }
22     public static void main(String[] args) {
23         TestPanel testPanel = new TestPanel();
24         testPanel.setSize(500, 300);
25         testPanel.setLocationRelativeTo(null);
26         testPanel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
27         testPanel.setVisible(true);
28     }
29     class ShowPanel extends JPanel{
30         JLabel jlb;
31         JLabel jlb2;
32         JButton jbt;
33         public ShowPanel(){
34             setLayout(new BorderLayout());
35             jbt = new JButton("PRESS");
36             jbt.addActionListener(new ActionListener() {
37                 @Override
38                 public void actionPerformed(ActionEvent e) {
39                     ShowTwo();                            //通过按钮增加一个label
40                 }
41             });
42             add(jbt, BorderLayout.NORTH);
43         }
44         public void ShowOne(){                            //显示一个label
45             jlb = new JLabel("LABEL1");
46             jlb.setFont(new Font("SansSerif", Font.BOLD, 80));
47             add(jlb, BorderLayout.CENTER);
48         }
49         public void ShowTwo(){                            //增加一个label
50             jlb2 = new JLabel("LABEL2");
51             jlb2.setFont(new Font("SansSerif", Font.BOLD, 80));
52             add(jlb2, BorderLayout.SOUTH);
53             validate();            //Validates this container and all of its subcomponents. 
54             //如果此处没有validate()点击PRESS,不会主动显示LABEL2
55         }
56         
57     }
58 }

 

posted @ 2013-11-26 21:10  soul390  阅读(1229)  评论(0编辑  收藏  举报