Haven't you been vexed of using that mini text field like editor (the default editor) for JSpinner? Well, I am. So I thought of changing it and started searching for the method and hurray! I got it.
The setEditor() method. This is taking a JComponent and replacing the default editor with the given component. Fine, I got a problem here, the value in the JComponent (the custom editor) isn't updated!!
How will it update? So ridiculous, isn't it? Because we've got a custom a component set as the editor and we need to look after value changes and update the component accordingly. How could we do it then? We need to add a ChangeListener for that!
In this example, I'll set a JButton as editor and the value in the JSpinner is updated on the JButton.
The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)
The setEditor() method. This is taking a JComponent and replacing the default editor with the given component. Fine, I got a problem here, the value in the JComponent (the custom editor) isn't updated!!
How will it update? So ridiculous, isn't it? Because we've got a custom a component set as the editor and we need to look after value changes and update the component accordingly. How could we do it then? We need to add a ChangeListener for that!
In this example, I'll set a JButton as editor and the value in the JSpinner is updated on the JButton.
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
class JSpinnerCustomEditor extends JFrame
{
JSpinner s1;
JButton jb;
public JSpinnerCustomEditor()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("JSpinner Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
s1=new JSpinner();
s1.setValue(10);
jb=new JButton("Current value "+s1.getValue());
s1.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent ce)
{
jb.setText("Current value "+s1.getValue());
}
});
// Size of jb is automatically adjusted!!
s1.setEditor(jb);
add(s1);
setSize(400,400);
setVisible(true);
}
public static void main(String args[])
{
new JSpinnerCustomEditor();
}
}
The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)
No comments:
Post a Comment