我正在用java编写一个简单的2D游戏。到目前为止,我有一个GGame类,基本上描述了整个游戏/它的状态。与此GGame的唯一互动是通过
GGame#render(width, height) : BufferedImage
和
GGame#addEvent(event) : void
当游戏启动时,会创建一个JFrame,并将一个扩展JPanel的GamePanel添加到该帧中。 GamePanel正在做各种事情,从发送事件到GGame并渲染/重绘自己。
现在我想在GGame之上添加一个GUI(库存,其他一些信息......)。我的想法是简单地让GUI扩展JPanel并将其添加到框架中,就像GamePanel一样,而GUI则引用GGame来询问库存等。
要明确这一点,我不想在GGame旁边添加GUI,但最重要的是。我的问题是我总是需要传递给两个面板的所有事件,而顶层(GUI)是透明的。此外,我希望两个面板都能自动适应窗口大小(GamePanel通过每次渲染时获取面板大小来实现这一点。)
实现类似这样的事情的最佳方式是什么?
答案 0 :(得分:2)
以下是两个具有您请求功能的面板的演示。 请参阅评论。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
public class LayeredPaneDemo extends JFrame{
private JLayeredPane layeredPane;
private RedPanel redPanel;
private YellowPanel yellowPanel;
public LayeredPaneDemo() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(300, 310));
//Create and set up the layered pane.
layeredPane = new JLayeredPane();
//create a red panel
redPanel = new RedPanel();
redPanel.setBackground(Color.RED);
//make it the same size as parent
redPanel.setBounds(getBounds());
//at it to layered pane with index of 1
layeredPane.add(redPanel, 1);
//similarly make yellow panel
yellowPanel = new YellowPanel (redPanel); //yellow panel has a reference
//to red panel
yellowPanel.setBackground(Color.YELLOW);
yellowPanel.setBounds(getBounds());
layeredPane.add(yellowPanel, 2);
//add a mouse listener to both panels
redPanel.addMouseListener(getMouseListener(yellowPanel));
yellowPanel.addMouseListener(getMouseListener(redPanel));
setContentPane(layeredPane);
layeredPane.setLayout(new BorderLayout(0, 0));
setVisible(true);
}
//mouse listener: when a panel is clicked, the other panel
//is moved to front
private MouseListener getMouseListener(JPanel panel) {
return new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
layeredPane.moveToFront(panel);
}
};
}
public class RedPanel extends JPanel {
RedPanel(){
}
//returns a fixed value
public int getValue() {
return 16;
}
}
public class YellowPanel extends JPanel {
YellowPanel(RedPanel redPanel){
//add a label showing value retrieved from red panel
add(new JLabel("Value from red panel is :"+ redPanel.getValue()));
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new LayeredPaneDemo();
}
});
}
}
根据需要,不要犹豫要求澄清。
(以上也说明了https://stackoverflow.com/help/mcve。它更容易
帮助并获得有关MCVE的问题的帮助。