gpt4 book ai didi

带有按键响应的 Java 计算器

转载 作者:行者123 更新时间:2023-12-02 05:27:45 29 4
gpt4 key购买 nike

所以我写了这个脚本;它有点像我找到并拼凑起来的计算器的大杂烩。

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

我正在尝试使用KeyListener来允许击键使计算器工作,这样就不必单击输入;目前脚本可以编译,但无法输入输入...我这样做对吗?

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();
}
}

最佳答案

屏幕上的主要可见组件是display JTextArea。您将此字段设置为不可编辑,display.setEditable(false);,因此用户将无法在其中输入文本...

此外,永远不会调用 contentPane 方法,因此永远不会显示 typingAreadisplayArea ,但我不确定您想要无论如何,请执行此操作,因为您已将布局管理器从 BorderLayout 更改为 GridLayout,这只会把事情搞砸......

此外,附加了 KeyListenertypingArea 永远不会添加到任何可显示组件中,因此它永远不会触发任何按键事件,因为没有人在其中键入内容。 ..

很难知道该建议什么,但我可能建议摆脱 displaydisplayArea 并使用 typingArea ,除非你确实需要多行数字...

无论如何,您应该避免在文本组件上使用 KeyListener,监听文本组件状态更改的更好解决方案是 DocumentListener,请参阅 Listening for Changes on a Document了解更多详情...

关于带有按键响应的 Java 计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25839356/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com