[英]How to get scrollbar to appear on a JList when the frame is too small to show all of the JList?
I want to make a scrollbar appear on a JList whenever the frame is resized to be too small for the List itself. 每当帧的大小调整为对于List本身而言太小时,我想让JList上出现一个滚动条。 So far, this is the code I have.
到目前为止,这是我的代码。 Run it, resize the frame, and notice how no scrollbar ever appears on the 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));
}
}
Notice how there is a JScrollPane added, but no scroll bar appears on the list when the window gets really small. 请注意如何添加JScrollPane,但当窗口变得非常小时,列表中不会显示滚动条。 This is what I want to fix.
这是我想要解决的问题。
Thanks in advance! 提前致谢!
JPanel has implemented FlowLayout JPanel实现了FlowLayout
FlowLayout accepting only PreferredSize (in your case hardcoded by setSize) FlowLayout仅接受PreferredSize(在您的情况下由setSize硬编码)
FlowLayout isn't designated, not implemented any resize JComponents (layed by FlowLayout) together with container, JComponent isn't resizable, stays as it is 没有指定FlowLayout,没有实现任何调整大小的JComponents(由FlowLayout布局)和容器,JComponent不可调整大小,保持不变
don't want to commenting something about your code posted here, see differencies, quite good low level 不想评论你在这里发布的代码,看到差异,相当不错的低级别
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();
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.