我有一个包含JPanel的JFrame.JPanel包含一个JComboBox,JTextField,添加按钮和一个删除按钮。如果我单击添加按钮,我需要添加一行包含上述组件(即JComboBox,JTextField) ,添加按钮和删除按钮)并禁用以前的添加按钮。如果我单击新形成的行中的添加按钮同样需要发生。我已经完成了这些。现在如果我点击任何删除按钮我需要从JPanel中的那一行中删除swing组件,以及其他删除按钮的方法。如何做到这一点?请帮助我。 以下是我的代码
public class SaveIt extends JFrame {
JPanel panel;
JButton btnAdd;
JButton btnRemove;
JTextField txtAmount;
JComboBox cmbAmount;
private int f = 0;
private int h = 0;
public SaveIt() {
super("Add component on JFrame at runtime");
setLayout(new BorderLayout());
panAmount = new JPanel();
panAmount.setLayout(new FlowLayout());
add(panAmount, BorderLayout.CENTER);
cmbAmount = new JComboBox();
add(cmbAmount, BorderLayout);
txtAmount = new JTextField();
add(txtAmount, BorderLayout);
btnAdd = new JButton("Add");
add(btnAdd, BorderLayout.SOUTH);
btnAdd.addActionListener(this);
btnRemove = new JButton("Remove");
add(btnRemove, BorderLayout.SOUTH);
btnRemove.addActionListener(this);
cps = new ArrayList<JComponent>();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
}
public void actionPerformed(ActionEvent evt) {
getPanComponents();
}
public void getPanComponents() {
btnAdd.setEnabled(false);
btnRemove.setVisible(true);
cmbAmount = new JComboBox();
cmbAmount.setBounds(80, 50 + f, 115, 28);
txtAmount = new JTextField();
txtAmount.setBounds(310, 50 + f, 135, 28);
btnAdd = new JButton("Add");
btnAdd.setBounds(463, 50 + f, 41, 29);
btnRemove = new JButton("Remove");
btnRemove.setBounds(510, 50 + f, 41, 29);
btnAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
getPanComponents();
}
});
btnRemove.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
}
});
cps.add(cmbAmount);
cps.add(txtAmount);
cps.add(btnAdd);
cps.add(btnRemove);
for (JComponent widget : cps) {
panAmount.add(widget);
}
panAmount.revalidate();
h = h + 40;
panAmount.repaint();
panAmount.setPreferredSize(new Dimension(611, 89 + h));
f = f + 35;
}
public static void main(String[] args) {
SaveIt acojfar = new SaveIt();
}
}
答案 0 :(得分:3)
没有理由使用NullLayout,将GridLayout与一列一起使用
使用JPanel作为JComponents的容器
将JPanel包含另一个JPanel添加到JScrollPane
不要为PreferredSize设置,也不要为revalidate()和repaint()设置
SaveIt acojfar = new SaveIt();
应该包含在invokeLater中,更多内容可以在Oracle tutorial Initial Thread中阅读