面板不想滚动

问题描述 投票:0回答:1

我有这段代码(一个包含其他JComponent的面板,在这种情况下为JButton的面板)和一个问题。

import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.util.*;

public class JTagPanelTest extends JPanel{

    public JTagPanelTest(){
        setLayout(new FlowLayout(FlowLayout.LEADING, 2, 0));
    }

    public void initializeTags(List<String> tags){
        tags.forEach(tag -> add(new JButton(tag)));
    }

    public static void main(String[] args){
        try{
            String lookAndFeelName = UIManager.getSystemLookAndFeelClassName();
            UIManager.setLookAndFeel(lookAndFeelName);
        }
        catch(Exception e){
            e.printStackTrace();
        }

        JTagPanelTest test = new JTagPanelTest();
        test.initializeTags(Arrays.asList("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
            "012", "qwer", "z<xc", "rty", "poiu", "gfj", "zxcv", "mjnb", "mko", "nij", "bhu"));
        JScrollPane scrollPane = new JScrollPane(test);
        scrollPane.setHorizontalScrollBar(null);
        test.setPreferredSize(new Dimension(200, 100));
        //scrollPane.setPreferredSize(new Dimension(200, 180));
        JFrame frame = new JFrame("Test");
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(new Dimension(200, 180));
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        EventQueue.invokeLater(() -> frame.setVisible(true));
    }

}

尽管我足以将我的JTagPanelTest放在JScrollPane内以使其滚动,但事实并非如此,我真的不知道为什么。

[计算内部面板的最终高度是没有用的,因为它得出0

请注意,JButton的数目不是固定的,因此面板必须是可滚动的才能显示所有“按钮”。

有人可以让我知道我的错误吗?

谢谢

java swing jscrollpane jcomponent
1个回答
0
投票

您通过在scrollPane上设置首选大小尝试了正确的方法。

所以恢复到该更改。它不滚动的原因是您的内容没有添加为垂直对齐。设置布局以帮助垂直添加项目。

例如:

test.setLayout(new BoxLayout(test, BoxLayout.Y_AXIS));
//test.setPreferredSize(new Dimension(200, 100));
scrollPane.setPreferredSize(new Dimension(200, 180));
© www.soinside.com 2019 - 2024. All rights reserved.