第十二週Java作業

主要代碼:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class PersonalInformation extends JFrame{
    JPanel pl;
    JLabel lbl1, lbl2;
    JCheckBox cb1, cb2, cb3;
    ButtonGroup bg;
    JRadioButton rb1, rb2;
    JScrollPane sp;
    JTextArea ta;
    public PersonalInformation(){
        super("PersonalInformation");
        Listener1 l1 = new Listener1();
        lbl1=new JLabel("興趣");
        cb1 = new JCheckBox("羽毛球");
        cb1.addItemListener(l1);
        cb2 = new JCheckBox("乒乓球");
        cb2.addItemListener(l1);
        cb3 = new JCheckBox("唱歌");
        cb3.addItemListener(l1);
        Box boxH1 = Box.createHorizontalBox();
        boxH1.add(Box.createHorizontalStrut(5));
        boxH1.add(lbl1);
        boxH1.add(Box.createHorizontalStrut(50));
        boxH1.add(cb1);
        boxH1.add(Box.createHorizontalStrut(5));
        boxH1.add(cb2);
        boxH1.add(Box.createHorizontalStrut(5));
        boxH1.add(cb3);

        Listener2 l2 = new Listener2();
        lbl2=new JLabel("性別");
        bg = new ButtonGroup();
        rb1 = new JRadioButton("男");
        rb1.addActionListener(l2);
        rb2 = new JRadioButton("女");
        rb2.addActionListener(l2);
        bg.add(rb1);
        bg.add(rb2);
        Box boxH2 = Box.createHorizontalBox();
        boxH2.add(Box.createHorizontalStrut(5));
        boxH2.add(lbl2);
        boxH2.add(Box.createHorizontalStrut(50));
        boxH2.add(rb1);
        boxH2.add(Box.createHorizontalStrut(5));
        boxH2.add(rb2);

        pl = new JPanel();
        pl.setLayout(new GridLayout(2,1));
        pl.add(boxH1);
        pl.add(boxH2);

        ta = new JTextArea(200, 300);
        sp = new JScrollPane(ta);

        Container contentPane = getContentPane();
        contentPane.add(pl, BorderLayout.NORTH);
        contentPane.add(sp, BorderLayout.CENTER);

        setSize(400,300);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

    }

    public static void main(String args[]){
        new PersonalInformation();
    }

    class Listener1 implements ItemListener{
        public void itemStateChanged(ItemEvent e){
            if(e.getSource()==cb1)
                ta.append(cb1.getText()+"\n");
            else if(e.getSource()==cb2)
                ta.append(cb2.getText()+"\n");
            else if(e.getSource()==cb3)
                ta.append(cb3.getText()+"\n");
        }
    }

    class Listener2 implements ActionListener{
        public void actionPerformed(ActionEvent e){
            if(e.getSource()==rb1)
                ta.append(rb1.getText()+"\n");
            else if(e.getSource()==rb2)
                ta.append(rb2.getText()+"\n");

        }
    }

}

演示效果圖:

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章