Java JButton仅在我将鼠标悬停在其上后出现?
我想知道为什么我的按钮直到我把鼠标悬停在它应该在的地方才出现在面板上?如果我调整窗口大小,它也会再次消失。MainMenuScreen只是我用作背景图像的图像Java JButton仅在我将鼠标悬停在其上后出现?,java,swing,jpanel,jbutton,gridbaglayout,Java,Swing,Jpanel,Jbutton,Gridbaglayout,我想知道为什么我的按钮直到我把鼠标悬停在它应该在的地方才出现在面板上?如果我调整窗口大小,它也会再次消失。MainMenuScreen只是我用作背景图像的图像 //MainMenu setup JPanel card2 = new JPanel(); card2.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.grid
//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);
}
}
下面是我如何设置的背景图像
//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);
}
}
JButton
不会显示,因为您对main菜单屏幕
组件和JButton
菜单按钮1
使用了相同的GridBagConstraints
值,即它们存在于同一位置。调整gbc
的值后,按钮将出现。在使用GridBagLayout
添加到容器时,最好始终使用正确的重载方法
编辑:
关于如何在
JPanel
容器上实现背景图像,已经有很多讨论。值得注意的是。我希望按钮显示在图像顶部。我有办法做到吗@ReimeusSure,有很多关于如何做到这一点的帖子,比如。另请参见updateI实际执行@Reimeus see edit中的一项操作。我觉得图像被视为gridbaglayout中的一个组件?您的菜单按钮1
需要添加到Main菜单屏幕中才能在按钮后面显示图像。而不是card2.add(菜单按钮1,gbc);我使用mms.add(菜单按钮1,gbc);那么,我如何将我的按钮定位到我需要的位置@莱默斯