JLabel array problem
I know there's an easy solution to this, one that will make me kick myself for not figuring it out beforehand, but here we go: I have a combo box and 6 labels in an array. What I want to happen is have it where whatever choice the user makes from the combo box is put after the word "Selected:", and all the other choices put in order afterwords skipping the spot where the selected item is.
For instance: if I were to select 3 the print out would be:
Selected: 3
1
2
4
5
6
If 6 was selected it would be:
Selected: 6
1
2
3
4
5
...etc...
I know all I need to use is some sort of simple 'if else' statement to get this to work properly, but I just can't get it! How embarrassing...
Here's the code (sorry if the indents are too big):
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
publicclass Test
{
publicstaticvoid main(String[] args)
{
//Initiate everything
JFrame frame =new JFrame();
frame.getContentPane().setLayout(new GridLayout(7, 1));
String[] values ={"One","Two","Three","Four","Five","Six"};
final JComboBox cb =new JComboBox(values);
final JLabel[] labels =new JLabel[6];
//Add components
frame.getContentPane().add(cb);
for (int i = 0; i < labels.length; i++)
{
labels[i] =new JLabel((String)cb.getItemAt(i));
frame.getContentPane().add(labels[i]);
}
labels[0].setText("Selected: " + labels[0].getText());
//Add listener
cb.addItemListener
(
new ItemListener()
{
publicvoid itemStateChanged(ItemEvent e)
{
int index = cb.getSelectedIndex();
for (int i = 1; i < labels.length; i++)
{
/*if (i == index)
labels[0].setText("Selected: " + (String)cb.getItemAt(index));
else if (i > index)
labels[i].setText((String)cb.getItemAt(i));*/
if (i < index)
labels[i].setText((String)cb.getItemAt(i));
elseif (i == index)
labels[0].setText("Selected: " + (String)cb.getItemAt(index));
else
labels[i].setText((String)cb.getItemAt(i - 1));
}
}
}
);
//Finalize and display window
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

