JTextfiled类中,给文本框添加监听事件,使用的方法是addActionListener(this),注意里面的参数。注意要实现ActionListener的接口。
public void actionPerformed(ActionEvent e) {
setTitle(jTextField.getText());
jTextField.setText("");
repaint();
}
JcheckBox类的监听事件,复选框被选中或是取消触发事件时,时间由itemStateChaged()处理,在处理的时候,封装一个ItemEvent对象给监听器,通过该对象的getItem方法产生事件的复选框。程序需要implements ItemListener。程序主要代码:
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
JCheckBox checkBox=(JCheckBox)e.getItem();
if(e.getStateChange()==ItemEvent.SELECTED){
jl.setText(checkBox.getText());//以便于选择了的都可以显示,而不是清空所有。
}
}
JRadio类的事件需要实现ActionListener接口,如果单选按钮实现只选一个,需要把他们放到ButtonGroup中。getActionCommand()方法返回的是字符串String对象。
ButtonGroup bg=new ButtonGroup();
bg.add(cb1);
bg.add(cb2);
bg.add(cb3);
......
public void actionPerformed(ActionEvent e)
{
jl.setText(e.getActionCommand());
}
JComboBox中,创建JCombBox对象,用addItem方法添加列表选项。程序也需要implements ItemListener:
public void itemStateChanged(ItemEvent e)
{
jl.setText((String)e.getItem());
}
JtabbedPane类,组件选项卡。可能会需要创建多个面板。
首先创建此类的对象
JTabbedPane jtp=new JTabbedPane();
然后添加面板(肯定是已经创建好的面板类了)
JPanel buttonjp=new JPanel();
buttonjp.add(new JButton("button1"));
buttonjp.add(new JButton("button2"));
buttonjp.add(new JButton("button2"));
JPanel paneljp=new JPanel();
paneljp.add(new JLabel("JLabel1"));
paneljp.add(new JLabel("JLabel2"));
paneljp.add(new JLabel("JLabel2"));
jtp.addTab("JButton",buttonjp);
jtp.addTab("JLabel", paneljp);
jtp.addTab("More", null);
swing中还会有滚动条、滑动条、树等的控件,多练习,并且尽量减少代码之间的耦合度,要不然看着很头大的,以后尽量放弃RCP