[英]I am trying to make a GUI in Java.I created the frame, but the panel doesn't show up. What is wrong?
When everything was in one class, it was working. 当一切都在一堂课时,它就在工作。 I tried to separate them to obtain a more "structured" code, but now only the frame shows up. 我试图分离它们以获得更“结构化”的代码,但是现在只显示框架。
My Main-class: 我的主班:
public class Main {
public static void main(String[] args) {
GraphicInterface gameInterface;
gameInterface = new GraphicInterface();
}
}
GraphicInterface-class: GraphicInterface类:
public class GraphicInterface {
public GraphicInterface() {
GameFrame gameFrame = new GameFrame();
MainPanel menuPanel = new MainPanel();
gameFrame.addPanel(menuPanel);
menuPanel.setVisible(true);
}
}
GameFrame-class: GameFrame类:
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GameFrame extends JFrame {
public GameFrame() {
JFrame gameFrame = new JFrame("Games");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setResizable(false);
gameFrame.getContentPane().setLayout(null);
gameFrame.setSize(905, 700);
gameFrame.setVisible(true);
}
public void addPanel(JPanel menuPanel) {
this.add(menuPanel);
}
}
MainPanel-class: MainPanel类:
import java.awt.Color;
import javax.swing.JPanel;
public class MainPanel extends JPanel {
public MainPanel() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(null);
mainPanel.setBounds(0, 0, 905, 700);
mainPanel.setBackground(new Color(243, 207, 252));
mainPanel.setVisible(true);
}
}
You intend to use a GameFrame
object as your JFrame
, but GameFrame
creates a brand new other frame for no reason. 您打算将GameFrame
对象用作JFrame
,但是GameFrame
创建了一个全新的其他框架。 So just avoid this and use only your GameFrame
: 因此,避免这种情况,只使用您的GameFrame
:
public GameFrame() {
super("Games");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
getContentPane().setLayout(null);
setSize(905, 700);
setVisible(true);
}
In the same way , you want to use a MainPanel
object as a container, but it creates a new JPanel
which will be discarded without being used at all, so as above : 同样,您希望将MainPanel
对象用作容器,但是它将创建一个新的JPanel
,该JPanel
将被丢弃而根本不使用,如下所示:
public MainPanel() {
setLayout(null);
setBounds(0, 0, 905, 700);
setBackground(new Color(243, 207, 252));
setVisible(true);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.