Java-使用KeyListener的程序无法正常工作 [英] Java - Program with KeyListener isn't working

查看:112
本文介绍了Java-使用KeyListener的程序无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

主要问题:当我使用KeyListener创建挪威计算器时,它无法正常工作.

Main problem: When I created a norwegian calculator using the KeyListener, it didn't work properly.

我已经添加了对JFrame的addKeyListener()方法的调用,并且已经实现了KeyListener接口以及所有其他内容.但这仍然行不通.我为糟糕的代码表示歉意.

I've added a call to the JFrame's addKeyListener() method and I've implemented the KeyListener interface and everything. But it still doesn't work. I apologize for poor code.

感谢您的帮助.预先感谢.

Any help is appreciated. Thanks in advance.

代码:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;  
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;


public class miniräknare extends JFrame implements KeyListener {
public static int answer = 0;
public JLabel lblRandomnum;
public static int answer2 = 0;
public static boolean flip = true;
public static JLabel lblOutput;
Random myRandom = new Random();
/**
 * 
 */
private static final long serialVersionUID = 1L;
/**
 * Launch the application.
 */
public static void main(String[] args) {
    new miniräknare();

}


public miniräknare() {

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 300, 600);
    setResizable(false);
    getContentPane().setLayout(null);
    lblOutput = new JLabel("" + answer);
    lblOutput.setBounds(35, 33, 222, 37);
    getContentPane().add(lblOutput);
    JButton button = new JButton("1");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        increment(1);
        lblRandomnum.setText("");
        }
    });
    button.setBounds(35, 111, 75, 75);
    getContentPane().add(button);

    JButton button_1 = new JButton("2");
    button_1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            increment(2);
            lblRandomnum.setText("");
        }
    });
    button_1.setBounds(109, 111, 75, 75);
    getContentPane().add(button_1);

    JButton button_2 = new JButton("3");
    button_2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            increment(3);
            lblRandomnum.setText("");
        }
    });
    button_2.setBounds(182, 111, 75, 75);
    getContentPane().add(button_2);

    JButton button_3 = new JButton("4");
    button_3.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            increment(4);
            lblRandomnum.setText("");
        }
    });
    button_3.setBounds(35, 184, 75, 75);
    getContentPane().add(button_3);

    JButton button_4 = new JButton("5");
    button_4.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            increment(5);
            lblRandomnum.setText("");
        }
    });
    button_4.setBounds(109, 184, 75, 75);
    getContentPane().add(button_4);

    JButton button_5 = new JButton("6");
    button_5.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        increment(6);
        lblRandomnum.setText("");
        }
    });
    button_5.setBounds(182, 184, 75, 75);
    getContentPane().add(button_5);

    JButton button_6 = new JButton("7");
    button_6.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            increment(7);
            lblRandomnum.setText("");
        }
    });
    button_6.setBounds(35, 257, 75, 75);
    getContentPane().add(button_6);

    JButton button_7 = new JButton("8");
    button_7.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            increment(8);
            lblRandomnum.setText("");
        }
    });
    button_7.setBounds(109, 257, 75, 75);
    getContentPane().add(button_7);

    JButton button_8 = new JButton("0");
    button_8.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            increment(0);
            lblRandomnum.setText("");
        }
    });
    button_8.setBounds(109, 331, 75, 75);
    getContentPane().add(button_8);

    JButton button_9 = new JButton("9");
    button_9.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            increment(9);
            lblRandomnum.setText("");
        }
    });
    button_9.setBounds(182, 257, 75, 75);
    getContentPane().add(button_9);

    JButton btnC = new JButton("C");
    btnC.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            answer = 0;
            answer2 = 0;
            flip = true;
            lblOutput.setText("" + answer);
            lblRandomnum.setText("");
        }
    });
    btnC.setBounds(35, 331, 75, 75);
    getContentPane().add(btnC);

    JButton button_10 = new JButton("=");
    button_10.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        lblOutput.setText("tänker.........");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lblOutput.setText("Detta tal är för advancerat :-(");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lblRandomnum.setText("Men, jag tror det blir " + myRandom.nextInt(100000));
        }
    });
    button_10.setBounds(182, 331, 75, 75);
    getContentPane().add(button_10);

    JButton button_11 = new JButton("+");
    button_11.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            if((lblOutput.getText().endsWith("+")) || (lblOutput.getText().endsWith("-")) || (lblOutput.getText().endsWith("x")) || (lblOutput.getText().endsWith("%"))) {
                lblOutput.setText("" + answer + "+");
            }
            else lblOutput.setText(lblOutput.getText() + "+");
            if(flip) {
                lblOutput.setText("+");
                flip = false;
            }
            else if(!flip) {
                flip = true;
            }
        }
    });
    button_11.setBounds(35, 405, 75, 75);
    getContentPane().add(button_11);

    JButton button_12 = new JButton("-");
    button_12.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            if((lblOutput.getText().endsWith("+")) || (lblOutput.getText().endsWith("-")) || (lblOutput.getText().endsWith("x")) || (lblOutput.getText().endsWith("%"))) {
                lblOutput.setText("" + answer + "-");
            }
            else lblOutput.setText(lblOutput.getText() + "-");
            if(flip) {
                lblOutput.setText("-");
                flip = false;
            }
            else if(!flip) {
                flip = true;
            }
        }
    });
    button_12.setBounds(109, 405, 75, 75);
    getContentPane().add(button_12);

    JButton btnX = new JButton("X");
    btnX.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            if((lblOutput.getText().endsWith("+")) || (lblOutput.getText().endsWith("-")) || (lblOutput.getText().endsWith("x")) || (lblOutput.getText().endsWith("%"))) {
                lblOutput.setText("" + answer + "x");
            }
            else lblOutput.setText(lblOutput.getText() + "x");
            if(flip) {
                lblOutput.setText("x");
                flip = false;
            }
            else if(!flip) {
                flip = true;
            }
        }
    });
    btnX.setBounds(182, 405, 75, 75);
    getContentPane().add(btnX);

    JButton button_13 = new JButton("%");
    button_13.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            if((lblOutput.getText().endsWith("+")) || (lblOutput.getText().endsWith("-")) || (lblOutput.getText().endsWith("x")) || (lblOutput.getText().endsWith("%"))) {
                lblOutput.setText("" + answer + "%");
            }
            else lblOutput.setText(lblOutput.getText() + "%");
            if(flip) {
                lblOutput.setText("%");
                flip = false;
            }
            else if(!flip) {
                flip = true;
            }
        }
    });
    button_13.setBounds(109, 479, 75, 75);
    getContentPane().add(button_13);

    lblRandomnum = new JLabel("randomnum");
    lblRandomnum.setBounds(45, 82, 212, 16);
    getContentPane().add(lblRandomnum);
    lblRandomnum.setText("");
    setVisible(true);
    setTitle("norsk miniräknare");
    addKeyListener(this);
}

