我需要将JPanel扩展类传递给主类。
这是我到目前为止的内容:
主班
import java.awt.Color;
import javax.swing.*;
public class main {
private gamePanel gamepanel = new gamePanel();
public JPanel createContentPane(){
// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
//We set the Layout Manager to null so we can manually place
// the Panels.
totalGUI.setLayout(null);
//Now we create a new panel and add it to the bottom JPanel.
totalGUI.add(gamepanel);
totalGUI.setOpaque(true);
return totalGUI;
}
private static void createAndShowGUI(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("[=] There's a JPanel in here! [=]");
//Create and set up the content pane.
main demo = new main();
frame.setContentPane(demo.createContentPane());
//The other bits and pieces that make your program a bit more stable.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700,500);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a jog for the event-dispatching thread:
//creating and showing this application's GUI.
System.out.println(gamepanel);
SwingUtilities.invokeLater(new Runnable() {
public void run(){
createAndShowGUI();
}
});
}
}
gamePanel类
public class gamePanel extends JPanel implements Commons {
private Dimension d;
private ArrayList snowmens;
private coreFunctions functions = new coreFunctions();
private int snowmenX = 150;
private int snowmenY = 5;
private final String snowmenpix = "snowman.png";
private JPanel background;
public gamePanel() {
add(new JLabel("TEST"));
setFocusable(true);
setDoubleBuffered(true);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(0, 0, 700, 700);
}
}
我不知道为什么没有显示蓝色背景和标签...
编辑:
以下是更多详细信息:
好的,所以我正在尝试制作2D游戏。为此,我需要在gamePanel类上创建一些雪人,并通过主类显示它。首先,createContentPane创建一个背景面板,如果需要,则创建根面板。 createandshowgui创建一个JFrame。
实际上,gamepanel类是一个JPanel,它到目前为止有1个面板,这是背景面板。现在,我只希望它具有蓝色背景。
我之所以这样说是因为我看到了一些示例,它们与我的示例非常相似,但是由于某些原因,我无法使其正常工作...。
谢谢,
阿拉
最佳答案
您应该使用LayoutManager
而不是setLayout(null);
,并且如果仅添加一个组件也不需要它(除非添加其他组件,否则该组件将拉伸以填充)。
请参阅此处以获取有关LayoutManager
的教程:
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
如果您想要做的只是具有蓝色背景(可以在上面添加组件),则只需覆盖paintComponent()
的gamePanel
并将背景涂成蓝色:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
}
那么您可以添加
JLabel
,就好像它是普通面板一样,因为背景现在被涂成蓝色,而不是由组件/作为组件设置。如果您有图像,请查看
g.drawImage(Image image,int x,int y,ImageObserver iO)
编辑
致电:
setLayout(null);
它会工作