+ -
当前位置:首页 → 问答吧 → 请问有关Button建在Panel上,如何处理Button的事件?

请问有关Button建在Panel上,如何处理Button的事件?

时间:2011-09-29

来源:互联网

如我们写一个计算机程式如下...

只是处理其中任一个按钮的事件...

但似乎都没有反应...我猜想是建在Panel上的Button,在处理事件上的方法不对?

请大家多多指教..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.awt.*;
import java.awt.event.*;
 
public class app17_18{
    static Frame frm = new Frame("Panel class");
    static Panel pnl = new Panel(new GridLayout(3,3));
   static Label lab = new Label("0.",Label.RIGHT);
    
  public static void main(String[] args){
    frm.setLayout(null);
    frm.setSize(200,150);
    frm.setResizable(false);
    lab.setBounds(20,30,120,20);
      lab.setBackground(Color.yellow);
      pnl.setBounds(20,60,120,80);
   for(int i=1;i<=9;i++){
     pnl.add(new Button(Integer.toString(i)));
     new Button(Integer.toString(i)).addActionListener(new ActLis());
   }
   frm.add(lab);
   frm.add(pnl);
   frm.setVisible(true);
  }
  
  static class ActLis implements ActionListener{
    public void actionPerformed(ActionEvent e){
      Button btn = (Button)e.getSource();
      if(btn == new Button("1"))
        lab.setText("1");
    }
  }
    
  
}

作者: jackyp0210   发布时间: 2011-09-29

if(btn == new Button("1")) {
lab.setText("1");
}
一个既有的 Button 怎么会等於一个刚 new 出来的?
先不论其它,

作者: ddtet   发布时间: 2011-09-29

jackyp0210 wrote:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.awt.*;
import java.awt.event.*;
 
public class app17_18{
  static Frame frm = new Frame();
  static Panel pnl = new Panel(new GridLayout(3, 3));
  static Label lab = new Label("0.", Label.RIGHT);
 
  public static void main(String[] args) {
    frm.setLayout(null);
    frm.setSize(200, 150);
    frm.setResizable(false);
    lab.setBounds(20, 30, 120, 20);
 
    lab.setBackground(Color.yellow);
 
    pnl.setBounds(20, 60, 120, 80);
    for(int i=1;i<=9;i++){
      Button btn =null;
   pnl.add(btn=new Button(Integer.toString(i)));
   btn.addActionListener(new ActLis());
   }
    frm.add(lab);
    frm.add(pnl);
    frm.setVisible(true);
  }
 
  static class ActLis implements ActionListener{
   public void actionPerformed(ActionEvent e){
   Button btn = (Button)e.getSource();
   System.out.println(btn.getLabel());
   if(btn.getLabel().equals("1"))
   lab.setText("1");
   }
   }
}


我做了部份修改,
再试试是不是你要的结果,
有问题再提出来呗…

作者: sayNever   发布时间: 2011-09-29

热门下载

更多