具有按键响应的Java计算器

具有按键响应的Java计算器,java,swing,Java,Swing,所以我写了这个剧本;这是我找到并拼凑起来的计算器的一个大杂烩 keylister来自Java-oracle-.com网站。顺便说一句,我对这一点非常陌生,不知道我在做什么 我试图使用keylister来允许击键使计算器工作,这样就不必点击输入;当前脚本已编译,但无法在中键入输入。。。我做得对吗 import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.awt.BorderLayout; import

所以我写了这个剧本;这是我找到并拼凑起来的计算器的一个大杂烩

keylister
来自Java-oracle-.com网站。顺便说一句,我对这一点非常陌生,不知道我在做什么

我试图使用
keylister
来允许击键使计算器工作,这样就不必点击输入;当前脚本已编译,但无法在中键入输入。。。我做得对吗

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;

public class Calculator extends JFrame implements KeyListener, ActionListener {

JPanel[] row = new JPanel[5];
JButton[] button = new JButton[19];
String[] buttonstring = {"7", "8", "9", "+",
                         "4", "5", "6", "-",
                         "1", "2", "3", "*",
                         ".", "/", "C", "SR",
                         "+/-", "=", "0"};
int[] dimW = {300,45,100,90};
int[] dimH = {35, 40};
Dimension displayDimension = new Dimension(dimW[0], dimH[0]);
Dimension regularDimension = new Dimension(dimW[1], dimH[1]);
Dimension rColumnDimension = new Dimension(dimW[2], dimH[1]);
Dimension zeroButDimension = new Dimension(dimW[3], dimH[1]);
boolean[] function = new boolean[4];
double[] temporary = {0, 0};
JTextArea display = new JTextArea(1,20);

Font font = new Font("Times new Roman", Font.BOLD, 14);
JTextArea displayArea;
JTextField typingArea;
static final String newline = System.getProperty("line.separator");

