package dongzuo;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
public class Window extends JFrame{
String str;
BorderLayout border;
JPanel P;
JLabel J1,J2;
JCheckBox cb1,cb2,cb3;
ButtonGroup bg;
public JRadioButton jb1;
public JRadioButton jb2;
Box boxh1,boxh2;
JTextArea textarea;
public Window (){}
public Window (String s)
{ init(s);
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setBounds(100, 100, 300, 300);
}
void init(String s){
/*整个界面的布局方式*/
GridLayout grid = new GridLayout(2,1);
setLayout(grid);
setTitle(s);
J1 = new JLabel("兴趣");
J2 = new JLabel("性别");
cb1 = new JCheckBox("羽毛球");
cb2 = new JCheckBox("乒乓球");
cb3 = new JCheckBox("唱歌");
/* JLabel标签,标签文本为“性别”,右边接着是两个JRadioButton按钮,选项分别是“男”、“女”。置成单选按钮*/
bg = new ButtonGroup();
jb1 = new JRadioButton("男");
jb2 = new JRadioButton("女");
bg.add(jb1);
bg.add(jb2);
/*两个盒型容器*/
boxh1 = Box.createHorizontalBox();
boxh2 = Box.createHorizontalBox();
boxh1.add(J1);
boxh1.add(Box.createHorizontalStrut(1));
boxh1.add(cb1);
boxh1.add(cb2);
boxh1.add(cb3);
boxh2.add(J2);
boxh2.add(Box.createHorizontalStrut(1));
boxh2.add(jb1);
boxh2.add(jb2);
/*面板上的折叠布局方式*/
P= new JPanel();
GridLayout grid1 = new GridLayout(2,1);
P.setLayout(grid1);
P.add(boxh1);
P.add(boxh2);
add(P,BorderLayout.NORTH);
/*窗口的CENTER区域放置一个JScrollPane容器,容器中放置一个JTextArea文本域。*/
textarea=new JTextArea();
JScrollPane jp1=new JScrollPane(textarea);
add(jp1,BorderLayout.CENTER);
/*事件*/
JRadioButtonListener lintener1 =new JRadioButtonListener ();//listener1是监听器,事件源是JRadioButton
jb1.addActionListener(lintener1 );
jb2.addActionListener(lintener1);
JCheckBoxListener listener2 = new JCheckBoxListener();//listener2是监听器,事件源是JCheckBox
cb1.addItemListener(listener2);
cb2.addItemListener(listener2);
cb3.addItemListener(listener2);
}
class JRadioButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent arg0)
{
if (arg0.getSource()==jb1) {textarea.append("性别:男"+'\n');}
else if (arg0.getSource()==jb2) {textarea.append("性别:女"+'\n');}
}
}
class JCheckBoxListener implements ItemListener
{
public void itemStateChanged(ItemEvent arg0) {
if(cb1.isSelected()){textarea.append("兴趣:羽毛球"+'\n');}
if(cb2.isSelected()){textarea.append("兴趣:乒乓球"+'\n');}
if(cb3.isSelected()){textarea.append("兴趣:唱歌"+'\n');}
}}
}
package dongzuo;
public class Test {
public static void main(String[] args) {
Window oneview = new Window("浏览器");
}
}
总结:注意区分不同控件的事件处理,找好事件源,事件类型,事件监听器。
学会界面的布局,区分各种布局方式的不同