Tyzak
Tyzak

Reputation: 2438

Java Swing JList

I am using a JList in Java Swing, but when my Dialog opens, the List isn't shown.

private JList getJList() {
  if (mylist == null) {
   mylist = new JList();
   mylist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
   mylist.setSize(new Dimension(154, 106));
   model.addElement("test");
   model.addElement("zwei");
   mylist.setVisible(true);

  }
  return mylist;
 }

The list is defined:

private JPanel getJContentPane() {
  if (jContentPane == null) {
   jContentPane = new JPanel();
   jContentPane.setLayout(new BorderLayout());
   jContentPane.add(getJList(), BorderLayout.CENTER);

  }
  return jContentPane;
 }

It's a JContentPane (/Panel)

public fensterdrei(Frame owner) {
  super(owner);
  initialize();
  }

the code calling getJContentPane():

private void initialize() {
      this.setSize(300, 200); 
      this.setContentPane(getJContentPane()); 
      this.setTitle("Auswahl"); 
} 

Upvotes: 5

Views: 2376

Answers (3)

user85421
user85421

Reputation: 29680

I can't find where you are setting the model of the JList?

Something like

mylist = new JList();    
mylist.setModel(model);

Please have a look at the Code Conventions for the Java Programming Language

FensterDreiinstead of fensterdrei
myListinstead of mylist

Upvotes: 8

willcodejavaforfood
willcodejavaforfood

Reputation: 44063

To answer your question I would need to see the code that calls getJContentPane to make sure that you are actually adding that JPanel somewhere. I would also need to see if you have assigned something to jContentPane since you only add the list if that panel is null.

My guess is that you are not actually adding the returned panel to the dialog or that jContentPane has been assigned a non null value.

The call to myList.setVisible(true) makes no sense since it is not added to a Window yet. When a dialog is made visible all its children will be made visible as well.

Upvotes: 1

Chad Okere
Chad Okere

Reputation: 4578

It's getContentPane not getJContentPane, and You're not supposed to overload it.

Instead, in your constructor (or other function that gets called right away) you do

getContentPane().setLayout(new BorderLayout());
getContentPane().add(getJList(), BorderLayout.CENTER);

Upvotes: 4

Related Questions