    //Uncomment this if you wish to turn off focus
    //traversal.  The focus subsystem consumes
    //focus traversal keys, such as Tab and Shift Tab.
    //If you uncomment the following line of code, this
    //disables focus traversal and the Tab events will
    //become available to the key event listener.
    //typingArea.setFocusTraversalKeysEnabled(false);


Calculator() {
    super("Calculator");
    setDesign();
    setSize(380, 250);
    setResizable(false);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    GridLayout grid = new GridLayout(5,5);
    setLayout(grid);

    for(int i = 0; i < 4; i++)
        function[i] = false;

    FlowLayout f1 = new FlowLayout(FlowLayout.CENTER);
    FlowLayout f2 = new FlowLayout(FlowLayout.CENTER,1,1);
    for(int i = 0; i < 5; i++)
        row[i] = new JPanel();
    row[0].setLayout(f1);
    for(int i = 1; i < 5; i++)
        row[i].setLayout(f2);

    for(int i = 0; i < 19; i++) {
        button[i] = new JButton();
        button[i].setText(buttonstring[i]);
        button[i].setFont(font);
        button[i].addActionListener(this);
    }

    display.setFont(font);
    display.setEditable(false);
    display.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    display.setPreferredSize(displayDimension);
    for(int i = 0; i < 14; i++)
        button[i].setPreferredSize(regularDimension);
    for(int i = 14; i < 18; i++)
        button[i].setPreferredSize(rColumnDimension);
    button[18].setPreferredSize(zeroButDimension);

    row[0].add(display);
    add(row[0]);

    for(int i = 0; i < 4; i++)
        row[1].add(button[i]);
    row[1].add(button[14]);
    add(row[1]);

    for(int i = 4; i < 8; i++)
        row[2].add(button[i]);
    row[2].add(button[15]);
    add(row[2]);

    for(int i = 8; i < 12; i++)
        row[3].add(button[i]);
    row[3].add(button[16]);
    add(row[3]);

    row[4].add(button[18]);
    for(int i = 12; i < 14; i++)
        row[4].add(button[i]);
    row[4].add(button[17]);
    add(row[4]);

    setVisible(true);
}



public void clear() {
    try {
        display.setText("");
        for(int i = 0; i < 4; i++)
            function[i] = false;
        for(int i = 0; i < 2; i++)
            temporary[i] = 0;
    } catch(NullPointerException e) {  
    }
}

public void getSqrt() {
    try {
        double value = Math.sqrt(Double.parseDouble(display.getText()));
        display.setText(Double.toString(value));
    } catch(NumberFormatException e) {
    }
}

public void getPosNeg() {
    try {
        double value = Double.parseDouble(display.getText());
        if(value != 0) {
            value = value * (-1);
            display.setText(Double.toString(value));
        }
        else {
        }
    } catch(NumberFormatException e) {
    }
}

public void getResult() {
    double result = 0;
    temporary[1] = Double.parseDouble(display.getText());
    String temp0 = Double.toString(temporary[0]);
    String temp1 = Double.toString(temporary[1]);
    try {
        if(temp0.contains("-")) {
            String[] temp00 = temp0.split("-", 2);
            temporary[0] = (Double.parseDouble(temp00[1]) * -1);
        }
        if(temp1.contains("-")) {
            String[] temp11 = temp1.split("-", 2);
            temporary[1] = (Double.parseDouble(temp11[1]) * -1);
        }
    } catch(ArrayIndexOutOfBoundsException e) {
    }
    try {
        if(function[2] == true)
            result = temporary[0] * temporary[1];
        else if(function[3] == true)
            result = temporary[0] / temporary[1];
        else if(function[0] == true)
            result = temporary[0] + temporary[1];
        else if(function[1] == true)
            result = temporary[0] - temporary[1];
        display.setText(Double.toString(result));
        for(int i = 0; i < 4; i++)
            function[i] = false;
    } catch(NumberFormatException e) {
    }
}

public final void setDesign() {
    try {
        UIManager.setLookAndFeel(
                "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
    } catch(Exception e) {   
    }
}

@Override
public void actionPerformed(ActionEvent ae) {
    if(ae.getSource() == button[0])
        display.append("7");
    if(ae.getSource() == button[1])
        display.append("8");
    if(ae.getSource() == button[2])
        display.append("9");
    if(ae.getSource() == button[3]) {
        //add function[0]
        temporary[0] = Double.parseDouble(display.getText());
        function[0] = true;
        display.setText("");
    }
    if(ae.getSource() == button[4])
        display.append("4");
    if(ae.getSource() == button[5])
        display.append("5");
    if(ae.getSource() == button[6])
        display.append("6");
    if(ae.getSource() == button[7]) {
        //subtract function[1]
        temporary[0] = Double.parseDouble(display.getText());
        function[1] = true;
        display.setText("");
    }
    if(ae.getSource() == button[8])
        display.append("1");
    if(ae.getSource() == button[9])
        display.append("2");
    if(ae.getSource() == button[10])
        display.append("3");
    if(ae.getSource() == button[11]) {
        //multiply function[2]
        temporary[0] = Double.parseDouble(display.getText());
        function[2] = true;
        display.setText("");
    }
    if(ae.getSource() == button[12])
        display.append(".");
    if(ae.getSource() == button[13]) {
        //divide function[3]
        temporary[0] = Double.parseDouble(display.getText());
        function[3] = true;
        display.setText("");
    }
    if(ae.getSource() == button[14])
        clear();
    if(ae.getSource() == button[15])
        getSqrt();
    if(ae.getSource() == button[16])
        getPosNeg();
    if(ae.getSource() == button[17])
        getResult();
    if(ae.getSource() == button[18])
        display.append("0");
}

public void contentPane() {
 typingArea = new JTextField(20);
    typingArea.addKeyListener(this);
   displayArea = new JTextArea();
       displayArea.setEditable(false);
       JScrollPane scrollPane = new JScrollPane(displayArea);
       scrollPane.setPreferredSize(new Dimension(375, 125));

       getContentPane().add(typingArea, BorderLayout.PAGE_START);  
       getContentPane().add(scrollPane, BorderLayout.CENTER); 


}

public void keyTyped(KeyEvent e) {
    displayInfo(e, "KEY TYPED: ");
}

/** Handle the key pressed event from the text field. */
public void keyPressed(KeyEvent e) {
    displayInfo(e, "KEY PRESSED: ");
}

/** Handle the key released event from the text field. */
public void keyReleased(KeyEvent e) {
    displayInfo(e, "KEY RELEASED: ");
}

/** Handle the button click. */
public void ActionPerformed(ActionEvent e) {
    //Clear the text components.
    displayArea.setText("");
    typingArea.setText("");

    //Return the focus to the typing area.
    typingArea.requestFocusInWindow();
}

private void displayInfo(KeyEvent e, String keyStatus){

    //You should only rely on the key char if the event
    //is a key typed event.
    int id = e.getID();
    String keyString;
    if (id == KeyEvent.KEY_TYPED) {
        char c = e.getKeyChar();
        keyString = "key character = '" + c + "'";
    }  else {
        int keyCode = e.getKeyCode();
        keyString = "key code = " + keyCode
                + " ("
                + KeyEvent.getKeyText(keyCode)
                + ")";
    }

    int modifiersEx = e.getModifiersEx();
    String modString = "extended modifiers = " + modifiersEx;
    String tmpString = KeyEvent.getModifiersExText(modifiersEx);
    if (tmpString.length() > 0) {
        modString += " (" + tmpString + ")";
    } else {
        modString += " (no extended modifiers)";
    }

    String actionString = "action key? ";
    if (e.isActionKey()) {
        actionString += "YES";
    } else {
        actionString += "NO";
    }

    String locationString = "key location: ";
    int location = e.getKeyLocation();
    if (location == KeyEvent.KEY_LOCATION_STANDARD) {
        locationString += "standard";
    } else if (location == KeyEvent.KEY_LOCATION_LEFT) {
        locationString += "left";
    } else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
        locationString += "right";
    } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
        locationString += "numpad";
    } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
        locationString += "unknown";
    }

    displayArea.append(keyStatus + newline
            + "    " + keyString + newline
            + "    " + modString + newline
            + "    " + actionString + newline
            + "    " + locationString + newline);
    displayArea.setCaretPosition(displayArea.getDocument().getLength()); 

}
public static void main(String[] arguments) {
Calculator c = new Calculator();
}
}
import java.awt.*;
导入javax.swing.*;
导入java.awt.event.*;
导入java.awt.BorderLayout;
导入java.awt.Container;
导入java.awt.Dimension;
公共类计算器扩展JFrame实现KeyListener、ActionListener{
JPanel[]行=新JPanel[5];
JButton[]按钮=新JButton[19];
字符串[]按钮字符串={“7”,“8”,“9”,“+”,
"4", "5", "6", "-",
"1", "2", "3", "*",
“,”/“,“C”,“SR”,
"+/-", "=", "0"};
int[]dimW={300,45100,90};
int[]dimH={35,40};
维度显示维度=新维度(dimW[0],dimH[0]);
尺寸常规尺寸=新尺寸(dimW[1],dimH[1]);
尺寸rColumnDimension=新尺寸(dimW[2],dimH[1]);
尺寸zeroButDimension=新尺寸(dimW[3],dimH[1]);
布尔[]函数=新布尔[4];
double[]临时={0,0};
JTextArea显示=新的JTextArea(1,20);
Font Font=新字体(“Times new Roman”,Font.BOLD,14);
JTextArea显示区;
JTextField-typingArea;
静态最终字符串newline=System.getProperty(“line.separator”);
//如果要关闭焦点,请取消对此的注释
//遍历。焦点子系统消耗
//焦点遍历键,例如Tab和Shift Tab。
//如果取消注释以下代码行,则
//禁用焦点遍历,选项卡事件将
//使键事件侦听器可用。
//键入区域setFocusTraversalKeysEnabled(false);
计算器(){
超级(“计算器”);
setDesign();
设置大小(380250);
可设置大小(假);
setDefaultCloseOperation(关闭时退出);
GridLayout grid=新的GridLayout(5,5);
设置布局(网格);
对于(int i=0;i<4;i++)
函数[i]=假;
FlowLayout f1=新的FlowLayout(FlowLayout.CENTER);
FlowLayout f2=新的FlowLayout(FlowLayout.CENTER,1,1);
对于(int i=0;i<5;i++)
行[i]=新JPanel();
行[0]。设置布局(f1);
对于(int i=1;i<5;i++)
第[i]行。设置布局(f2);
对于(int i=0;i<19;i++){
按钮[i]=新的JButton();
按钮[i].setText(按钮串[i]);
按钮[i]。设置字体(字体);
按钮[i].addActionListener(此);
}
display.setFont(字体);
display.setEditable(false);
display.setComponentOrientation(ComponentOrientation.RIGHT\u至\u LEFT);
display.setPreferredSize(displayDimension);
对于(int i=0;i<14;i++)
按钮[i].setPreferredSize(regularDimension);
对于(int i=14;i<18;i++)
按钮[i].setPreferredSize(rColumnDimension);
按钮[18]。设置首选大小(zeroButDimension);
行[0]。添加(显示);
添加(第[0]行);
对于(int i=0;i<4;i++)
行[1]。添加(按钮[i]);
行[1]。添加(按钮[14]);
添加(第[1]行);
对于(int i=4;i<8;i++)
第[2]行。添加(按钮[i]);
第[2]行。添加(按钮[15]);
添加(第[2]行);
对于(int i=8;i<12;i++)
第[3]行。添加(按钮[i]);
第[3]行。添加(按钮[16]);
添加(第[3]行);
第[4]行。添加(按钮[18]);
对于(int i=12;i<14;i++)
第[4]行。添加(按钮[i]);
第[4]行。添加(按钮[17]);
添加(第[4]行);
setVisible(真);
}
公共空间清除(){
试一试{
display.setText(“”);
对于(int i=0;i<4;i++)
函数[i]=假;
对于(int i=0;i<2;i++)
临时[i]=0;
}捕获(NullPointerException e){
}
}
public void getSqrt(){
试一试{
double value=Math.sqrt(double.parseDouble(display.getText());
display.setText(Double.toString(value));
}捕获(数字格式){
}
}
public void getPosNeg(){
试一试{
double value=double.parseDouble(display.getText());
如果(值!=0){
值=值*(-1);
display.setText(Double.toString(value));
}
否则{
}
}捕获(数字格式){
}
}
public void getResult(){
双结果=0;
临时[1]=Double.parseDouble(display.getText());
字符串temp0=Double.toString(临时[0]);
字符串temp1=Double.toString(临时[1]);
试一试{
if(temp0.contains(“-”){
字符串[]temp00=temp0.split(“-”,2);
临时[0]=(Double.parseDouble(temp00[1])*-1);
}
if(temp1.contains(“-”){
字符串[]temp11=temp1.split(“-”,2);
临时[1]=(Double.parseDouble(temp11[1])*-1);
}
}捕获(阵列索引边界外异常e){
}
试一试{
if(函数[2]==true)
结果=临时[0]*临时[1];
else if(函数[3]==true)
结果=临时[0]/临时[1];
else if(函数[0]==true)
结果=临时[0]+临时[1];
else if(函数[1]==true)
结果=临时[0]-临时[1];
display.setText(Double.toString(结果));
对于(int i=0;i<4;i++)
函数[i]=假;
}捕获(数字格式){
}
}
公共最终设计(){
试一试{
UIManager.setLookAndFeel(
“com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel”);
}捕获(例外e){
}
}
@凌驾
已执行的公共无效行动(行动事件ae){
如果(ae.getSource()==按钮[0])
显示。附加(“7”);
如果(ae.getSource()==按钮[1])
显示。附加(“8”);
if(ae.getSource()==按钮[2])
显示。附加(“9”);
如果(ae.getSource()==butt
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class CalculatorPanel extends JPanel
{
    private JTextField display;

    public CalculatorPanel()
    {
        Action numberAction = new AbstractAction()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                display.setCaretPosition( display.getDocument().getLength() );
                display.replaceSelection(e.getActionCommand());
            }
        };

        setLayout( new BorderLayout() );

        display = new JTextField();
        display.setEditable( false );
        display.setHorizontalAlignment(JTextField.RIGHT);
        add(display, BorderLayout.NORTH);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout( new GridLayout(0, 5) );
        add(buttonPanel, BorderLayout.CENTER);

        for (int i = 0; i < 10; i++)
        {
            String text = String.valueOf(i);
            JButton button = new JButton( text );
            button.addActionListener( numberAction );
            button.setBorder( new LineBorder(Color.BLACK) );
            button.setPreferredSize( new Dimension(50, 50) );
            buttonPanel.add( button );

            InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
            inputMap.put(KeyStroke.getKeyStroke(text), text);
            inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
            button.getActionMap().put(text, numberAction);
        }
    }

    private static void createAndShowUI()
    {
//      UIManager.put("Button.margin", new Insets(10, 10, 10, 10) );

        JFrame frame = new JFrame("Calculator Panel");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.add( new CalculatorPanel() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}