1
我想通過更改第一個組合框的值來更改第二個組合框元素,但它不起作用。組合框的ActionListener僅適用於聲明後的第一列。如果我運行調試並按「運行」 - 它運作良好。 這裏是我的代碼:組合框的ActionListener僅適用於聲明後的第一列
import java.awt.Container;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class face extends JFrame {
public face() {
super("Test frame");
setDefaultCloseOperation(EXIT_ON_CLOSE);
// READ FILE //
File f=new File("");
String tname = f.getAbsolutePath()+File.separator+"1.txt";
Scanner in = null;
int i=0;
List<String> list = new ArrayList<String>();
try {
in = new Scanner(new File(tname));
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
while (in.hasNextLine())
list.add(in.nextLine());
in.close();
String[] teacherlist = list.toArray(new String[0]);
JComboBox tcombo = new JComboBox(teacherlist);
tcombo.setSelectedIndex(1);
String item = (String)tcombo.getSelectedItem();
JPanel panel = new JPanel();
panel.add(tcombo);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
File r = new File("");
//String item = (String)tcombo.getSelectedItem();
String sname = r.getAbsolutePath()+File.separator+"aaaa.txt";
List<String> slist = new ArrayList<String>();
Scanner k;
k=null;
try {
k = new Scanner(new File(sname));
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
while (k.hasNextLine())
slist.add(k.nextLine());
k.close();
String[] subjectlist = slist.toArray(new String[0]);
JComboBox scombo = new JComboBox(subjectlist);
scombo.setVisible(true);
panel.add(scombo);
}
};
tcombo.addActionListener(actionListener);
panel.add(but);
label.setVisible(false);
setContentPane(panel);
}
public static void main(String[] args)
{JFrame myWindow = new face();
myWindow.setVisible(true);
myWindow.setSize(500,500);
}}