Why can't I add both a JList and a JScrollPane to my JFrame?
Hi everyone, here is the code:
Code:
public class ListFrame extends JFrame
{
JList myJList;
String[] colorrs;
public ListFrame()
{
super("This is a List Frame");
this.setLayout(new FlowLayout());
colorrs = new String[6];
colorrs[0] = "Red";
colorrs[1] = "Blue";
colorrs[2] = "Green";
colorrs[3] = "Black";
colorrs[4] = "White";
colorrs[5] = "Purple";
myJList = new JList();
myJList.setListData(colorrs);
myJList.setVisibleRowCount(4);
JScrollPane scrollPane = new JScrollPane(myJList);
this.add(scrollPane);
//this.add(myJList);
}// end Constructor
}//end Class
With this code, I get a nice JScrollPane that includes myJList with the options.
But:
If I remove the comment slashes from last statement I have(//this.add(myJList);), I am expecting to see both the JScrollPane and myJList.
However I only get an ugly JList with no scrolling option. JScrollPane gets invisible.
Any help?
Thanks.
Re: Why can't I add both a JList and a JScrollPane to my JFrame?
A component can only be added once to a visible GUI. If you try to add it twice, the last component only is seen. To remedy the situation, use two JLists that share the same model.
For example,
Code:
import java.awt.FlowLayout;
import javax.swing.*;
public class ListFrame extends JFrame
{
JList myJList;
String[] colorrs;
public ListFrame()
{
super("This is a List Frame");
this.setLayout(new FlowLayout());
colorrs = new String[6];
colorrs[0] = "Red";
colorrs[1] = "Blue";
colorrs[2] = "Green";
colorrs[3] = "Black";
colorrs[4] = "White";
colorrs[5] = "Purple";
myJList = new JList();
myJList.setListData(colorrs);
myJList.setVisibleRowCount(4);
JScrollPane scrollPane = new JScrollPane(myJList);
this.add(scrollPane);
JList newList = new JList(myJList.getModel());
this.add(newList);
}
public static void main(String[] args) {
ListFrame listFrame = new ListFrame();
listFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
listFrame.pack();
listFrame.setLocationRelativeTo(null);
listFrame.setVisible(true);
}
}
Re: Why can't I add both a JList and a JScrollPane to my JFrame?
Thanks for the quick and very clear answer.
Re: Why can't I add both a JList and a JScrollPane to my JFrame?
Quote:
Originally Posted by
fatabass
Thanks for the quick and very clear answer.
You are quite welcome!
Re: Why can't I add both a JList and a JScrollPane to my JFrame?
Moved from 'New to Java'
db