2

I'd like to make an application in Java with a JList on the left, and then everything else as an area for JPanels. The JPanel that would be displayed to the right of the JList is dependent on which item in the JList is being selected. I want to use a JList as the tabs, in this regard, not JTabbedPane.

enter image description here

How can I set up a listener on my JList that will achieve this?

I tried the following, but it didn't work. I did check that panel1 has both a location (0,0) and a size (greater than (0,0)) after the add call below.

public void valueChanged(ListSelectionEvent e) {
     int i = stepList.getSelectedIndex();
     if(i == 0) {
          //mainPanel is the green placeholder panel in the image above
          mainPanel.add(panel1);
     }
}

By the way, I am creating this project in Netbeans.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
CodeGuy
  • 28,427
  • 76
  • 200
  • 317

1 Answers1

2

You would use a CardLayout where perhaps the JList String would be the key that is used to display the JPanel "card".

CardLayout myCardLayout = new CardLayout();
JPanel cardHolderPanel = new JPanel(myCardLayout);

// here add items to the JList and the cardHolderPanel, using the same String
// added to the JLabel as the key 2nd parameter to the add(...) method


// elsewhere...
public void valueChanged(ListSelectionEvent e) {
  String selection = stepList.getSelectedValue().toString();
  myCardLayout.show(cardHolderPanel, selection);
}

For more on the CardLayout, please check out the CardLayout Tutorial.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • I have an E.G. of a [`CardLayout`](http://docs.oracle.com/javase/7/docs/api/java/awt/CardLayout.html) as seen in this [short example](http://stackoverflow.com/a/5786005/418556). – Andrew Thompson Jan 31 '14 at 02:19