Hello,
I'm trying to create Frame with 2 JButtons and 1 JList.
Buttons are Add and Remove. After clicking Add button JFileChooser creates and user choses a file.
The file then must to be added to the JList.

public class GmFrame extends JFrame {

	private JButton bAdd;
	private JButton bRemove;
	public JList jl;
	public Vector<File> vf = new Vector<File>();
	
	public GmFrame() {
		super("GM & OBP");
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setBounds(200,200,800,400);
		Container c = this.getContentPane();
		c.setLayout(new FlowLayout(FlowLayout.LEFT, 10,10));
		JPanel p = new JPanel();
		p.setLayout(new BorderLayout(10,0));
		
		bAdd = new JButton("Add");
		bRemove = new JButton("Remove");
		
		jl = new JList(vf);
		jl.setPreferredSize(new Dimension(500,100));
		vf.add(new File("C://"));
		vf.add(new File("D://"));
		
		p.add(bAdd, BorderLayout.WEST);
		p.add(bRemove, BorderLayout.EAST);
		p.add(jl, BorderLayout.CENTER);
		
		c.add(p);
		
		this.addActionListeners();
		
		this.setVisible(true);
		
	}
	
	private void addActionListeners() {
		
		bAdd.addActionListener(new AddListener(this));
		
		bRemove.addActionListener(
				new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						System.out.println(jl.getSelectedValue().getClass().getName() );
						int i = jl.getSelectedIndex();
						jl.remove(i);
					}
				}
		);
		
	}
	
}

class AddListener implements ActionListener {
	GmFrame gf;
	AddListener(GmFrame gf) {
		this.gf = gf;
	}
		
		public void actionPerformed(ActionEvent arg0) {
			JFileChooser fileChooser = new JFileChooser(new File("C:/Program Files/"));
			int ret = fileChooser.showDialog(null, "Open file");
			if (ret == JFileChooser.APPROVE_OPTION) {
		      File file = fileChooser.getSelectedFile();
		      gf.vf.add(file);
		      
		    }
			System.out.println(gf.vf.size());
	}
}

My problem is that chosen file doesn't shown on the frame. But the file is added to the Vector that linked with JList.
What have I do to "refresh" the frame?
Could someone please show me my mistake?

Thanks in advance

Recommended Answers

All 2 Replies

Because you add it only to vector and not the JList:

gf.vf.add(file);

You added it successfully to the Vector but where is the code that adds it to list?

Thank you, javaAddict.

Just I thought JList use Observer/Observable interface. So if Vector changes, the JList changes too. Apparently my understanding is wrong.

javaAddict, could you please tell me how can I add element to JList?
Should I create new JList?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.