1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
| package homeWork;
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener;
public class Test3 extends JFrame {
JPanel j1 = new JPanel(); JLabel name = new JLabel("请输入姓名:"); JTextField t1 = new JTextField("小雪", 10); JPanel j2 = new JPanel(); JLabel sex = new JLabel("性别:"); JRadioButton man = new JRadioButton("男"); JRadioButton woman = new JRadioButton("女"); ButtonGroup g = new ButtonGroup(); JPanel j3 = new JPanel(); JLabel hobby = new JLabel("爱好:"); JCheckBox book = new JCheckBox("读书"); JCheckBox pe = new JCheckBox("体育"); JCheckBox music = new JCheckBox("音乐"); JPanel j4 = new JPanel(); JLabel info1 = new JLabel(""); JLabel info2 = new JLabel(""); JLabel info3 = new JLabel(""); String st1 = ""; String st2 = ""; String st3 = ""; Test3() { super("作业3"); Container con = getContentPane(); con.setLayout(new GridLayout(4, 1));
con.add(j1); con.add(j2); con.add(j3); con.add(j4);
g.add(man); g.add(woman);
j1.add(name); j1.add(t1); j2.add(sex); j2.add(man); j2.add(woman);
j3.add(hobby); j3.add(book); j3.add(pe); j3.add(music); j4.add(info1); j4.add(info2); j4.add(info3);
t1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { info3.setText("姓名: " + t1.getText()); } });
ItemListener item_listener = new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { JCheckBox source = (JCheckBox)e.getSource(); if (source == book) { if (source.isSelected()) st1 = "书籍,"; else st1 = ""; } else if (source == pe) { if (source.isSelected()) st2 = "体育,"; else st2 = ""; } else if (source == music) { if (source.isSelected()) st3 = "音乐"; else st3 = ""; } info2.setText("爱好:"+st1+st2+st3); } }; book.addItemListener(item_listener); pe.addItemListener(item_listener); music.addItemListener(item_listener);
ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JRadioButton source = (JRadioButton)e.getSource(); if (source == man) { info1.setText("性别:男"); } else if (source == woman) { info1.setText("性别:女"); } } }; man.addActionListener(listener); woman.addActionListener(listener);
setVisible(true); setSize(340, 200); setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String[] args) { Test3 f = new Test3(); } }
|