您的位置:首页 > 其它

ActionListener ItemListener 和几个SWING组件的练习

2006-01-11 15:25 274 查看
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class TestAction extends JFrame implements ItemListener,ActionListener{
String newline = "/n";
JPanel panel = new JPanel(new BorderLayout());
JMenuBar menubar = new JMenuBar();
JTextArea textarea = new JTextArea(5,20);
JToolBar toolbar = new JToolBar();
JScrollPane scrollpane = new JScrollPane(textarea);
public TestAction(){
//构造函数,创建主窗口
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.getContentPane().add(scrollpane,BorderLayout.CENTER);
this.getContentPane().add(menubar,BorderLayout.NORTH);
this.getMenuBar(menubar);
this.pack();
this.setVisible(true);
textarea.setEditable(false);
}
public static void main(String[] args){
//main主函数
TestAction ian = new TestAction();
}
public void drawButton(String name){
//按钮
JButton button = new JButton(name);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
//实现ActionListener接口,退出的Item
System.exit(0);
}
public void itemStateChanged(ItemEvent e){
//实现ItemListener接口,想textarea添加CheckBoxMenuItem的信息,包括名称和state
JMenuItem source = (JMenuItem)(e.getSource());
String s = "actionPerformed"+
newline
+source.getText()
+newline
+source.isSelected();
textarea.append(s+newline);
//textarea.setCaretPosition(output.getDocument().getLength());
}
public void getMenuBar(JMenuBar bar){
//绘制MenuBar的函数
JMenu open = new JMenu("open");
JMenuItem close = new JMenuItem("close");
close.addActionListener(this);
JCheckBoxMenuItem[] checkbox = new JCheckBoxMenuItem[4];
JMenu menu2 = new JMenu("submenu");
for(int i = 0;i<checkbox.length;i++){
//向subMenuBar中添加Item
checkbox[i] = new JCheckBoxMenuItem("NO."+i);
checkbox[i].addItemListener(this);
menu2.add(checkbox[i]);
}
bar.add(open);
bar.add(close);
open.add(menu2);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: