我自己做了一个简单的项目,就是使用Java开发一个计算器,但是输出错误了:
时
我问大家,我查看了我的代码,但找不到解决方案。大多数人都说我的代码逻辑是代码。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JTextField;
public class ButtonListener implements ActionListener {
JTextField text;
String display = "";
String button[];
JButton buttons[];
public ButtonListener(JTextField text, String[] button, JButton[] buttons) {
this.text = text;
this.button = button;
this.buttons = buttons;
}
public void Display(String button) {
display = display + button;
// return display;
}
public void actionPerformed(ActionEvent Buttonpress) {
/******************** Constants ********************/
// Planks Constant
if (Buttonpress.getSource() == buttons[0]) {
// display+=button[0];
Display(button[0]);
}
// Elementary Charge
if (Buttonpress.getSource() == buttons[8]) {
// display+=Buttonpress.getSource();
Display(button[8]);
}
text.setText(display);
}
}
答案 0 :(得分:2)
首先,方法名称不应以大写字母开头。 "显示"应该是"显示"。
不要保留按钮和字符串数组,以确定点击了哪个按钮以及应追加哪些文字。
您可以从ActionEvent本身获取更新显示文本字段所需的所有信息。
以下是您要查看的示例:
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();
}
});
}
}