我正试图创建一个基本的游戏,角色可以在屏幕上移动图像,这是在背景图像的顶部。这里是我的主要方法,我设置所有这些:在一个框架上显示多个面板
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
public void run(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Stuff");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a panel with a component to be moved
JPanel character = new JPanel();
JLabel component = new JLabel();
component.setIcon(new ImageIcon("C:/Users/Cory/Desktop/img/eagle.jpg"));
component.setSize(component.getPreferredSize());
component.setLocation(200, 200);
component.repaint();
JButton left = addMotionSupport(component);
character.add(component);
character.repaint();
//end moveable
frame.add(character);
frame.repaint();
JPanel background = new JPanel();
JLabel contentPane = new JLabel();
contentPane.setIcon(new ImageIcon("C:/Users/Cory/Desktop/img/background.png"));//sets contentPane to display the background
contentPane.setSize(contentPane.getPreferredSize());
background.add(contentPane);
background.repaint();
frame.add(background);
frame.repaint();
//frame.add(left, BorderLayout.SOUTH);
frame.setSize(1000, 800);
frame.setVisible(true);
}
});
}
我遇到的问题如下。我能够显示可移动图像的背景图像或,但不能同时显示。我相信发生的事情是两个jpanels在彼此之上“重叠” - 这是正确的吗?我将如何解决这样的事情?我浏览了一下API,发现了一个名为JLayeredPane的东西,但我不确定如何使用它,以及它是否是正确的工具。你提供的任何洞察力将是最受赞赏的。
N.B. 'addMotionSupport'方法只会将一个KeyListener添加到传递的参数中。
JFrame的默认布局管理器是'BorderLayout'。此布局允许其5个部分(北部,南部,东部,西部,中部)中的每个部分都有一个组件。您将两个组件添加到相同的中心部分,因此您添加的第二个组件只是替换第一个组件。您不能像这样将组件叠加在彼此之上。 – BoDidely
以下是关于如何使用'JLayeredPane'的文档,这是一种分层组件的方法。 http://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html。但个人而言,我会使用'Graphics2D'来代替在一个JPanel上绘制我的背景和图像。 http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics2D.html – BoDidely
您的预期输出是什么? –