1

I am working on a Java Swing application. My Requirement :-

In my JFrame, I have a JList with values "One", "Two", "Three" etc. When I select one list item, I want to show "n" buttons where "n" is the value selected.

Example :- If I select "Three" from the list, there should be 3 buttons in the JFrame.

Below is my code :-

public class Details extends JFrame {

    String[] navData = new String{"One","Two","Three","Four"};
    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Details frame = new Details();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */

    public Details()  {

        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        Toolkit tk = Toolkit.getDefaultToolkit();
         int xSize = ((int) tk.getScreenSize().getWidth());
         int ySize = ((int) tk.getScreenSize().getHeight());
         //frame.setSize(xSize,ySize);
        setTitle("Test");
        setBounds(0, 0, 776, 457);
        setResizable(false);
        //setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        final JList list = new JList(navData);
        list.setBounds(0, 0, 140, ySize);
        contentPane.add(list);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setFixedCellHeight(50);
        list.setFixedCellWidth(70);
        list.setBorder(new EmptyBorder(10,10, 10, 10));


        list.addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent arg0) {

                int numButtons;
                String selectedItem = navData[list.getSelectedIndex()];
                switch (selectedItem) {
                case "One":
                    addButtons(1);
                    break;
                case "Two":
                    addButtons(2);
                    break;
                case "Three":
                    addButtons(3);
                    break;
                case "Four":
                    addButtons(4);
                    break;
                default:
                    break;
                }

            }
        });
        list.setSelectedIndex(0);


    }

    public void addButtons(int n)
    {
        revalidate();
        for(int i = 0; i<n;i++)
        {
            JButton button = new JButton(" "+navData[i]);
            button.setBounds(200 + (i*50), 150, 50, 50);
            contentPane.add(button);    
        }

    }
}

- Problem :-

When I change the selected item in the list, the JPanel is not getting updated. In other words, I don't get 3 buttons when I select "Three" from the List. I get only 1 button which was created by the default selection.

Partha Chetry
  • 136
  • 1
  • 9

3 Answers3

0

Replace contentPane.setLayout(null); with some kind of layout such as contentPane.setLayout(new GridBagLayout());

Add

contentPane.removeAll() as the first line in addButtons().

user489041
  • 27,916
  • 55
  • 135
  • 204
  • `contentPane.setLayout(new GridBagLayout())` moved my JList and JButtons to the center of the screen ... I want my JList to appear in the leftmost corner of the frame and the JButtons to appear right of JList and aligned horizontally wrt to other buttons .... also `contentPane.removeAll()` removes the JList ... – Partha Chetry Mar 26 '15 at 18:46
0

You can create a "wrapper" panel for buttons, i.e.

...
private JPanel buttonsWrapper;
...
// in the constructor
buttonsWrapper = new JPanel();
buttonsWrapper.setLayout(null);
buttonsWrapper.setBounds(200, 150, 200, 50);
buttonsWrapper.add(wrapperPanel);

and add buttons to this panel

public void addButtons(int n) {
    buttonsWrapper.removeAll();
    for(int i = 0; i < n; i++) {
        JButton button = new JButton(" " + navData[i]);
        button.setBounds((i*50), 0, 50, 50);
        buttonsWrapper.add(button);    
    }
    buttonsWrapper.revalidate();
    buttonsWrapper.repaint();
}
0

I made these changes:

  1. I put the JList in a JPanel, and the JButtons in another JPanel.

  2. I used the FlowLayout for the JList JPanel, and the FlowLayout for the JButtons JPanel. You're free to change these Swing layouts if you wish.

  3. I changed the default to 4 buttons, so the JFrame would pack properly for up to 4 JButtons.

  4. I added a method to remove the JButtons from the JPanel before trying to add JButtons to the JPanel.

  5. I revalidated and repainted the JButton JPanel.

Here's the code:

package com.ggl.testing;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class Details extends JFrame {

    private static final long serialVersionUID = -555805219508469709L;

    private String[] navData = { "One", "Two", "Three", "Four" };

    private JPanel buttonPanel;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Details frame = new Details();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */

    public Details() {
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setTitle("Test");

        buttonPanel = new JPanel();

        JPanel listPanel = new JPanel();
        final JList<String> list = new JList<String>(navData);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setFixedCellHeight(50);
        list.setFixedCellWidth(70);
        list.setBorder(new EmptyBorder(10, 10, 10, 10));

        list.addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent event) {

                String selectedItem = navData[list.getSelectedIndex()];
                switch (selectedItem) {
                case "One":
                    removeButtons(buttonPanel);
                    addButtons(buttonPanel, 1);
                    break;
                case "Two":
                    removeButtons(buttonPanel);
                    addButtons(buttonPanel, 2);
                    break;
                case "Three":
                    removeButtons(buttonPanel);
                    addButtons(buttonPanel, 3);
                    break;
                case "Four":
                    removeButtons(buttonPanel);
                    addButtons(buttonPanel, 4);
                    break;
                default:
                    break;
                }

            }
        });
        list.setSelectedIndex(3);

        listPanel.add(list);

        add(listPanel, BorderLayout.WEST);
        add(buttonPanel, BorderLayout.CENTER);

        pack();
    }

    public void removeButtons(JPanel panel) {
        Component[] components = panel.getComponents();
        for (int i = 0; i < components.length; i++) {
            panel.remove(components[i]);
        }
    }

    public void addButtons(JPanel panel, int n) {
        for (int i = 0; i < n; i++) {
            JButton button = new JButton(navData[i]);
            panel.add(button);
        }
        panel.revalidate();
        panel.repaint();
    }
}
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111