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.