Java KeyListener,试图根据按下的键来改变颜色

时间:2014-03-27 01:22:46

标签: java swing jpanel keylistener

这是我第一次时间询问stackoverflow,所以请告诉我我是否做错了。

我正在编写一个实现键监听器的程序,我试图让它根据按下哪个键来改变颜色。 (参见下面的代码)但是,它不会改变颜色,但它仍然记录按键。 我试图测试它的方式是使用'b'键,如代码中所示。 提前谢谢。

import java.awt.*;
import java.awt.event.*;

import javax.swing.JFrame;
import javax.swing.JPanel;

class Spring extends JPanel implements KeyListener {
    private char f = 'a';
    private int a = 0, b = 0, c = 0;
    private Color flower = new Color(a,b,c);

    public Spring() {  //Constructor
        this.setPreferredSize(new Dimension(500, 500));
        addKeyListener(this);
    }

    public void addNotify() { //the focus
        super.addNotify();
        requestFocus();
    }

    public void paintComponent(Graphics g) {
        g.clearRect(0, 0, getWidth(), getHeight()); //clear before next press
        g.drawString("the key that pressed is " + f, 0, 10);
        g.setColor(flower);
        Polygon flowa = new Polygon();
        flowa.addPoint(220,270);
        flowa.addPoint(250,300);
        flowa.addPoint(270,270);
        flowa.addPoint(250,300);
        g.fillPolygon(flowa);
        g.fillRect(250,300,30,30);

    }

    public void keyPressed(KeyEvent e) { }
    public void keyReleased(KeyEvent e) { }
    public void keyTyped(KeyEvent e) { //when key is typed, do something
        f = e.getKeyChar(); //modify value of f
        switch (f){
        case 'a': 
            a = 10;
            b = 10;
            c = 10;
        case 'b': 
            a = 223;
            b = 45;
            c = 45;
            System.out.println("Bals");
        case 'c': 
            a = 10;
            b = 10;
            c = 10;
        case 'd': 
            a = 10;
            b = 10;
            c = 10;
        case 'e': 
            a = 10;
            b = 10;
            c = 10;
        case 'f': 
            a = 10;
            b = 10;
            c = 10;
        case 'g': 
            a = 10;
            b = 10;
            c = 10;
        case 'h': 
            a = 10;
            b = 10;
            c = 10;
        case 'i': 
            a = 10;
            b = 10;
            c = 10;
        case 'j': 
            a = 10;
            b = 10;
            c = 10;
        case 'k': 
            a = 10;
            b = 10;
            c = 10;
        case 'l': 
            a = 10;
            b = 10;
            c = 10;
        case 'm': 
            a = 10;
            b = 10;
            c = 10;
        }
        repaint();
    }

    public static void main(String[] s) { //main method, creates the frame
        JFrame f = new JFrame();
        f.getContentPane().add(new Spring());
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }
}

2 个答案:

答案 0 :(得分:2)

您只需设置变量abc。更改这些变量不会更改flower使用的数字,因为flower正在使用您传入的数字,而不是您正在使用的变量。

您需要在每个实例中创建一个新的Color对象,如下所示:

flower = new Color(20, 230, 210);

另外,不要忘记在案例之间添加break;行;否则,您的flower对象将是您上次列出的颜色。

此外,您可能希望使用KeyAdapter类的实现,它允许您仅定义要使用的方法而不是所有方法,而不是拥有自己的类KeyListener

答案 1 :(得分:1)

saiarcot895答案是正确的,因为它解决了手头的问题(+1)。这是使用Key Bindings API

实现目标的示例

KeyListener对于监控关键事件通常是一个糟糕的选择,因为它会遇到与您正在尝试解决的焦点相关的问题,但无法工作。

更好的解决方案是使用Key Bindings API,它可以让您配置触发关键事件的焦点级别。

您将遇到的问题是您需要使用大量可能的击键。为此,我只使用Map将关键代码映射到用于设置所需颜色的Action

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Spring extends JPanel {

    private Color flower = Color.BLACK;
    private String key;

    public Spring() {
        Map<Integer, ColorAction> mapColors = new HashMap<>(25);
        mapColors.put(KeyEvent.VK_F, new ColorAction(this, "F", new Color(10, 10, 10)));
        mapColors.put(KeyEvent.VK_B, new ColorAction(this, "B", new Color(223, 45, 45)));

        InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
        ActionMap am = getActionMap();

        for (Integer keyCode : mapColors.keySet()) {

            KeyStroke ks = KeyStroke.getKeyStroke(keyCode, 0);
            im.put(ks, ks);
            am.put(ks, mapColors.get(keyCode));

        }
    }

    public void update(String ks, Color color) {
        flower = color;
        key = ks;
        repaint();
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(500, 500);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawString("the key that pressed is " + key, 0, 10);
        g.setColor(flower);
        Polygon flowa = new Polygon();
        flowa.addPoint(220, 270);
        flowa.addPoint(250, 300);
        flowa.addPoint(270, 270);
        flowa.addPoint(250, 300);
        g.fillPolygon(flowa);
        g.fillRect(250, 300, 30, 30);

    }

    public static void main(String[] s) { //main method, creates the frame
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame f = new JFrame();
                f.getContentPane().add(new Spring());
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.pack();
                f.setVisible(true);
            }
        });
    }

    public class ColorAction extends AbstractAction {

        private Spring spring;
        private String key;
        private Color color;

        private ColorAction(Spring spring, String ks, Color color) {
            this.spring = spring;
            this.key = ks;
            this.color = color;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            spring.update(key, color);
        }

    }
}

如果您觉得有用,欢迎投票,但saiarcot895答案应保持标记为正确