-
Getting a Jlist to work
The code is supposed to activate a JList containg a label called hello as soon as the button is pressed.
Why does nothing happen when I click the activate-button?
Code:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
public class JListPractice extends JFrame implements ActionListener {
JButton activateButton = new JButton("activate");
JList resultList = new JList();
public static void main(String[] args) {
new JListPractice();
}
public JListPractice() {
setTitle("");
setBounds(200, 200, 500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container content = getContentPane();
activateButton.addActionListener(this);
content.add(activateButton, BorderLayout.NORTH);
content.add(resultList, BorderLayout.CENTER);
pack();
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent ev) {
if (ev.getSource() == activateButton){
System.out.println("searched");
//String[] g = {"a", "b", "v"};
//for Characters.
resultList.add(new JLabel("Hello"));
//resultList = new JList(g);
//repaint();
getContentPane().add(resultList, BorderLayout.CENTER);
}
}
private static final long serialVersionUID = 1L;
}
-
Well, you should not be adding "components" to the "list", you need to add "data" to the "model". So the first thing you need to do is use a ListModel that can be changed dynamically, such as the DefaultListModel. So you need to change:
Code:
//JList resultList = new JList();
JList resultList = new JList( new DefaultListModel());
Then you need to update the model:
Code:
// resultList.add(new JLabel("Hello"));
// getContentPane().add(resultList, BorderLayout.CENTER);
DefaultListModel model = (DefaultListModel)resultList.getModel();
model.addElement( "Hello" );
pack();
Read the JList API and follow the link to the Swing tutorial on "How to Use Lists" for working examples of using a JList. And download the entire tutorial for future reference.