边框布局();按钮不显示

BorderLayout(); buttons not showing up

大家好,我的按钮和文本区域在编译时不会显示在 JFrame 上,我已经尝试了所有方法并搜索了该站点,但没有成功。任何帮助将不胜感激。由于他们不让我 post 没有更多细节,我只是添加这部分以便我可以点击提交按钮。

import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class DataManager extends JFrame {

private String students[] = {"John Smith","Ken Hanson","Michael Li","John Andersen","Fiona Harris","Angela Lim","Bob London","Sydney Shield","Tina Gillard",
                             "Ross Brinns","Scott Cairns","Grant Peterson","David Power","Joshua Kane","Alan Newton","Frady Morgan","Quinn Perth"};


private int english[] = {80,52,71,61,39,62,31,46,60,26,77,40,58,38,94,90,97};

private int maths[] = {60,45,77,90,45,55,66,87,31,42,65,55,80,71,51,55,95};

private int total[];

private JButton sortNameButton;

private JButton sortTotalButton;

private JTextField searchTextField;

private JButton statisticsButton;

private JButton exitButton;

private JTextArea infoTextArea;

private JPanel jPan;


public DataManager() {

super("Data Manager ");

jPan = new JPanel();

sortNameButton = new JButton("Sort By Name");

sortTotalButton = new JButton("Sort By Total");

searchTextField = new JTextField("Search");

statisticsButton = new JButton("Statistics");

exitButton = new JButton("Exit");

infoTextArea = new JTextArea();

setLayout(new BorderLayout());

jPan.add(sortNameButton, BorderLayout.NORTH);
jPan.add(sortTotalButton, BorderLayout.NORTH);
jPan.add(searchTextField, BorderLayout.NORTH);
jPan.add(statisticsButton, BorderLayout.NORTH);
jPan.add(exitButton, BorderLayout.NORTH);
jPan.add(infoTextArea, BorderLayout.CENTER);


}

public static void main(String[] args) {

    DataManager frame = new DataManager();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800,600);
    frame.setVisible(true);

} // End of main method.

} // End of DataManager class

您将 JButton 添加到 jPan JPanel,但永远不要将 jPan 添加到任何东西 -- 它必须添加到您的 JFrame,this 才能看到。

jPan.add(sortNameButton);
jPan.add(sortTotalButton);
jPan.add(searchTextField);
jPan.add(statisticsButton);
jPan.add(exitButton);
jPan.add(infoTextArea);

add(jPan);  // don't forget this! ************

注意其他问题:

  • 您将 JFrame 的布局设置为 BorderLayout -- 已经 使用 BorderLayout
  • 您使用 BorderLayout 常量将组件添加到 jPan JPanel,但不是 使用 BorderLayout。
  • 如果是,许多按钮将不会被看到,因为许多按钮被添加到 相同的 BorderLayout 位置并且将覆盖之前添加的组件。

换句话说,请在做出错误假设时阅读教程。

更好的是:

    // setLayout(new BorderLayout());
    jPan.setLayout(new BorderLayout());

    JPanel northPanel = new JPanel();  // **** to hold buttons

    northPanel.add(sortNameButton);
    northPanel.add(sortTotalButton);
    northPanel.add(searchTextField);
    northPanel.add(statisticsButton);
    northPanel.add(exitButton);

    jPan.add(northPanel, BorderLayout.PAGE_START);
    jPan.add(infoTextArea, BorderLayout.CENTER);