ActionListener ItemListener 和几个SWING组件的练习

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);
     }             
 }
 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值