Jlabel,Jtextfield,Jbutton不会立即显示在我生气的GUI中

时间:2020-02-02 22:52:11

标签: java swing jbutton jlabel jtextfield

我在GUI上显示元素时遇到问题。我正在创建一个非常简单的程序,在该程序中,我要求用户在三个不同的框中输入三个不同的整数,并在按下按钮时将这些数字加在一起。现在,我已经创建了一个按钮,一个文本字段和一个标签,但是有一个问题:该按钮,文本字段和标签没有出现在GUI上。我必须将鼠标悬停在按钮区域上才能使其显示并与文本字段相同。即使我将鼠标悬停在原本应该显示的位置,标签也不会显示。为什么会这样呢?这是我的代码

import javax.swing.*;

public class ButtonPractice extends javax.swing.JFrame
{

    public static void main(String[] args)
    {

        JFrame box = new JFrame("Simple addition");
        box.setVisible(true);
        box.setSize(500,500);
        box.setResizable(false);
        box.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        panel.setLayout(null);
        box.add(panel);

        JTextField inputNumOne = new JTextField("Integer here");
        inputNumOne.setBounds(225,50,200,30);
        panel.add(inputNumOne);

        JLabel labelNumOne = new JLabel("First integer");
        labelNumOne.setBounds(100,50,150,50);
        panel.add(labelNumOne);


        JButton combiner = new JButton("Concactentate");
        //positioning of the button on the panel
        combiner.setBounds(175,300,125,50);

        panel.add(combiner);

    }

}

在此先感谢审核代码的人!

1 个答案:

答案 0 :(得分:0)

致电 box.getContentPane().add(panel);

创建面板后。然后打电话

box.setVisible(true)

您也不应该将布局管理器设置为null。首先,可以将其保留为默认的FlowLayout

enter image description here