因此,基本上我開始學習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'方法,如果你希望能夠訪問在一個類的層次上,你將需要使它成爲一個實例字段 – MadProgrammer
也許[Java變量的範圍](http://www.geeksforgeeks.org/variable-scope-in-java/)可能會更好地幫助 – MadProgrammer
那麼如何才能我這樣做?我試圖將方法和實例聲明爲公共的,但這是不可能的。 – Otomeram