JButton动作执行了吗? [英] JButton Action Performed?

查看:88
本文介绍了JButton动作执行了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个具有10x10网格的Jframe /按钮。每个jbutton都位于网格之外。我试图影响通过JFrame / button按下的每个按钮,因为我希望最终使其成为战舰游戏。

I have created a Jframe/button with 10x10 grid. Each jbutton is apart of the grid. I am trying to how to affect each button pressed through JFrame/button, as I want to eventually make it into a battleships games.

frame.setLayout(new GridLayout(width,length));
            grid=new JButton[width][length]; 
            for(int y=0; y<length; y++){
                    for(int x=0; x<width; x++){
                            grid[x][y]=new JButton("("+x+","+y+")");     
                            frame.add(grid[x][y]);
                    }
            }

例如,我正在尝试一段基本的代码来看看我是否可以通过单击将Jframe的颜色更改为红色,但似乎不起作用。

For example I am trying a basic piece of code to see if i can change the color of the Jframe to red by clicking it but it doesn't seem to be working.

 public void actionPerformed(ActionEvent e){
           if( e.getSource() instanceof JButton) {
               ((JButton)e.getSource()).setBackground(Color.red);
           }
        }

有人有什么想法吗?

推荐答案

假设我们有一个按钮: JButton按钮。要在按下按钮时调用动作,必须向其添加动作侦听器。有两种方法(我知道):

Let's say we have a button: JButton button. To invoke an action when the button is pressed, an action listener must be added to it. There are two ways of doing this (that I know of):

ActionListener

ActionListener

我认为这比第二个更常用方法。

I think this is more often used than the second method. It's also easier and faster to write IMO:

JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("button was clicked!");
    }
}

动作

Action

另一个动作监听器。功能和用法有些不同。但是,要使按钮的行为类似于 ActionListener ,请执行以下操作:

Another kind of action listener. The functionality and use is somewhat different. However to achieve a button that behaves simarly to an ActionListener, do this:

Action buttonAction = new AbstractAction("Click me") {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("button was clicked!");
    }
}

JButton button = new JButton(action);

请注意,在两个示例中,我都使用匿名的 inner 类,在大多数情况下,使用命名的内部类甚至是外部最好选择l类。

Note that in both examples I'm using anonymous inner classes. In most cases, using a named inner class or even an external class is more preferable.

ActionListener 动作在某种程度上取决于情况(一如既往……叹息),而且恐怕我不能对这个问题透露太多。 Google是您的朋友。快速搜索从SO中提供了该帖子: 链接

Choosing between an ActionListener and an Action depends a little on the situation (as always... sigh), and I'm afraid I cannot shed too much light on this matter. Google is your friend here. A fast search provided this post from SO: link

这篇关于JButton动作执行了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