栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使JScrollPane每个鼠标滚轮步长滚动1行?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使JScrollPane每个鼠标滚轮步长滚动1行?

出于纯粹的兴趣(有点无聊),我创建了一个工作示例:

public class Main {    private JTable table;    private JList list;    private Jframe frame;    private final String[] data;        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();    }}

真正的魔力是在custom中完成的

AdjustmentListener
,我们每次都将当前的“滚动位置”增加一个单节。如示例所示,它可以上下移动并具有不同的行大小。


就像 注释中 提到的 @kleopatra一样 ,您也可以使用a

MouseWheelListener
来重新定义鼠标滚轮的行为。

请参阅此处的官方教程。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/438719.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号