【问题标题】:JScrollPane components do not appearJScrollPane 组件不出现
【发布时间】:2020-09-17 16:33:54
【问题描述】:

我试图将一些组件放入JScrollPane 中,但每次启动程序时它们都不会出现。我今天刚开始学习 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 个单词添加到滚动窗格中,以便您可以滚动通过这。

【问题讨论】:

    标签: java swing scroll components jscrollpane


    【解决方案1】:

    我今天才开始学习 GUI

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

    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 );
    

    【讨论】:

    • 非常感谢!这解决了我的问题!
    猜你喜欢
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-12-02
    • 1970-01-01
    • 2013-09-25
    相关资源
    最近更新 更多