Show label in panel, combo box, action listener
Hi I have written small program. It has combo box. When I choose one item from combo box it should be write something on new label on Panel.
My program writes it on new Label, but it is not visible until I change size of Frame (and panel as well :D).
Is there any suggestion about what I'm doing wrong?
Code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JComboBox;
public class ComboListenExample {
public static void main(String[] args) {
ComboFrame frame = new ComboFrame();
frame.shwUI();
}
}
class ComboFrame extends JFrame {
JPanel rightPanel;
JComboBox combo;
JLabel label;
String[] names = { "Mike", "Jack", "Steven", "Peter", "John" };
public ComboFrame() {
rightPanel = new JPanel();
getContentPane().add(rightPanel, BorderLayout.EAST);
label = new JLabel("Hello");
rightPanel.add(label);
rightPanel.setLayout(new GridLayout(5,0));
combo = new JComboBox(names);
getContentPane().add(combo, BorderLayout.NORTH);
combo.addActionListener(new MyListen());
}
public void shwUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(400,400));
setLocationRelativeTo(null);
setVisible(true);
}
private class MyListen implements ActionListener {
JLabel label;
@Override
public void actionPerformed(ActionEvent arg0) {
label = new JLabel("Name");
rightPanel.add(label);
}
}
}