【发布时间】:2019-09-28 17:53:56
【问题描述】:
我有一个程序,它本质上应该是一些游戏的标题屏幕。背景是 GIF(我不确定这是否会导致问题),我需要一些 JButtons 来运行实际游戏。问题是JButton 有时仅在我将鼠标悬停在它上面时才会出现(并且在那一瞬间),否则它是不可见的。它工作得很好,进入游戏等等,它只是不可见的。
我试图查看问题是否在于我使用的是 GIF 以及 paintComponent() 方法,不过,当我使用 JPEG 时它没有出现。
代码如下:
public class TestingGrounds extends JFrame{
//declarations
JButton snakeButton;
JPanel snakeButtonPanel;
JFrame window;
Container con;
TitleScreenHandler tsHandler = new TitleScreenHandler();
//constructor
public TestingGrounds(){
//main JFrame
window = new JFrame("Title Screen");
window.add(new ImagePanel());
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(1831, 1030);
window.setVisible(true);
window.setLocationRelativeTo(null);
window.setLayout(null);
con = window.getContentPane();
//panel for the button to go to the snake game
snakeButtonPanel = new JPanel();
snakeButtonPanel.setBounds(100,100,600,150);
//button to go to snake game
snakeButton = new JButton("Snake");
snakeButton.setBackground(Color.BLACK);
snakeButton.setForeground(Color.WHITE);
snakeButton.setFont(new Font("Times New Roman", Font.ITALIC, 30));
snakeButton.addActionListener(tsHandler);
snakeButton.setFocusPainted(false);
//adding button to panel
snakeButtonPanel.add(snakeButton);
//adding panel to container
con.add(snakeButtonPanel);
//setting the panel as visible
snakeButtonPanel.setVisible(true);
}
//main method for running constructor
public static void main(String[] args) {
new TestingGrounds();
}
//what to do if the button is pressed
public class TitleScreenHandler implements ActionListener {
public void actionPerformed(ActionEvent event){
//goes to main game screen if start button is pressed
new SnakeGame();
}
}
}
//class for using the gif
class ImagePanel extends JPanel {
Image image;
public ImagePanel() {
image = Toolkit.getDefaultToolkit().createImage("C:/Users/eklut/Desktop/Coding/ICS4U1/src/graphicsstuff/snek/source.gif");
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
抱歉,我知道这是相当多的代码,但我觉得我必须展示所有这些,因为我不确定问题出在哪里。
我预计按钮会显示在 gif 上,但它几乎似乎正在以相反的方式发生
【问题讨论】:
-
“我不确定这是否会导致问题” 您是否尝试过删除 GIF?但是 1+ 对于几乎完整的minimal reproducible example,我们无法访问您的图片,请使用来自互联网链接的图片。
-
@Frakcool “我们无权访问您的图片,请使用来自 Internet 链接的图片。” 有多种图片类型和尺寸可用于 hot-来自this Q&A 的链接,我为此特定目的放在一起。例如。 This answer 指向嵌入在 this question 中的图像的热链接。
-
@AndrewThompson 那是我正在寻找的链接,但不记得是你的链接还是 camickr 的问答,当我写那个评论时,我脑子里正是那个帖子,谢谢分享跨度>
标签: java swing user-interface awt