简体   繁体   English

Java JFrame gui-为什么按钮不显示?

[英]Java JFrame gui - Why won't the buttons show up?

I've just started learning Swing/JFrame, basically making a GUI. 我刚刚开始学习Swing / JFrame,基本上是制作一个GUI。 I've been doing Java for a month now, just using the console, making a sin/true or false games and it is pretty easy for me now. 我已经使用Java做了一个月了,只使用控制台,制作一个正误游戏,对我来说现在很容易。

I decided to take a further step, and I must say it's totally a pain, different logic. 我决定采取进一步的措施,我必须说这完全是一种痛苦,并且是不同的逻辑。

That's what I've done so far: 到目前为止,这就是我所做的:

Main.java: Main.java:

import java.awt.*;
import javax.swing.*;
import java.io.*;

class Main {
    public static void main(String[] args) {
        final Gui gui = new Gui();
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                gui.createMyGui();
            }
         });
    }
}

gui.java gui.java

class Gui {

    protected JFrame j = new JFrame("My First window");
    protected JPanel p = new JPanel();
    protected Container c;

    public Gui() {
        j.setSize(500, 400);
        p.setSize(j.getSize());
        this.c = j.getContentPane();
    }

    public void createMyGui() {
        setButtons();
        setGuiBackground();
        j.setVisible(true);
        p.setVisible(true);
        this.c.add(p);
    }

    private void setGuiBackground() {
        this.c.setBackground(Color.green);
    }

    private void setButtons() {
        p.add(new JButton("Hey"));

    }
}

Problem 问题

I can't really get the button to show up, people are telling me to use setBounds but I am not really sure on how to start as I can't even place a button there. 我真的不能让按钮显示出来,有人告诉我要使用setBounds,但是我不确定如何启动,因为我什至不能在其中放置按钮。 I've tried searching about my problem, but no luck actually. 我曾尝试搜索我的问题,但实际上没有运气。

Basically what happens is a 500x400 green GUI opens, and that's it. 基本上会发生一个500x400绿色GUI打开,仅此而已。

Why won't the button show? 为什么按钮不显示?

people are telling me to use setBounds Dont! 人们告诉我使用setBounds Dont! Layout managers are the correct way to go. 布局管理器是正确的方法。

Your problem is you add your buttons to the "p" panel, but you never add it (p panel) to the contentPane 您的问题是您将按钮添加到“ p”面板,但从未将按钮(p面板)添加到contentPane

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM