动态添加组件,无需点击按钮
我在运行时单击按钮动态添加组件。 但现在我想动态添加组件而不单击按钮。 我怎样才能做到这一点..?这是我在单击按钮时添加组件的源代码。
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 个文本值,那么它也会显示两行,如果有 3 个值,那么应该只有 3 行..!!我怎样才能做到这一点?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不知道你想要什么,需要/需要对此进行一些控制,作为 GUI 的输出并使用一些 监听器 (作为您的 ActionListener),
也许(完全控制)JPopupMenu,API,示例此处 或此处
no idea what do you want, there is needed / required some control about that, as output to the GUI and by using some of Listener (as your ActionListener),
maybe (with full control) JPopupMenu, API, examples here or here
javax.swing.Timer< 的实例/code>
可以定期调用 actionPerformed()
方法href="http://download.oracle.com/javase/6/docs/api/java/awt/event/ActionListener.html" rel="nofollow noreferrer">ActionListener
,如本示例中所建议的添加和删除JLabel
。An instance of
javax.swing.Timer
can periodically invoke theactionPerformed()
method of anActionListener
, as suggested in this example that adds and removesJLabel
s.