這是我的代碼:爲什麼我的ActionListener只能用於我的其中一個按鈕?
import java.io.*;
import javax.swing.*;
import java.awt.event.* ;
class plugin extends JFrame implements ActionListener {
JPanel pnl = new JPanel();
public static void main(String args[]) {
plugin gui = new plugin();
}
JTextField progname = new JTextField("Program Name");
JButton pnameok = new JButton("Ok");
JTextField endtxt = new JTextField("Type of file");
JButton endok = new JButton("Ok");
JButton stop = new JButton("Stop the Server");
public plugin() {
super();
add(pnl);
pnl.add(stop);
pnl.add(progname);
pnl.add(pnameok);
pnl.add(endtxt);
pnl.add(endok);
pnameok.addActionListener(this);
endok.addActionListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if(event.getSource() == endok) {
try {
String end = endtxt.getText();
FileWriter endfile = new FileWriter(end + ".txt");
}
catch(IOException e) {
boolean uselessend = true;
}
if(event.getSource() == pnameok) {
try {
String pname = progname.getText();
FileWriter pnamefile = new FileWriter(pname + ".txt");
}
catch(IOException e1) {
boolean uselesspname = true;
try {
FileWriter pnamefileuse = new FileWriter("error");
}
catch(IOException e2) {
boolean completeandutterfail = true;
}
}
}
}
}
}
當我運行它,進入yay
到節目名稱和exe
到文件的類型,然後單擊兩個OK按鈕,我得到一個新的文件名爲exe.txt
但沒有文件名爲yay.txt
。爲什麼是這樣?
您是否嘗試通過在每個for循環中打印某些內容來調試它,以確保在單擊按鈕時它們都被正確執行? – smac89
是的,並且在pnameok的for循環中,它沒有執行那 – 33CoolyDude33