0
我想知道爲什麼我的按鈕沒有顯示在面板上,直到我將鼠標懸停在它將會出現的位置之後?如果我調整窗口大小,它也會消失。 MainMenuScreen只是一張我用作背景圖片的圖片。JButton只在我將鼠標懸停在它上面之後纔出現?
//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);
}
}
我想按鈕顯示在圖像的頂部。有沒有辦法可以做到這一點? @Reimeus – mstep91 2013-03-16 18:09:24
當然,有很多關於如何可以完成的帖子,如[這裏](http://stackoverflow.com/questions/299495/java-swing-how-to-add-an-image-to-一個-的JPanel)。另請參閱更新 – Reimeus 2013-03-16 18:31:23
我實際上做了其中的@Reimeus 請參閱編輯。 我覺得圖像被視爲gridbaglayout中的組件? – mstep91 2013-03-16 18:42:16