Java 按钮未显示在 JFrame 上

2 java swing jpanel jframe

我对java相当陌生,我正在启动一种词汇表程序。一开始,我尝试使用带有按钮的 JFrame。

但当我运行它时只显示 1 个按钮。另外,我认为按钮的位置不正确。

         package glossary;

import java.awt.BorderLayout;
import javax.swing.JFrame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;

public class Glossary {


    public static void main(String[] args) {

         JFrame frame = new JFrame("Glossary");
         frame.setVisible(true);
         frame.setSize(400,200);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);



         JPanel panel1 = new JPanel();
         frame.add(panel1);
         JButton LookUpWord = new JButton("Look up word");
         panel1.add(LookUpWord, BorderLayout.NORTH);

         JPanel panel2 = new JPanel();
         frame.add(panel2);
         JButton SubmitNewWord = new JButton("Submit word");
         panel2.add(SubmitNewWord, BorderLayout.SOUTH);

          }

}
Run Code Online (Sandbox Code Playgroud)

请告诉我我做错了什么!

whi*_*der 6

我认为您只是对在哪里添加组件感到困惑。您可能不打算将按钮添加到 NORTH 和 SOUTH,而是将面板添加到 NORTH 和 SOUTH 的框架中。另外,请等到添加完所有组件后再调用frame.setVisible(true).

尝试这个:

public static void main(String[] args) {
    JFrame frame = new JFrame("Glossary");
    frame.setSize(400, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JButton LookUpWord = new JButton("Look up word");  // create the button
    JPanel panel1 = new JPanel();  // create the panel
    panel1.add(LookUpWord);  // add the button to the panel
    frame.add(panel1, BorderLayout.NORTH);  // add the panel to the frame

    JButton SubmitNewWord = new JButton("Submit word");
    JPanel panel2 = new JPanel();
    panel2.add(SubmitNewWord);
    frame.add(panel2, BorderLayout.SOUTH);

    frame.setVisible(true);
}
Run Code Online (Sandbox Code Playgroud)