我正在嘗試構建一個工資系統,並且在使用變量和動作監聽器時遇到了問題,不知何故,它無法看到我所擁有的變量在actionlistener中聲明,我試過在類中調用它,但不知道我做錯了什麼導致它沒有工作。先謝謝你!如何從一個keylistener調用一個變量到不同的類
這裏是我的代碼:
import java.io.File; import java.io.FileNotFoundException; import
java.util.ArrayList; import java.util.List; import
java.util.Scanner; import javax.swing.*; import java.awt.*; import
java.awt.event.*;
@SuppressWarnings("serial")
public class kapoy extends JFrame{
public static JTextField text1;
public static JTextField text2;
public JLabel label1;
public JLabel label2;
public JPanel panel1;
public JPanel panel2;
public JPanel panel3;
public JPanel panel4;
public kapoy() {
text1 = new JTextField();
text1.setPreferredSize(new Dimension(50,20));
text2 = new JTextField();
text2.setPreferredSize(new Dimension(50,20));
label1 = new
JLabel("Inpute Employee ID: ");
label2 = new JLabel("Input workedDays: ");
panel1 = new JPanel();
panel1.setLocation(0,0);
panel1.setSize(300,40);
panel1.setBackground(Color.blue);
panel1.add(label1);
panel1.add(text1);
add(panel1);
panel2 = new JPanel();
panel2.setLocation(0,40);
panel2.setSize(300,40);
panel2.setBackground(Color.red);
panel2.add(label2);
panel2.add(text2);
add(panel2);
panel3 = new JPanel();
panel3.setLocation(0,80);
panel3.setSize(400,200);
panel3.setBackground(Color.green);
add(panel3);
panel4 = new JPanel();
panel4.setLocation(300,0);
panel4.setSize(100,80);
panel4.setBackground(Color.yellow);
add(panel4);
setSize(410,300);
setLayout(null);
setTitle("Pay Roll by Migz"); }
public static void main(String[] args) {
kapoy cn = new kapoy(); cn.setVisible(true);
text1.addKeyListener(new KeyAdapter(){
public void keyReleased(KeyEvent e)
{
try {
/**Cant use this-->**/int x = Integer.parseInt(text1.getText());
} catch (NumberFormatException nfe) {
text1.setText("");
}
} });
try {
File f = new File("D:/Users/DAVID Family/Desktop/Employees.txt");
Scanner sc = new Scanner(f);
List<Employee> people = new ArrayList<Employee>();
while(sc.hasNextLine()){
String line = sc.nextLine();
String[] details = line.split(" ");
int Id = Integer.parseInt(details[0]);
String name = details[1];
int rate = Integer.parseInt(details[2]);
Employee p = new Employee(Id, name, rate);
/**in here-->**/if (x == Id){
people.add(p);
}
}
for(Employee p: people){
System.out.println(p.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
class Employee{
private int Id;
private String name;
private int rate;
public Employee(int Id, String name, int rate){
this.Id = Id;
this.setName(name);
this.rate = rate;
}
public int getId() {
return Id; }
public void setId(int Id)
{
this.Id = Id; }
/public void setName(String
name) {
this.name = name; }
public String getName() {
return name; }
public int getrate() {
return rate; }
public void setrate(int rate) {
this.rate = rate; }
public String toString(){
return this.Id + " " + this.name + " " + this.rate; } }