Java Jframe Jpanel画桌面程序及Jbutton点击监听事件
下面只是一个使用小demo
1 package cnom.test.testUtils; 2 3 import java.awt.BorderLayout; 4 import java.awt.Color; 5 import java.awt.FlowLayout; 6 import java.awt.Graphics; 7 import java.awt.event.ActionEvent; 8 import java.awt.event.ActionListener; 9 10 import javax.swing.Box; 11 import javax.swing.JButton; 12 import javax.swing.JFrame; 13 import javax.swing.JLabel; 14 import javax.swing.JPanel; 15 import javax.swing.JPasswordField; 16 import javax.swing.JTextField; 17 import javax.swing.WindowConstants; 18 19 public class testJframeJpanel { 20 public static void main(String[] args) { 21 testJframe(); 22 // testBox(); 23 } 24 25 private static void testJframe() { 26 JButton jb1, jb2, jb3, jb4, jb5, jb6; 27 JPanel jp1, jp2; 28 JFrame jf = new JFrame(); 29 30 jb1 = new JButton("西瓜"); 31 jb2 = new JButton("苹果"); 32 jb3 = new JButton("香蕉"); 33 jb4 = new JButton("荔枝"); 34 jb5 = new JButton("葡萄"); 35 jb6 = new JButton("桔子"); 36 37 final JTextField tf = new JTextField(); 38 tf.setBounds(50, 50, 150, 20); 39 jb3.setBounds(100, 50, 65, 30); 40 jb3.addActionListener(new ActionListener() { 41 public void actionPerformed(ActionEvent e) { 42 tf.setText("This is Banana"); 43 tf.setBackground(Color.cyan); 44 testBox(); 45 } 46 }); 47 48 jp1 = new JPanel(); 49 jp2 = new JPanel(); 50 51 jp1.add(jb1); 52 jp1.add(jb2); 53 jp2.add(jb4); 54 jp2.add(jb5); 55 jp2.add(jb6); 56 57 jf.add(jp1, BorderLayout.NORTH); 58 jf.add(jp2, BorderLayout.SOUTH); 59 jf.add(jb3); 60 jf.add(tf); 61 62 jf.setTitle("用户登录"); 63 jf.setSize(400, 200); 64 jf.setLocation(300, 300); 65 jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 66 67 jf.setVisible(true); 68 } 69 70 private static void testBox() { 71 JFrame jf = new JFrame("用户登录"); 72 jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 73 74 // 第 1 个 JPanel, 使用默认的浮动布局 75 JPanel panel01 = new JPanel(); 76 panel01.add(new JLabel("用户名")); 77 JTextField username = new JTextField(10); 78 panel01.add(username); 79 80 // 第 2 个 JPanel, 使用默认的浮动布局 81 JPanel panel02 = new JPanel(); 82 panel02.add(new JLabel("密 码")); 83 panel02.add(new JPasswordField(10)); 84 85 // 第 3 个 JPanel, 使用浮动布局, 并且容器内组件居中显示 86 JPanel panel03 = new JPanel(new FlowLayout(FlowLayout.CENTER)); 87 JButton loginButton = new JButton("登录"); 88 panel03.add(loginButton); 89 panel03.add(new JButton("注册")); 90 91 loginButton.addActionListener(new ActionListener() { 92 93 @Override 94 public void actionPerformed(ActionEvent e) { 95 System.out.println("username=" + username.getText()); 96 } 97 98 }); 99 100 Box vBox = Box.createVerticalBox(); 101 vBox.add(panel01); 102 vBox.add(panel02); 103 vBox.add(panel03); 104 105 jf.setContentPane(vBox); 106 jf.setSize(400, 200); 107 jf.pack(); 108 jf.setLocationRelativeTo(null); 109 jf.setVisible(true); 110 111 } 112 }