有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么JComponents不出现在框架中?

我对java相当陌生。我不能让它工作。。。我正在尝试使用以下代码添加组件:

    public class Board
    {
        public static void main(String[] args) {
           JFrame window = new JFrame("Tellraw Generator");
           window.setVisible(true);
           window.setSize(400, 600);
           window.setResizable(false);
           window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           JPanel panel = new JPanel();
           JLabel label = new JLabel();
           panel.setLayout(null);
           window.add(panel);
           //"Generate" Button
           JButton button1 = new JButton("Generate");
           button1.setBounds(262, 485, 100, 37);
           panel.add(button1);
           //"Add Text" Button
           JButton button2 = new JButton("Add Text");
           button2.setBounds(51, 337, 88, 33);
           panel.add(button2);
           //Title
           JLabel txt1 = new JLabel("Tellraw Generator");
           txt1.setFont(new Font("Minecrafter Alt Regular", Font.BOLD, 29));
           txt1.setBounds(61, 18, 278, 30);
           panel.add(txt1);
        }
    }

但是当我尝试这样做时,组件并没有显示在屏幕上

那么,有没有人能告诉我为什么它不起作用/不出现,以及我如何添加它

谢谢


共 (4) 个答案

  1. # 1 楼答案

    并且始终:将setVisible(true)调用作为最后一个调用。添加到窗口/框架的所有操作都必须在setVisible调用之前完成

  2. # 2 楼答案

    这是如何声明JTextField的

    final JTextField variableName = new JTextField(size);

    这就是从JTextField获取文本的方式

    variableName.getText()

    希望有帮助

  3. # 3 楼答案

    你是说JLabelJButton没有出现?正当不是JTextField,因为代码中没有JTextField

    无论如何,只需在末尾添加这行代码:

    window.add(panel);
    

    这里您将把包含所有JComponentJPanel添加到JFrame

  4. # 4 楼答案

    试试这个:

    public class Board
        {
            public static void main(String[] args) {
               JFrame window = new JFrame("Tellraw Generator");
               window.setVisible(true);
               window.setSize(400, 600);
               window.setResizable(false);
               window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               JPanel panel = new JPanel();
               JLabel label = new JLabel();
               panel.setLayout(null);
               window.add(panel);
               //"Generate" Button
               JButton button1 = new JButton("Generate");
               button1.setBounds(262, 485, 100, 37);
               panel.add(button1);
               //"Add Text" Button
               JButton button2 = new JButton("Add Text");
               button2.setBounds(51, 337, 88, 33);
               panel.add(button2);
               //Title
               JTextField txt1 = new JTextField ();
               txt1.setFont(new Font("Minecrafter Alt Regular", Font.BOLD, 29));
               txt1.setBounds(61, 18, 278, 30);
               panel.add(txt1);
            }
        }