我想在选择单选按钮“不显示字段”时删除文本字段,但无法删除。我已经使用了重绘和重新验证方法。我还尝试通过将可见性设置为false来使该字段不可见,但似乎无济于事。
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
new Frame();
}
}
class Frame
{
private JFrame frame;
private JButton button;
private ImageIcon img;
private JRadioButton b1;
private JRadioButton b2;
private JTextField text;
public Frame()
{
frame = new JFrame();
text=new JTextField(10);
b1=new JRadioButton("show Field");
b2=new JRadioButton("Dont show field");
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
img = new ImageIcon("Letter-S-icon.png");
b1.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg) {
if(arg.getSource()==b1)
{
frame.add(text);
frame.revalidate();
frame.repaint();
}
else if(arg.getSource()==b2)
{
text.setVisible(false);
frame.remove(text);//cannot remove this even after repaint();
frame.revalidate();
frame.repaint();
}
}
});
frame.add(b1);
frame.add(b2);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
frame.setBounds(500, 200, 200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setIconImage(img.getImage());
}
}