public static void increment(int i) {
    if(flip) {
    String s = "" + answer;
    StringBuilder str = new StringBuilder(s);
    if(s.startsWith("0")) {
        answer = i;
    } else {
    str.insert(s.length(), "" + i);
    s = str.toString(); 

    if(s.length() != 10) answer = Integer.parseInt(s);
    }
    lblOutput.setText("" + answer);
    }
    if(!flip) {
        String s = "" + answer2;
        StringBuilder str = new StringBuilder(s);
        if(s.startsWith("0")) {
            answer2 = i;
        } else {
        str.insert(s.length(), "" + i);
        s = str.toString();
        answer2 = Integer.parseInt(s);
        }
        lblOutput.setText("" + answer2);
        }
}


@Override
public void keyPressed(KeyEvent e) {
    System.out.println("lol");
    int KeyCode = e.getKeyCode();
    if(KeyCode == KeyEvent.VK_0) increment(0);
    if(KeyCode == KeyEvent.VK_1) increment(1);
    if(KeyCode == KeyEvent.VK_2) increment(2);
    if(KeyCode == KeyEvent.VK_3) increment(3);
    if(KeyCode == KeyEvent.VK_4) increment(4);
    if(KeyCode == KeyEvent.VK_5) increment(5);
    if(KeyCode == KeyEvent.VK_6) increment(6);
    if(KeyCode == KeyEvent.VK_7) increment(7);
    if(KeyCode == KeyEvent.VK_8) increment(8);
    if(KeyCode == KeyEvent.VK_9) increment(9);
}


@Override
public void keyReleased(KeyEvent e) {
    System.out.println("trololol");

}


@Override
public void keyTyped(KeyEvent e) {
    System.out.println("ofta");
}
}

推荐答案

不要将KeyListener添加到JFrame.只有将KeyListener添加到具有焦点的组件中,并且该组件几乎不是JFrame时,KeyListener才起作用.实际上,对于Swing应用程序,应该避免完全使用KeyListeners,而应使用Key Bindings,因为它们可以解决焦点问题并允许您使用可重复使用的Actions.

Don't add a KeyListener to a JFrame. KeyListeners only work if they are added to a component that has focus, and that is hardly ever the JFrame. In fact with Swing applications, you should avoid using KeyListeners altogether and instead use Key Bindings since these get around the focus problem and allow you to use re-usable Actions.

请查看密钥绑定"教程:此处.

Please check out the Key Bindings tutorial: here.

顺便说一句:您不应该使用null布局和设置边界,因为它会使调试和扩展程序变得非常困难.相反,可以考虑使用布局管理器将一组JButton放置到GUI中. GridLayout对于容纳您的JButton的JPanel会很好地工作.

Also as an aside: you shouldn't be using null layout and set bounds as it makes for a very difficult program to debug and extend. Instead consider using an array of JButtons placed into your GUI using layout managers. A GridLayout would work well for the JPanel that holds your JButtons.

这篇关于Java-使用KeyListener的程序无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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