import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener{
JButton[] nums;
JButton eq, mult, div, clr, clrEnt, sub, add, dot;
JTextArea txtArea = new JTextArea();
public Calculator() {
super("Calculator");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel(new GridLayout(6, 1, 0, 5));
add(pane);
JPanel paneSecond = new JPanel(new GridLayout(1, 3, 5, 5));
JPanel paneThird = new JPanel(new GridLayout(1, 3, 5, 5));
JPanel paneFourth = new JPanel(new GridLayout(1, 3, 5, 5));
JPanel paneFifth = new JPanel(new GridLayout(1, 3, 5, 5));
JPanel paneSixth = new JPanel(new GridLayout(1, 3, 5, 5));
JPanel paneSeventh = new JPanel(new GridLayout(1, 3, 5, 5));
nums = new JButton[11];
//add = new JButton();
addOpButton(eq, "=");
addOpButton(mult, "x");
addOpButton(div, "/");
addOpButton(clr, "C");
addOpButton(clrEnt, "CE");
addOpButton(sub, "-");
addOpButton(add, "+");
addOpButton(dot, ".");
for (int i = 0; i < nums.length; i++) {
nums[i] = new JButton("" + i);
nums[i].setActionCommand(nums[i].toString());
nums[i].addActionListener(this);
}
addPanel(paneSecond, 1, 4);
addPanel(paneThird, 4, 7);
addPanel(paneFourth, 7, 10);
//addButtons(paneFifth, add, nums[0], sub);
pane.add(paneSecond);
pane.add(paneThird);
pane.add(paneFourth);
pane.add(paneFifth);
pane.add(paneSixth);
pane.add(paneSeventh);
pack();
}
void addPanel(JComponent pane, int start, int condition) {
for (int i = start; i < condition; i++) {
pane.add(nums[i]);
}
}
void addButtons(JComponent pane, JButton btn1, JButton btn2, JButton btn3) {
pane.add(btn1);
pane.add(btn2);
pane.add(btn3);
}
void addOpButton(JButton btn, String op) {
btn = new JButton(op);
btn.setActionCommand(op);
btn.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
}
public static void main(String[] args) {
Calculator calc = new Calculator();
}
}
在addOpButton方法中,我的按钮都没有被初始化。我不知道为什么。字符串正在传递和使用,但不是按钮。即使在初始化其中一个按钮(构造函数中的“添加”按钮并删除了注释)之后,该方法中的按钮仍然为null。我无法弄清楚为什么。任何帮助表示赞赏。
答案 0 :(得分:4)
Java是&#34;传递值&#34;。这意味着如果您尝试传递引用,则复制引用然后传递。
在实践中,这意味着您为addOpButton提供的btn
参数是一个副本,而另一个副本由调用该方法的人保留。然后当你执行btn = new
时,你要为副本分配一些内容,给它一个命令和一个actionlistener,然后它就被丢弃了。来电者仍然可以参考他自己的副本。