首页 > 解决方案 > JScrollPane 组件不出现

问题描述

我试图将一些组件放入 aJScrollPane但每次启动程序时它们都不会出现。我今天刚开始学习 GUI,所以我想我错过了一些小东西,但无论我在哪里上网,我都找不到答案。唯一出现的就是它JScrollPane自己。

class MainFrame extends JFrame{
    public MainFrame(String title){
        //Main Frame Stuff
        super(title);
        setSize(655, 480);
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

        //Layout
        FlowLayout flow = new FlowLayout();
        setLayout(flow);

        //Components
        JButton spam_button = new JButton("Print");
        JLabel label = new JLabel("What do you want to print?",
                                  JLabel.LEFT);
        JTextField user_input = new JTextField("Type Here", 20);

        //Scroll Pane
        JScrollPane scroll_pane = new JScrollPane(
                ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scroll_pane.setPreferredSize(new Dimension(640, 390));

        //Adding to Scroll
        scroll_pane.add(label);
        scroll_pane.add(user_input);
        scroll_pane.add(spam_button);

        //Adding to the Main Frame
        add(scroll_pane);

        //Visibility
        setVisible(true);
    }
}

该程序的重​​点是打印您键入的任何内容 100 次,但我还没有做到这一点,因为我一直被这个滚动问题所困扰。当我最终将内容显示在滚动窗格中时JPanel,我会将这三个组件移动到滚动窗格上方,然后将 100 个单词添加到滚动窗格中,以便您可以滚动浏览它。

标签: javaswingscrollcomponentsjscrollpane

解决方案


我今天才开始学习 GUI

所以首先要从 Swing 教程开始。有大量的演示代码可供下载、测试和修改。

scroll_pane.add(label);
scroll_pane.add(user_input);
scroll_pane.add(spam_button);

JScrollPane 不像 JPanel:

  1. 您不会将组件直接添加到滚动面板。您将组件添加到viewport滚动窗格
  2. 只能将单个组件添加到视口。

所以你的代码应该是这样的:

JPanel panel = new JPanel();
panel.add(label);
panel.add(user_input);
panel.add(spam_button);
scrollPane.setViewportView( panel );

推荐阅读