java jpanel类_将JPanel类传递给JAVA中的主类

博主在尝试创建一个基于JPanel的小型2D游戏,遇到了JPanel的蓝色背景和标签不显示的问题。主类中,gamePanel实例被添加到JFrame的内容窗格,但背景颜色和标签未按预期显示。在gamePanel类中,覆盖了`paintComponent`方法以绘制蓝色背景,同时添加了一个JLabel,但这些改动并未生效。博主寻求帮助,希望能解决显示问题。
摘要由CSDN通过智能技术生成

我需要将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 .

游戏面板类实际上是一个JPanel,它现在有1个面板,这是背景面板 . 现在,我只希望它有蓝色背景 .

我尝试这样做因为我看到了一些例子,它们与我的相似,但由于某种原因,我无法让它工作......

谢谢,Ara

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值