我想知道为什么我的按钮没有显示在面板上,直到我将鼠标悬停在它的位置之后?如果我调整窗口大小,它也会再次消失。 MainMenuScreen只是我用作背景图像的图像。
//MainMenu setup
JPanel card2 = new JPanel();
card2.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2,2,2,2);
gbc.anchor = GridBagConstraints.CENTER;
MainMenuScreen mms = new MainMenuScreen();
mms.setLayout(new FlowLayout());
card2.add(mms);
card2.add(menuButton1, gbc);
以下是我按背景图片设置的方式。
public class MainMenuScreen extends JPanel{
private static final long serialVersionUID = 1L;
private BufferedImage background;
public MainMenuScreen() {
try {
background = ImageIO.read(new File("M&M Arcade.png"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
int x = (getWidth() - background.getWidth());
int y = (getHeight() - background.getHeight());
g.drawImage(background, x, y, this);
}
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.white);
}
}
答案 0 :(得分:1)
由于JButton
组件和GridBagConstraints
MainMenuScreen
使用相同的JButton
值,menuButton1
不会显示,即它们存在在同一个地方。调整gbc
的值后,将显示该按钮。使用GridBagLayout
添加到容器时,最好始终使用add的正确重载方法。
修改:
关于如何在JPanel
容器上实现背景图像的讨论很多。值得注意的是Background Panel。