我有这段代码(一个包含其他 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){
EventQueue.invokeLater(() -> {
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);
frame.setVisible(true);
});
}
}
我认为将我的 JTagPanelTest
放入 JScrollPane
中以使其滚动就足够了,但事实并非如此,我真的不知道为什么。
计算内部面板的最终高度是没有用的,因为它的结果是0
。
请注意,JButton
的数量不固定,因此面板必须可滚动才能显示所有“按钮”。
有人可以让我意识到我的错误吗?
谢谢
最佳答案
您尝试了正确的方法,在 scrollPane
上设置首选大小。
所以恢复到那个改变。它不滚动的原因是因为您的内容没有添加为垂直对齐。设置布局有助于垂直添加项目。
例如:
test.setLayout(new BoxLayout(test, BoxLayout.Y_AXIS));
//test.setPreferredSize(new Dimension(200, 100));
scrollPane.setPreferredSize(new Dimension(200, 180));
关于java - 面板不想滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59437536/