这是带有 GUI 的代码以及对我之前创建的 for 循环的修订。每次用户按下一个按钮时,我都希望文本字段反映该按钮被按下。
如果用户按下 1 按钮一次: 1 被推到场上。如果用户按两次 1 按钮:11 被推到场上。... 等等。
相反,程序在第二次按下按钮时崩溃。有人可以告诉我出了什么问题吗?
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Arrays;
import java.util.ArrayList;
import java.lang.Math;
public class poopy
{
public static void main(String[] args)
{
//frame width and height
final int FRAME_WIDTH = 290;
final int FRAME_HEIGHT = 210;
//created frame and panel. Panel layout is taken away from the flow layout.
JFrame myFrame = new JFrame();
myFrame.setTitle("Simple Calculator");
myFrame.setSize(FRAME_WIDTH,FRAME_HEIGHT);
JPanel myPanel = new JPanel();
myPanel.setLayout(null);
//TextField on Simple Calculator
final JTextField myText = new JTextField();
myText.setSize(250,30);
myText.setLocation(10,10);
final JButton oneButton = new JButton("1");
oneButton.setSize(50,50);
oneButton.setLocation(10,102);
//makes panel visible and close when the 'x' is hit
myFrame.add(myPanel);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
myPanel.add(oneButton);
myPanel.add(myText);
class CalculatorListener implements ActionListener
{
ArrayList<Integer> num = new ArrayList<Integer>();
double x=0;
int k = 0;
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == oneButton)
{
num.add(1);
for(int i = num.size() -1; i>=0; i--)
{
x = num.get(k) * Math.pow(10,i);
k=k+1;
}
myText.setText(" " + String.valueOf(x));
}
}
}
//buttons are given life
CalculatorListener myListener = new CalculatorListener();
oneButton.addActionListener(myListener);
}
}