2014-12-21 7 views
2

JButton을 클릭하면 JButton을 제거하고 싶습니다.JFrame에서 JButton을 제거하려면 어떻게해야합니까?

나는 remove 메소드를 사용해야한다는 것을 알고 있지만 작동하지 않습니다.

어떻게하면됩니까? 여기

내 코드입니다 :

class Game implements ActionListener { 

JFrame gameFrame; 
JButton tmpButton; 
JLabel tmpLabel1, tmpLabel2, tmpLabel3, tmpLabel4; 

public void actionPerformed(ActionEvent e) { 
    gameFrame.remove(tmpLabel1); 
    gameFrame.getContentPane().validate(); 
    return; 
} 

Game(String title) { 
    gameFrame = new JFrame(title); 
    gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    gameFrame.setBounds(100, 100, 300, 500); 
    gameFrame.setResizable(false); 
    gameFrame.getContentPane().setLayout(null); 

    tmpLabel4 = new JLabel(new ImageIcon("./images/bomber.jpg")); 
    tmpLabel4.setSize(200, 200); 
    tmpLabel4.setLocation(50, 100); 
    tmpButton = new JButton("Play"); 
    tmpButton.setSize(100, 50); 
    tmpButton.setLocation(100, 350); 
    tmpButton.addActionListener(this); 

    gameFrame.getContentPane().add(tmpLabel4); 
    gameFrame.getContentPane().add(tmpButton); 
    gameFrame.setVisible(true); 
} 
} 
+0

처럼 버튼)/다시 칠 숨기기()'. 또한 Absolute Positioning을 사용하지 말고 정품 Layout Manager를 사용하십시오. –

+0

@ GáborBakos 당신은'JFrame # remove'가'contentPane'에 대한 호출에 위임 할 수 있다는 것을 알고 계십니까? 그것은 항상 좋은 생각입니다.) – MadProgrammer

+2

Java GUI는 다른 OS, 화면 크기, 화면 해상도 등에서 작동해야합니다. 따라서 픽셀 완벽한 레이아웃에 도움이되지 않습니다. 대신 레이아웃 관리자 또는 [조합] (http://stackoverflow.com/a/5630271/418556)과 [공백] 레이아웃 채우기 및 테두리 (http://stackoverflow.com/a/17874718/)를 사용하십시오. 418556). –

답변

2

가장 간단한 솔루션을 수 있습니다 ...

... 몇 가지 아이디어로

Container parent = buttonThatWasClicked.getParent(); 
parent.remove(buttonThatWasClicked); 
parent.revaidate(); 
parent.repaint(); 

... ... 부모의 버튼이 있는지 확인하셔야의 actionPerformed 방법의 모든

1

우선 클릭했는지 여부. 단추를 클릭하면 제거하십시오.

public void actionPerformed(ActionEvent event){ 
    tmpButton.setVisible(false); 
} 

을 button.But 단추의 : 코드를위한 작품을 제거하는 대신 버튼을 숨기고 후 사용할 수있는 경우

if(e.getSource() == tmpButton){ 
    gameFrame.getContentPane().remove(tmpButton); 
} 

당신의 actionPerformed 방법

4

이 추가 방법은 다음과 같습니다 : 제거되지 않은 상태로 숨겨져 있습니다.

0

버튼을 jframe에 추가하지 않고 원하는 각 구성 요소를 추가하십시오! 은`JButton` 제거 이미 볼 용기에

public void actionPerformed(ActionEvent event) 
{ 
    //gameFrame.getContentPane().add(tmpButton); -=> "Commented Area" 
    gameFrame.getContentPane().validate(); 
} 

또는 먼저 (재 검증`호출 할 필요는이

public void actionPerformed(ActionEvent event) 
{ 
    tmpButton.setVisible(false); 
} 
관련 문제