구성 요소를 제거 할 때 컨테이너에 validate()
및 repaint()
을 호출하는 것을 잊지 마시고 정상적으로 작동해야합니다.
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class RemoveDemo {
static class RemoveAction extends AbstractAction{
private Container container;
public RemoveAction(Container container){
super("Remove me");
this.container = container;
}
@Override
public void actionPerformed(ActionEvent e) {
container.remove((Component) e.getSource());
container.validate();
container.repaint();
}
}
private static void createAndShowGUI() {
final JFrame frame = new JFrame("Demo");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RemoveAction action = new RemoveAction(frame);
frame.add(new JButton(action));
frame.add(new JButton(action));
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
+1 [sscce] (http://sscce.org/). 또한'Action'을 고려하십시오. – trashgod
@trashgod 감사, 액션으로 업데이트되었습니다. – tenorsax
예시. 초기 'invokeLater()'이상을 요구하는 작업 코드는 CPCookieMan (보이지 않는) 코드가 왜 멈추는 지에 대한 질문을 제기합니다. – trashgod