我有一个JScrollPane其内容窗格是JXList。 当我使用鼠标滚轮在名单上,名单步骤同时三(3)项。 这也适用于表,不管行的高度。 我怎样才能改变这种做法, - 不管是什么平台的 - 两个名单和表格的滚动距离正好是1项? 设置块增量不剪,因为表中的某些行有不同的高度。
Answer 1:
纯粹是出于兴趣(和一点点无聊)的我创建了一个工作示例:
/**
* Scrolls exactly one Item a time. Works for JTable and JList.
*
* @author Lukas Knuth
* @version 1.0
*/
public class Main {
private JTable table;
private JList list;
private JFrame frame;
private final String[] data;
/**
* This is where the magic with the "just one item per scroll" happens!
*/
private final AdjustmentListener singleItemScroll = new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
// The user scrolled the List (using the bar, mouse wheel or something else):
if (e.getAdjustmentType() == AdjustmentEvent.TRACK){
// Jump to the next "block" (which is a row".
e.getAdjustable().setBlockIncrement(1);
}
}
};
public Main(){
// Place some random data:
Random rnd = new Random();
data = new String[120];
for (int i = 0; i < data.length; i++)
data[i] = "Set "+i+" for: "+rnd.nextInt();
for (int i = 0; i < data.length; i+=10)
data[i] = "<html>"+data[i]+"<br>Spacer!</html>";
// Create the GUI:
setupGui();
// Show:
frame.pack();
frame.setVisible(true);
}
private void setupGui(){
frame = new JFrame("Single Scroll in Swing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
frame.add(split);
// Add Data to the table:
table = new JTable(new AbstractTableModel() {
@Override
public int getRowCount() {
return data.length;
}
@Override
public int getColumnCount() {
return 1;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex];
}
});
for (int i = 0; i < data.length; i+=10)
table.setRowHeight(i, 30);
JScrollPane scroll = new JScrollPane(table);
// Add out custom AdjustmentListener to jump only one row per scroll:
scroll.getVerticalScrollBar().addAdjustmentListener(singleItemScroll);
split.add(scroll);
list = new JList<String>(data);
scroll = new JScrollPane(list);
// Add out custom AdjustmentListener to jump only one row per scroll:
scroll.getVerticalScrollBar().addAdjustmentListener(singleItemScroll);
split.add(scroll);
}
public static void main(String[] agrs){
new Main();
}
}
真正神奇的是在定制完成AdjustmentListener
,我们去哪里,并通过每次一个单块增加当前“滚动位置”。 这工作上下不同行的大小,如图所示的例子。
正如评论@kleopatra提到的,你也可以使用一个MouseWheelListener
只重新定义了鼠标滚轮的行为。
请参阅官方教程这里 。
Answer 2:
一个简单的解释太多的代码:
JLabel lblNewLabel = new JLabel("a lot of line of text...");
JScrollPane jsp = new JScrollPane(lblNewLabel);
jsp.getVerticalScrollBar().setUnitIncrement(10); //the bigger the number, more scrolling
frame.getContentPane().add(jsp, BorderLayout.CENTER);
文章来源: How to make JScrollPane scroll 1 line per mouse wheel step?