java - GUI 显示空白

标签 java user-interface

这是我的问题。我只是想为 friend 的生日写一个漂亮的小应用程序。问题是当我运行程序时,我最初得到一个空白的 GUI。但是,如果我稍微调整一下窗口的边框,问题就会像预期的那样出现。

这仅在我放入 JTextArea 后发生。所有要做的就是显示文本。它不会用于输入文本。关于我做错了什么的任何建议?我要越过 JFrame 的范围吗?

感谢您的帮助。

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

public class Birthday {

  private JFrame mainFrame;
  private JPanel mainPanel;
  private JPanel labelPanel;
  private JPanel buttonPanel;
  private JButton story;
  private JButton misc;
  private JButton next;
  private JLabel mainLabel;

  private JFrame miscFrame;
  private JPanel miscPanel;
  private JLabel miscLable;

  private JTextArea text;

  public Birthday(){
    gui();
  }

  public static void main(String [] args){
    Birthday b = new Birthday();

  }

  public void gui(){
    mainFrame = new JFrame("The Buttercup Project"); //main window
    mainFrame.setVisible(true);
    mainFrame.setSize(550,650);
    //mainFrame.setResizable(false);
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    text = new JTextArea(30,35);

    mainPanel = new JPanel(); //displays content in window
    mainPanel.setBackground(Color.YELLOW);
    mainPanel.setVisible(true);
    mainPanel.add(text);

    labelPanel = new JPanel();
    labelPanel.setVisible(true);
    labelPanel.setBackground(Color.LIGHT_GRAY);

    buttonPanel = new JPanel();
    buttonPanel.setVisible(true);
    buttonPanel.setBackground(Color.LIGHT_GRAY);


    story = new JButton("Story"); //button
    misc = new JButton("?");
    next = new JButton ("Next Story");
    mainLabel = new JLabel("The Buttercup Project"); //label


    labelPanel.add(mainLabel); //adds buttons to panel
    buttonPanel.add(story, BorderLayout.CENTER);
    buttonPanel.add(misc, BorderLayout.CENTER);
    buttonPanel.add(next, BorderLayout.CENTER);

    mainFrame.add(labelPanel,BorderLayout.NORTH );
    mainFrame.add(buttonPanel, BorderLayout.AFTER_LAST_LINE);

    mainFrame.add(mainPanel,BorderLayout.CENTER );  //put panel inside of frame

  }

}

最佳答案

您不需要在每个面板上调用 setVisible()。您只需为包含它们的 JFrame 执行一次;您还应该在添加所有组件后执行此操作。此外,请务必调用 mainFrame.pack() 以便计算正确的大小。

关于java - GUI 显示空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12486873/

相关文章:

java - Swing GridBagLayout 组件调整大小

python - 防止 Kivy 留下调试信息

java - 如何在字符串中伪装转义字符 -\"

java - 如何使用特定算法设置数组的元素?

java - 重新创建 jpa 元模型

c++ - 确保一个小部件有一个容器?

eclipse - 是否有任何用于 Eclipse 的用户界面原型(prototype)设计工具?

java - 第一个计时器..java异常

Java - 另存为 RTF 不支持文本对齐?

java - 如何使 View 的宽度相对正确