首页 > 解决方案 > 无法在滚动窗格上滚动 - 垂直框对齐

问题描述

我有一个带有 4 个文本窗格的窗口,它垂直地超出窗口。文本窗格位于 JPanel 内,该 JPanel 位于滚动条内。我的问题是,滚动条没有出现。我猜,这是因为我将 jPanel 布局设置为绝对。但是,如果我更改布局,则无法控制文本窗格的高度和 Y 轴上的位置。

这是我的窗口的样子。我希望能够向下滚动以查看所有 4 个文本窗格: 在此处输入图像描述

这是我的简化代码:

    frame = new JFrame();
    frame.setBounds(100, 100, 500, 540);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);


    // Scroll Pane
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(0, 0, 500, 503);
    frame.getContentPane().add(scrollPane);

    // JPanel container for the text panes
    JPanel panel = new JPanel();
    scrollPane.setViewportView(panel);
    panel.setLayout(null);

    // There is 4 TextPanes, that goes out of the window vertically.
    // I want to have control over height and spacing between textpanes.
    JTextPane txt1 = new JTextPane();
    JTextPane txt2 = new JTextPane();
    JTextPane txt3 = new JTextPane();
    JTextPane txt4 = new JTextPane();
    txt1.setBounds(0, 0, 500, 150);
    txt2.setBounds(0, 200, 500, 150);
    txt3.setBounds(0, 400, 500, 150);
    txt4.setBounds(0, 600, 500, 150);
    txt1.setBackground(Color.ORANGE);
    txt2.setBackground(Color.RED);
    txt3.setBackground(Color.ORANGE);
    txt4.setBackground(Color.RED);
    panel.add(txt1);
    panel.add(txt2);
    panel.add(txt3);
    panel.add(txt4);

解决方案(编辑):

我将 jPanel 设置为垂直框布局而不是绝对布局,并使用“首选大小”而不是使用边界来定义文本窗格的宽度。结果我的文本窗格长出了窗口,我可以向下滚动以查看它们!归功于@camickr

标签: javaswinglayoutscrollpane

解决方案


推荐阅读