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();
}
});
}
}
ゲームパネル クラス
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 クラスは実際には、現在 1 つのパネル (背景パネル) を持つ JPanel です。今のところ、私はそれを青い背景にしたいだけです。
いくつかの例を見て、私が持っているものとかなり似ていたので、このように入れてみましたが、何らかの理由で機能させることができません....
ありがとう、あら