我在运行时通过单击按钮动态添加组件。但现在我想在不单击按钮的情况下动态添加组件。我怎样才能做到这一点..??这是我在单击按钮时添加组件的源代码。
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String[] items = new String[4];
items[0]="English";
items[1]="French";
items[2]="Spanish";
items[3]="Hindi";
JTextField jtextfield = new JTextField();
jtextfield.setPreferredSize(new Dimension(50, 20));
JButton jbutton = new JButton();
jbutton.setText("Remove");
jbutton.setPreferredSize(new Dimension(89, 23));
JLabel jlabel = new JLabel();
jlabel.setText("Text:");
jlabel.setPreferredSize(new Dimension(40, 20));
JLabel jlabel2 = new JLabel();
jlabel2.setText("Language:");
jlabel2.setPreferredSize(new Dimension(65, 20));
JComboBox jcombo = new JComboBox();
jcombo.setPreferredSize(new Dimension(80,20));
jcombo.addItem(items[0]);
jcombo.addItem(items[1]);
jcombo.addItem(items[2]);
jcombo.addItem(items[3]);
jPanel6.add(jlabel);
jPanel6.add(jtextfield);
jPanel6.add(jlabel2);
jPanel6.add(jcombo);
jPanel6.add(jbutton);
jbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component[]storeAllButtonInPanel = jPanel6.getComponents();
if(storeAllButtonInPanel.length!=0) {
jPanel6.remove(storeAllButtonInPanel.length-1);
jPanel6.remove(storeAllButtonInPanel.length-2);
jPanel6.remove(storeAllButtonInPanel.length-3);
jPanel6.remove(storeAllButtonInPanel.length-4);
jPanel6.remove(storeAllButtonInPanel.length-5);
jPanel6.revalidate();
validate();
repaint();
}
}
});
jPanel6.validate();
jPanel6.repaint();
}
如果我只有 2 个 Text 值,那么它也会显示两行,如果是 3 个值,那么应该只有 3 行..!!我怎样才能做到这一点。?