[英]Java swing, out of scope variable and usage of buttons
我正在嘗試制作一個動作監聽器,針對我創建的按鈕,並在每次輸入數字時都像計算器一樣顯示每個文本框。
但是在actionPerformed
方法下,似乎button1
似乎都超出了范圍,我現在不能將按鈕聲明為static嗎?
我需要克服范圍外的問題嗎?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import layout.TableLayout;
public class example extends JFrame implements ActionListener
{
public static void main (String args[])
{
new example();
}
public example ()
{
super("The Power of Preferred Sizes");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = getContentPane();
double size[][] = {{75, 75, 75, 75, 75}, // Columns
{75, 75, 75, 75, 75,75}}; // Rows
pane.setLayout(new TableLayout(size));
TableLayout layout = new TableLayout(size);
pane.setLayout (layout);
// Create all controls
String label[] = {"1", "2", "3", "4", "5","6","7", "8","9","0","PLS","RES"};
JButton button[] = new JButton[label.length];
JTextField upperText = new JTextField();
JTextField bottomText = new JTextField();
// textfieldName.setSize(10, 10);
pane.add(upperText, "0, 0, 4, 0");
pane.add(bottomText, "0, 5, 4, 0");
JButton button1 = new JButton(label[0]);
JButton button2 = new JButton(label[1]);
JButton button3 = new JButton(label[2]);
JButton button4 = new JButton(label[3]);
JButton button5 = new JButton(label[4]);
JButton button6 = new JButton(label[5]);
JButton button7 = new JButton(label[6]);
JButton button8 = new JButton(label[7]);
JButton button9 = new JButton(label[8]);
JButton button10 = new JButton(label[9]);
JButton button11= new JButton(label[10]);
JButton button12 = new JButton(label[11]);
pane.add(button1, "1,1");//1
pane.add(button2, "2,1");//2
pane.add(button3, "3,1");//3
pane.add(button4, "1,2");//
pane.add(button5, "2,2");
pane.add(button6, "3,2");
pane.add(button7, "1,3");
pane.add(button8, "2,3");
pane.add(button9, "3,3");
pane.add(button10, "1,4");
pane.add(button11, "2,4");
pane.add(button12, "3,4");
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button5.addActionListener(this);
button6.addActionListener(this);
button7.addActionListener(this);
button8.addActionListener(this);
button9.addActionListener(this);
button10.addActionListener(this);
button11.addActionListener(this);
button12.addActionListener(this);
pack();
setResizable(false);
show();
}
public void actionPerformed(ActionEvent e) {
//code that reacts to the action...
Object source = e.getSource();
if(source == button1){
upperText.append("1");
}
}
}
您可以將它們聲明為類字段,因此可以在整個類中訪問它們:
public class example extends JFrame implements ActionListener {
JButton button1;
JButton button2;
JButton button3;
JButton button4;
JButton button5;
JButton button6;
JButton button7;
JButton button8;
JButton button9;
JButton button10:
JButton button11;
JButton button12;
// Constructor
// Methods
}
另外,您應該考慮使用數組來容納12個按鈕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.