键入按钮时,JButton不会更改颜色 [英] JButton does not change color when button is typed

查看:126
本文介绍了键入按钮时,JButton不会更改颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常小的问题.现在,我编写了用于创建虚拟键盘的代码.我希望在键入按钮时更改其颜色.这是我的代码:

I have a very small question. Now I wrote the code for creating a virtual keyboard. I want the color of the button to change when it is typed. Here is my code:

public class ButtonColor implements KeyListener {

    @Override
    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyTyped(KeyEvent e) {
        if (e.getKeyChar()=='a') {
            A.setBackground(Color.red);
        }

    }

}

]

每当我按A时,都不会发生任何反应.当我添加此行时:

Whenever I press A, nothing happens. When I add this line:

JOptionPane.showMessageDialog(null, "A was typed");

然后键入a,出现消息,然后单击确定",按钮将更改颜色.为什么会这样呢?我该如何解决这个问题?

then type a, the message appears and after I click OK the button changes color. Why does that happen? How can I fix this problem?

推荐答案

对您不起作用的原因有很多,对于初学者而言,按钮可能是透明的(opaque == false)

There could be any number of reasons why this doesn't work for you, for starters, the button may be transparent (opaque == false)

我强烈建议反对KeyListener,而推荐使用键绑定,因为KeyListener存在焦点问题...

I would strongly recommend against KeyListener in favour of Key Bindings as KeyListener has issues with focus...

例如...

以下使用按键绑定API来响应给定的按键,具体取决于它是按键按下还是释放事件,它将相应地设置背景颜色和不透明度状态,甚至设置按钮按下状态.

The following uses the key bindings API in order to respond to a given key stroke, depending on if it's a key press or release event, it will set the background color and opacity state accordingly and even sets the buttons pressed state...

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class KeyboardTest {

    public static void main(String[] args) {
        new KeyboardTest();
    }

    public KeyboardTest() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            JButton btnA = createButton("A");
            JButton btnB = createButton("B");
            JButton btnC = createButton("C");
            JButton btnD = createButton("D");
            JButton btnE = createButton("E");

            add(btnA);
            add(btnB);
            add(btnC);
            add(btnD);
            add(btnE);

            addKeyBinding(btnA, "A", KeyEvent.VK_A);
            addKeyBinding(btnB, "B", KeyEvent.VK_B);
            addKeyBinding(btnC, "C", KeyEvent.VK_C);
            addKeyBinding(btnD, "D", KeyEvent.VK_D);
            addKeyBinding(btnE, "E", KeyEvent.VK_E);

        }

        protected JButton createButton(String text) {
            JButton btn = new JButton(text);
            btn.setFocusable(false);
            return btn;
        }

        protected void addKeyBinding(JButton btn, String name, int virtualKey) {
            ActionMap am = getActionMap();
            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);

            im.put(KeyStroke.getKeyStroke(virtualKey, 0, false), name + ".pressed");
            im.put(KeyStroke.getKeyStroke(virtualKey, 0, true), name + ".released");

            am.put(name + ".pressed", new KeyAction(btn, true));
            am.put(name + ".released", new KeyAction(btn, false));
        }

    }

    public class KeyAction extends AbstractAction {

        private JButton btn;
        private boolean highlight;

        public KeyAction(JButton btn, boolean highlight) {
            this.btn = btn;
            this.highlight = highlight;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (highlight) {
                btn.getModel().setPressed(true);
                btn.setBackground(Color.RED);
                btn.setOpaque(true);
            } else {
                btn.getModel().setPressed(false);
                btn.setBackground(null);
                btn.setOpaque(false);
            }
        }

    }

}

已更新

如果您还使用btn.getModel().setArmed(...);,您将获得更多的增强"响应,从而产生更好的视觉反馈...恕我直言

If you also use btn.getModel().setArmed(...); you will get a much more "bolded" response, which produces better visual feedback...IMHO

这篇关于键入按钮时,JButton不会更改颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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