Custom JSpinner Model / Editor

Hello,

This question may have been answered in the past but I could not find anything. I am trying to use a JSpinner for cycling through pages of information. I would like the display to show current page of total number of pages, i.e. 1 of 10. I would also like the user to be able to enter a number and have the spinner display that number in the same format. I am not quite sure if I need to create a custom model and editor or expand the SpinnerNumberModel. Any guidance is much appreciated.

[508 byte] By [rogerrhodya] at [2007-10-3 10:33:57]
# 1

this might be one way for the '1 of 10', for entering a number, just add a keyListener,

and modify the methods accordingly

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

class Testing

{

JSpinner spinner;

JTextField tf;

final int TOTAL_PAGES = 10;

int currentPage;

public void buildGUI()

{

tf = new JTextField(10);

tf.setHorizontalAlignment(JTextField.RIGHT);

tf.setEditable(false);

tf.setBackground(Color.WHITE);

spinner = new JSpinner();

spinner.setUI(new MyUI());

spinner.setEditor(tf);

changeValue(1);

JFrame f = new JFrame();

f.getContentPane().add(spinner);

f.pack();

f.setLocationRelativeTo(null);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

}

public void changeValue(int amount)

{

try

{

int newPageNumber = currentPage+amount;

if(newPageNumber < 1 || newPageNumber > TOTAL_PAGES)

{

java.awt.Toolkit.getDefaultToolkit().beep();

return;

}

tf.setText(newPageNumber+" of "+TOTAL_PAGES);

currentPage = newPageNumber;

}

catch(Exception e){e.printStackTrace();}

}

class MyUI extends javax.swing.plaf.basic.BasicSpinnerUI

{

protected Component createNextButton()

{

JButton btnNext = (JButton)super.createNextButton();

btnNext.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

changeValue(1);}});

return btnNext;

}

protected Component createPreviousButton()

{

JButton btnPrevious = (JButton)super.createPreviousButton();

btnPrevious.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

changeValue(-1);}});

return btnPrevious;

}

}

public static void main(String[] args)

{

SwingUtilities.invokeLater(new Runnable(){

public void run(){

new Testing().buildGUI();

}

});

}

}

Michael_Dunna at 2007-7-15 5:57:10 > top of Java-index,Desktop,Core GUI APIs...