【发布时间】:2017-07-25 07:08:33
【问题描述】:
所以基本上我开始学习 Java 的 awt 和 swing 库,在编写基本计算器时,我遇到的唯一问题是,当您按下其中一个按钮进行操作时,结果标签无法从操作方法,请注意它首先被实例化,当我从同一个方法(例如构造函数)执行所有操作时它确实有效(实例化标签,获取输入并生成输出)。
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JFrame {
JPanel panel=new JPanel();
double a,b;
public GUI(){
setTitle("Calculator");
setVisible(true); //Initializes window frame
add(panel); //Initializes window panel
input1();
input2();
result();
addition();
subtraction();
multiplication();
division();
setSize(400,500);
}
void input1(){ //Sets Input 1 label and input box
JLabel lInput1=new JLabel("Input 1");
lInput1.setForeground(Color.green);
panel.add(lInput1);
JTextField tInput1=new JTextField(4);
panel.add(tInput1);
a=Double.parseDouble(tInput1.getText()); //Saves the input on a variable for later usage
}
void input2(){ //Sets Input 2 label and input box
JLabel lInput2=new JLabel("Input 2");
lInput2.setForeground(Color.green);
panel.add(lInput2);
JTextField tInput2=new JTextField(4);
panel.add(tInput2);
b=Double.parseDouble(tInput2.getText()); //Saves the input on a variable for later usage
}
void addition(){ //Sets addition button
JButton addition=new JButton("+");
panel.add(addition);
addition.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
result.setText(String.valueOf(a+b));
}
});
}
void subtraction(){ //Sets subtraction button
JButton subtraction=new JButton("-");
panel.add(subtraction);
subtraction.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
result.setText(String.valueOf(a-b));
}
});
}
void multiplication(){ //Sets multiplication button
JButton multiplication=new JButton("*");
panel.add(multiplication);
multiplication.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
result.setText(String.valueOf(a*b));
}
});
}
void division(){ //Sets division button
JButton division=new JButton("/");
panel.add(division);
division.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
result.setText(String.valueOf(a*b));
}
});
}
void result(){
JLabel result=new JLabel();
panel.add(result);
}
}
错误出现在具有以下方法的行中:
result.setText();
提前致谢。
【问题讨论】:
-
result被声明为result方法的局部变量,如果您希望能够在类级别访问,则需要将其设为实例字段 -
也许Scope of variables in Java 可能会有更好的帮助
-
那我该怎么做呢?我试图将方法和实例都声明为公共的,但这是不可能的。
-
做一个或另一个,而不是两个(否则你最终会隐藏你的变量)
-
我的意思是我分别尝试了两者,但它说结果实例只允许 final 。你的意思是唯一的方法是在构造函数中而不是在方法中声明结果字段?
标签: java swing user-interface methods awt