I want to add JCombobox to the panel at run time, I don't have idea about this, so please if you have any idea about this suggest me.
+1
A:
I assume you want to add a combo box to a component that is already on screen. Just add the component to the appropriate Container and call the Container's validate method. Here is a little example for this:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Application {
private static final String[] choices = { "One", "Two", "Three" };
/**
* @param args
*/
public static void main(String[] args) {
JFrame frame = new JFrame();
final JPanel content = new JPanel();
content.setPreferredSize(new Dimension(50, 200));
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
JButton addButton = new JButton(new AbstractAction("Add Combobox") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent arg0) {
content.add(new JComboBox(choices));
content.validate();
}
});
frame.add(content);
content.add(addButton);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Although I have used a frame only for this example, it should also work for a JPanel.
Klarth
2010-02-20 12:00:51
I use the Swing revalidate() method instead of the AWT validate() method.
camickr
2010-02-20 16:20:28