获取文件.png图像以使用 java.awt 和 java.swing 显示在帧上



我试图让图像显示在我创建的游戏的框架上。我没有扩展任何 JPanels 或 JFrame,我只是创建多个框架类和一个操作类。我目前无法在我创建的测试帧上显示图像。我的代码可以编译,但是当我单击框架时,它会关闭。谢谢!

附言这只是我代码的一部分。我听说在网上发布总代码不好。

法典:

public void testframe(){
testframe = new Frame("Main Menu");
testframe.setSize(1600,1600);
try{
myPicture = ImageIO.read(new File("basic.png"));
}
catch(IOException e){
e.printStackTrace();
//FirstFrame.setVisible(true);
//testframe.setVisible(false);
}
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
testframe.add(picLabel);
//testframe.drawImage(myPicture,"png", );
testframe.setVisible(true);
}
private void showButtonDemo(){
Font myFont = new Font("Serif", Font.ITALIC | Font.BOLD, 12);
Font newFont = myFont.deriveFont(50F);
headerLabel.setText("SNAKE GAME"); 
headerLabel.setFont(newFont);
statusLabel.setText("By Tejas and Ashwin");
statusLabel.setFont(newFont);
Button startButton = new Button("Start Game");//begins game
Button snakecolorButton = new Button("Choose Snake Color");//selects snake color
Button themeColorButton = new Button("Choose Theme");//selects two colors(1 primary and 1 secondary)
Button InstructionsButton = new Button("Instructions");
Button testbutton = new Button("test");
testbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//testframe();
//testframe.setVisible(true);
FirstFrame.setVisible(false);
}
});

首先,共享代码需要帮助,所以如果你认为代码无论如何都涉及你需要帮助分享它的内容,否则没关系...... 对于手头的问题,您可以使用 jlable 并为其设置 iamge 以显示 png,但执行此操作的最佳方法是为游戏创建此内容是创建一个类(例如 Player(和一个渲染方法,在渲染时,您将图像显示在播放器的位置 (XYZ(,

ImageIcon image = new ImageIcon("C:\Users\Name\Pictures\image.png");
JLabel imageLabel = new JLabel(image); 
frame.add(imageLabel);

请记住将其设置为可见并设置其边界,

最新更新