如何让每个鼠标滚轮步骤滚动1行JScr​​ollPane?

我有一个JScrollPane,其内容窗格是一个JXList。 当我在列表上使用鼠标滚轮时,列表一次只能处理三(3)个项目。 无论行高如何,这也适用于表格。 我怎样才能改变这一点 – 无论平台如何 – 对于列表和表格,滚动距离恰好是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] = ""+data[i]+"
Spacer!"; // 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(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来重新定义鼠标滚轮的行为。

请参阅此处的官方教程。

太多代码用于简单解释:

 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);