Java JScrollpane不可见

use*_*219 8 java swing

我正试图在一个按钮中显示一系列按钮JScrollpane.阅读时,我设法退出此代码,但没有显示任何内容.我不明白可能的错误.谢谢你的帮助

正如我所做的那样,我做了一些修改,但我编辑了但没有作

编辑 或我是愚蠢的,或者这是一些其他问题.这是我输出图像的完整代码

public class Main extends javax.swing.JFrame {
    private final JPanel gridPanel;

    public Main() {
        initComponents();
        // EXISTING PANEL
        gridPanel = new JPanel();
        JScrollPane scrollPane = new JScrollPane(gridPanel);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        JPanel borderLayoutPanel = new JPanel(new BorderLayout());
        borderLayoutPanel.add(scrollPane, BorderLayout.CENTER);

        this.Avvio();
    }

    private void Avvio() {
        JPanel pane = new JPanel(new GridBagLayout());
        pane.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        pane.setLayout(new GridBagLayout());

        for (int i = 0; i < 10; i++) {
            JButton button;
            GridBagConstraints c = new GridBagConstraints();
            c.fill = GridBagConstraints.HORIZONTAL;
            c.anchor = GridBagConstraints.PAGE_START;

            button = new JButton("Button 1");
            c.weightx = 0.5;
            c.gridx = 0;
            c.gridy = i;
            pane.add(button, c);

            button = new JButton("Button 2");
            c.gridx = 1;
            c.gridy = i;
            pane.add(button, c);

            button = new JButton("Button 3");
            c.gridx = 2;
            c.gridy = i;
            pane.add(button, c);

        }
        gridPanel.add(pane);
        gridPanel.revalidate();
        gridPanel.repaint();

    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Tam*_*Rev 1

要使其发挥作用,需要做几件事:

  1. 添加一个main方法
  2. main方法是入口点。这确保了 swing 代码在 AWT 线程中运行。这就是它的SwingUtilities.invokeLater用途
  3. 实例化、打包并显示框架。大小设置仅用于试验滚动窗格
  4. 将 声明gridPanel为实例变量
  5. 包裹gridPanelscrollPane
  6. 或者,scrollPaneborderLayoutPanel
  7. 调用该Avvio方法,因为这是添加按钮的方法
  8. 将最外面的元素添加到框架中

这是固定代码:

public class MyFrame extends javax.swing.JFrame {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            MyFrame frame = new MyFrame();
            frame.pack();
            frame.setSize(600, 300);
            frame.setVisible(true);
        });
    }

    private JPanel gridPanel;

    public MyFrame() {
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        gridPanel = new JPanel(new GridLayout(0, 1));
        JScrollPane scrollPane = new JScrollPane(gridPanel);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        JPanel borderLayoutPanel = new JPanel(new BorderLayout());
        borderLayoutPanel.add(scrollPane, BorderLayout.CENTER);
        this.Avvio();
        this.add(borderLayoutPanel, BorderLayout.CENTER);
    }


    private void Avvio() {...}
}
Run Code Online (Sandbox Code Playgroud)