【问题标题】:buttons in java, creating and using action listeners [closed]java中的按钮,创建和使用动作监听器[关闭]
【发布时间】:2013-04-25 19:11:08
【问题描述】:

我对 Eclipse 真的很陌生,我是第一次创建按钮。我想我有基本的想法,但它不起作用。您可以在我的代码的任何部分添加的任何内容都非常有用。帮助!这是我的代码:

import java.applet.Applet; 
import java.awt.*; 
import java.awt.event.*; 

public class MovingBox extends Applet 
{
  Thread thread; 
  Dimension dim; 
  Image img; 
  Graphics g; 
  Color red = null;
  Color blue = null;
  Font fnt16P = null;


  public void init()
  { 
    resize(800,500);    


    Button b_Up = new Button("Up"); 
    b_Up.setSize(100, 25);
    b_Up.setLocation(450,450+ 90);
    b_Up.setBackground(red); 
    b_Up.setForeground(blue);
    b_Up.setFont(fnt16P);
    b_Up.setVisible(true);
    b_Up.addActionListener((ActionListener) this);
    add(b_Up);


  }

  public void paint(Graphics gfx)
  {
    g.setColor(Color.green);
    g.fillRect(0,0,800,500);
  }
  public void actionPerformed(ActionEvent event)
  {
    int value, total;;
    Object cause = event.getSource();

    if (cause == b_Up)
    (
    )

  }

}

【问题讨论】:

  • 您当前的代码有什么问题?您还需要在if (cause == b_Up) 之后将() 替换为{}
  • 你遇到了什么错误?

标签: java eclipse swing applet radio-button


【解决方案1】:

不要定义图形对象。使用传递给该方法的 Graphics 对象。

Graphics g; 
...
public void paint(Graphics gfx)
  {
    g.setColor(Color.green);
    g.fillRect(0,0,800,500);
  }

不要手动设置大小/位置。使用布局管理器,让布局管理器完成其工作。

Button b_Up = new Button("Up"); 
b_Up.setSize(100, 25);
b_Up.setLocation(450,450+ 90);

我建议你花时间学习如何使用 Swing 而不是学习 AWT。从Swing tutorial 开始了解基础知识。

【讨论】:

    【解决方案2】:

    由于 3 个原因,此代码无法编译:

    变量b_UpactionPerformed 中不可见。使其成为一个类成员变量,使其工作并将其声明为

    b_Up = new Button("Up"); 
    

    您不能将this 注册为ActionListener

    b_Up.addActionListener(this);
    

    除非该类属于该类型,因此该类需要声明为

    public class MovingBox extends Applet implements ActionListener {
    

    使用大括号而不是括号来定义if 语句的主体:

    if (cause == b_Up) {
       ...
    }
    

    考虑使用以下方法:

    • 对组件使用匿名ActionListener。更好的实施方法
    • private 类成员变量 - 一定要使用这些
    • Java 命名约定推荐 camelCase 而不是匈牙利表示法
    • 考虑使用更现代的轻量级 Swing 库而不是重量级 AWT,

    【讨论】:

      猜你喜欢
      • 2013-12-24
      • 1970-01-01
      • 2020-08-26
      • 2017-03-08
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      相关资源
      最近更新 更多