0
이 문제가 발생했습니다. JPanel에서 기존의 모든 구성 요소를 제거하고 버튼 클릭 후 또 다른 새로운 기능을 추가하고 싶습니다. 이제 버튼을 클릭하면 왼쪽 상단에 동일한 버튼이 추가되지만 아무 것도 클릭 할 수 없습니다.구성 요소를 제거하고 다시 칠할 수 없습니다.
public class MainPanel extends JPanel implements ActionListener{
private Image backgroundImage;
private Image startScreen;
private boolean gameStarted = false;
private SingleplayerButton button1;
private MultiplayerButton button2;
public MainPanel() {
String imgUrl = "graphics/";
try {
startScreen = ImageIO.read(new File(imgUrl+"start.png"));
} catch (IOException e) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, e);
}
backgroundImage = startScreen;
this.setLayout(null);
button1 = new SingleplayerButton(this);
button1.addActionListener(this);
this.add(button1);
button2 = new MultiplayerButton(this);
button2.addActionListener(this);
this.add(button2);
}
@Override
protected void paintComponent(Graphics g) {
if(gameStarted == false) {
g.drawImage(backgroundImage, 0, 0, null);
} else {
this.removeAll();
this.setBackground(Color.WHITE);
this.revalidate();
}
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1) {
gameStarted = true;
this.repaint();
// something more
} else if(e.getSource() == button2) {
gameStarted = true;
this.repaint();
// something more
}
}
실제 SSCCE를 게시 할 수 있습니까? 이 코드는 심지어 컴파일되지 않습니다. –
super.paintComponent (g)를 호출하지 않아 내용이 사라지지 않을 수도 있습니다. paintComponent 메소드의 맨 위에. 그래픽이 필요하지 않으면 paintComponent 메소드에서 제거, 재확인 및 다시 그리기가 필요하지 않은 경우 아래 답변에 동의합니다. 리스너 –
@ FelipeO.Thomé에서 paintComponent() 메서드는 패널의 자식을 그리는 작업을 수행하지 않습니다. paint() 메서드는 자식을 칠합니다. 자세한 내용은 [페인팅 메커니즘을 자세히 살펴보십시오.] (http://docs.oracle.com/javase/tutorial/uiswing/painting/closer.html)를 참조하십시오. – camickr