JButton被移除后会在JPanel中留下文物?

时间:2015-03-24 19:17:59

标签: java swing jpanel

所以我必须创建JLabelJButton,将它们放入JPanel,然后将其全部显示在JFrame中。必须删除JButton,并在点击JLabel后更改JButton的文字。一切正常,除了一件事:当按钮从JPanel移除时,它仍然留下了自己的神器。这是我的代码,亲自试试:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class TestClass
{
    public static void main (String[] args)
    {
        new TestClass();
    }

    public TestClass()
    {
        JPanel jpanel = new JPanel();
        JLabel jlabel = new JLabel ("-->");
        JButton jbutton = new JButton ("Click here!");

        jbutton.addActionListener (new ActionListener()
        {
            public void actionPerformed (ActionEvent event)
            {
                jlabel.setText ("Good job!");
                jpanel.remove (jbutton);
            }
        });

        jpanel.add (jlabel);
        jpanel.add (jbutton);

        JFrame jframe = new JFrame ("Test Frame");
        jframe.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        jframe.setSize (340, 60);
        jframe.setResizable (false);
        jframe.add (jpanel);
        jframe.setVisible (true);
    }
}

有关如何解决此问题的任何建议?感谢。

2 个答案:

答案 0 :(得分:1)

删除Swing组件时,应在其容器上调用revalidate()然后repaint()

public void actionPerformed(ActionEvent event) {
    jlabel.setText("Good job!");
    jpanel.remove(jbutton);
    jpanel.revalidate();
    jpanel.repaint();
}

答案 1 :(得分:0)

试试这个:

jlabel.setText ("Good job!");
jbutton.setVisible (false);
jpanel.remove (jbutton);
jpanel.repaint();

删除后重新绘制面板,并关闭可见性。