Search code examples
javajspinner

MouseWheelListener in JSpinner JAVA


Please see my code below.. What i want is during my mouse wheel event it would scroll to a list set in my spinnermodel but unable to do it. can you help me what is appropriate code on mousewheel event?

    JSpinner lines = new JSpinner();
    lines.addMouseWheelListener(new MouseWheelListener() {
        public void mouseWheelMoved(MouseWheelEvent e) {
            lines.setValue(new Integer((Integer)lines.getValue()).intValue() - e.getWheelRotation());
        }
    });
    lines.setFont(new Font("Tahoma", Font.BOLD, 12));
    lines.setModel(new SpinnerListModel(new String[] {"P5", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", }));
    lines.setBounds(63, 11, 49, 35);
    frmHistoryRequest.getContentPane().add(lines);

This is the error i got when i execute my program

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer.

Im still new in Java programming and i have lots to learn.. Thanks for those who will help.


Solution

  • You are getting a ClassCastException because your code is trying to set the current value of the model to an Integer when your model consists of only Strings.

    The following code snippet should correctly set the current value of the model using the next and previous values from your model.

    lines.addMouseWheelListener(new MouseWheelListener() {
        public void mouseWheelMoved(MouseWheelEvent e) {
            int positiveWheelRotation = Math.abs(e.getWheelRotation());
            Object value = null;
            for(int i=0;i<positiveWheelRotation;i++) {
                if(e.getWheelRotation() > 0) 
                    value = lines.getNextValue();
                else if(e.getWheelRotation() < 0)
                    value = lines.getPreviousValue();
            }
            if(value != null)
                lines.setValue(value);
        }
    });