我有一个大型 gui 中的 JList,我删除了所有其他不相关的代码。我可以初始化列表,但是当我使用按钮时,我无法从中添加/删除项目。我读过的所有内容都说使用 DefaultListModel。然后它会在您重新初始化列表时自动更新列表。
我也尝试过重新聚焦和重新绘制面板和框架,但这也不起作用。
public static void main(String[] args) {
Play worker=new Play();
worker.GUI();
}
public void GUI(){
frame=new JFrame();
mainPanel=new JPanel(new GridBagLayout());
filePanel=new JPanel(new GridBagLayout());
allFilePanel=new JPanel(new GridBagLayout());
fileInputLabel=new JLabel("Enter the directory of the csv file:");
fileNameField=new JTextField(25);
readFileButton=new JButton("Read File");
ReadFileButtonListener buttonListener=new ReadFileButtonListener();
readFileButton.addActionListener(buttonListener);
addItem(filePanel,fileInputLabel , 0, 0, 1, 1, GridBagConstraints.CENTER);
addItem(filePanel,fileNameField , 1, 0, 2, 1, GridBagConstraints.CENTER);
addItem(filePanel,readFileButton , 3, 0, 1, 1, GridBagConstraints.CENTER);
allFileLabel=new JLabel("List of all Data");
String [] name={"joe"};
allFileList=new JList<String>(name);
allFileList.setVisibleRowCount(10);
addItem(allFilePanel,allFileLabel , 0, 0, 1, 1, GridBagConstraints.CENTER);
addItem(allFilePanel,allFileList , 0, 1, 1, 1, GridBagConstraints.CENTER);
addItem(mainPanel, filePanel, 0, 0, 4, 1, GridBagConstraints.CENTER);
addItem(mainPanel, allFilePanel, 1, 2, 1, 1, GridBagConstraints.CENTER);
frame.setSize(1000,800);
frame.add(mainPanel);
frame.setVisible(true);
}
/**configures the panels
* @param p
* @param c
* @param x
* @param y
* @param width
* @param height
* @param align
*/
private void addItem(JPanel p,JComponent c, int x, int y , int width,int height, int align){
GridBagConstraints gc=new GridBagConstraints();
gc.gridx=x;
gc.gridy=y;
gc.gridwidth=width;
gc.gridheight=height;
gc.weightx=100;
gc.weighty=100;
gc.insets=new Insets(5,5,5,5);
gc.fill=GridBagConstraints.NONE;
p.add(c,gc);
}
private class ReadFileButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent arg0) {
generateAllFileList();
}
}
public void generateAllFileList(){
DefaultListModel<String> list=new DefaultListModel<String>();
list.addElement("Fred");
allFileList=new JList<String>(list);
}
}