Slo*_*ong 3 java swing button paintcomponent
这是存在问题的JPanel类:
public class EntryDialog extends JPanel{
private static final long serialVersionUID = 1L;
MainWindow mainWindow;
Image background;
JButton continueresume;
JButton newresume;
JButton settings;
JButton exit;
public EntryDialog(MainWindow mainWindow){
continueresume = new JButton("Continue resume");
newresume = new JButton("New resume");
settings = new JButton("Settings");
exit = new JButton("Exit");
this.mainWindow = mainWindow;
this.background = Utilities.getImage("images\\entryDialogBackground.jpg", true);
this.setLayout(null);
//continueresume button
continueresume.setBounds(Utilities.getScaledWidth(1150),
Utilities.getScaledHeight(150),
Utilities.getScaledWidth(500),
Utilities.getScaledHeight(50));
//newresume button
newresume.setBounds(Utilities.getScaledWidth(1150),
Utilities.getScaledHeight(220),
Utilities.getScaledWidth(500),
Utilities.getScaledHeight(50));
//settings button
settings.setBounds(Utilities.getScaledWidth(1150),
Utilities.getScaledHeight(290),
Utilities.getScaledWidth(500),
Utilities.getScaledHeight(50));
//exit button
exit.setBounds(Utilities.getScaledWidth(1150),
Utilities.getScaledHeight(360),
Utilities.getScaledWidth(500),
Utilities.getScaledHeight(50));
this.add(continueresume);
this.add(newresume);
this.add(settings);
this.add(exit);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
if(background != null){
g2d.drawImage(background, 0, 0, this);
}
g2d.dispose();
}
Run Code Online (Sandbox Code Playgroud)
将此JPanel绘制到另一类的主框架上。发生的是“背景”被很好地绘制,但按钮却没有。一旦我将鼠标悬停在按钮上,这些按钮就会出现,但直到那时它们都是不可见的。我已经搜索了几个小时,还没有找到解决方案,所以我们将不胜感激。谢谢!
小智 5
我不得不猜测它正在您的paintComponent方法中发生。您正在调用super.paintComponent()会像平常一样绘制所有内容,包括按钮。然后,使用g2d.drawImage()对其进行绘制。您应该先绘制背景。