每当帧的大小调整为对于List本身而言太小时,我想让JList上出现一个滚动条。到目前为止,这是我的代码。运行它,调整框架大小,并注意JList上没有滚动条显示。
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class JListScroll extends JPanel{
JScrollPane listScrollPane;
public JListScroll() {
String[] stringArray = {"Testing","This","Stuff"};
JList<String> rowList = new JList<String>(stringArray);
listScrollPane = new JScrollPane();
listScrollPane.getViewport().setView(rowList);
this.setSize(new Dimension(75,200));
this.add(listScrollPane);
this.doLayout();
}
public static void main(String[] args){
JFrame frame = new JFrame();
JListScroll scrollPanel = new JListScroll();
frame.add(scrollPanel);
frame.setVisible(true);
frame.setSize(new Dimension(75,300));
}
}
注意如何添加JScrollPane,但当窗口变得非常小时,列表中不会出现滚动条。这就是我想解决的问题。
提前致谢!
答案 0 :(得分:6)
JPanel已实施FlowLayout
FlowLayout仅接受PreferredSize(在您的情况下由setSize硬编码)
没有指定FlowLayout,没有实现任何调整大小的JComponents(由FlowLayout布局)和容器,JComponent不可调整大小,保持原样
不想评论有关您在此处发布的代码的内容,请参阅差异,相当不错的低级别
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class JListScroll {
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
private JScrollPane listScrollPane = new JScrollPane();
private String[] stringArray = {"Testing", "This", "Stuff"};
private JList rowList = new JList(stringArray);
public JListScroll() {
rowList.setVisibleRowCount(2);
listScrollPane.setViewportView(rowList);
panel.setLayout(new BorderLayout());
panel.add(listScrollPane);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // EDIT
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JListScroll jListScroll = new JListScroll();
}
});
}
}
答案 1 :(得分:2)