Java事件处理程序(任意窗口)
1.完成一个按钮的事件处理程序,实现功能自拟,例如:改变窗口的背景颜色,改变按钮的位置等等
代码
1 package Person; 2 import java.awt.*; 3 import javax.swing.*; 4 5 class Example extends JFrame{ 6 public void CrFrame(String title){ 7 JFrame f=new JFrame(title); 8 Container container=f.getContentPane(); //容器 9 10 JLabel l=new JLabel("这是一个居中的标签 :)"); //标签 11 l.setHorizontalAlignment(SwingConstants.CENTER); //标签居中 12 container.add(l); 13 container.setBackground(Color.pink); 14 f.setVisible(true); 15 f.setSize(500,500); 16 f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 17 } 18 } 19 20 public class Button { 21 public static void main(String[] args) { 22 new Example().CrFrame("来创建一个窗口"); 23 } 24 25 }
运行界面
2.
代码
1 public class example implements ActionListener { 2 JFrame f1,f2; 3 JPanel p1,p2; 4 JButton b1,b2; 5 JLabel l1,l2; 6 7 public example() { 8 f1 = new JFrame(); 9 f2 = new JFrame(); 10 p1 = new JPanel(new GridLayout(2,3)); 11 p2 = new JPanel(new GridLayout(2,3)); 12 b1 = new JButton("点击一下"); 13 l1 = new JLabel("这是一个标签"); 14 15 b1.addActionListener(this); 16 f1.setLocationRelativeTo(null); 17 f1.setSize(400,200); 18 f1.setTitle("第一个窗口"); 19 f1.add(p1); 20 p1.add(b1); 21 p1.add(l1); 22 f1.setVisible(true); 23 } 24 25 public static void main(String[] args) { 26 new example(); 27 } 28 29 public void actionPerformed(ActionEvent e) { 30 31 f2.setLayout(new GridLayout(2,1)); 32 33 f1.setVisible(false); 34 b2 = new JButton("再点一下"); 35 l2=new JLabel("这是一个居中的标签 :)"); 36 l2.setHorizontalAlignment(SwingConstants.CENTER); 37 f2.setLocationRelativeTo(null); 38 f2.setSize(400,200); 39 f2.setTitle("第二个窗口"); 40 f2.add(p2); 41 p2.add(b2); 42 p2.add(l2,BorderLayout.CENTER); 43 f2.setVisible(true); 44 } 45 }
运行界面