java 中JSlider和Jspinner的使用
2个回答
展开全部
import javax.swing.*;
import java.awt.Color;
import java.awt.Container;
import java.util.Calendar;
import java.util.Date;
public class SpinnerDemo extends JPanel {
public SpinnerDemo(boolean cycleMonths) {
super(new SpringLayout());
String[] labels = {"Month: ", "Year: ", "Another Date: "};
int numPairs = labels.length;
Calendar calendar = Calendar.getInstance();
JFormattedTextField ftf = null;
//Add the first label-spinner pair.
String[] monthStrings = getMonthStrings(); //get month names
SpinnerListModel monthModel = null;
if (cycleMonths) { //use custom model
monthModel = new CyclingSpinnerListModel(monthStrings);
} else { //use standard model
monthModel = new SpinnerListModel(monthStrings);
}
JSpinner spinner = addLabeledSpinner(this,
labels[0],
monthModel);
//Tweak the spinner's formatted text field.
ftf = getTextField(spinner);
if (ftf != null ) {
ftf.setColumns(8); //specify more width than we need
ftf.setHorizontalAlignment(JTextField.RIGHT);
}
//Add second label-spinner pair.
int currentYear = calendar.get(Calendar.YEAR);
SpinnerModel yearModel = new SpinnerNumberModel(currentYear, //initial value
currentYear - 100, //min
currentYear + 100, //max
1); //step
//If we're cycling, hook this model up to the month model.
if (monthModel instanceof CyclingSpinnerListModel) {
((CyclingSpinnerListModel)monthModel).setLinkedModel(yearModel);
}
spinner = addLabeledSpinner(this, labels[1], yearModel);
//Make the year be formatted without a thousands separator.
spinner.setEditor(new JSpinner.NumberEditor(spinner, "#"));
//Add the third label-spinner pair.
Date initDate = calendar.getTime();
calendar.add(Calendar.YEAR, -100);
Date earliestDate = calendar.getTime();
calendar.add(Calendar.YEAR, 200);
Date latestDate = calendar.getTime();
SpinnerModel dateModel = new SpinnerDateModel(initDate,
earliestDate,
latestDate,
Calendar.YEAR);//ignored for user input
spinner = addLabeledSpinner(this, labels[2], dateModel);
spinner.setEditor(new JSpinner.DateEditor(spinner, "MM/yyyy"));
//Lay out the panel.
SpringUtilities.makeCompactGrid(this,
numPairs, 2, //rows, cols
10, 10, //initX, initY
6, 10); //xPad, yPad
}
/**
* Return the formatted text field used by the editor, or
* null if the editor doesn't descend from JSpinner.DefaultEditor.
*/
public JFormattedTextField getTextField(JSpinner spinner) {
JComponent editor = spinner.getEditor();
if (editor instanceof JSpinner.DefaultEditor) {
return ((JSpinner.DefaultEditor)editor).getTextField();
} else {
System.err.println("Unexpected editor type: "
+ spinner.getEditor().getClass()
+ " isn't a descendant of DefaultEditor");
return null;
}
}
/**
* DateFormatSymbols returns an extra, empty value at the
* end of the array of months. Remove it.
*/
static protected String[] getMonthStrings() {
String[] months = new java.text.DateFormatSymbols().getMonths();
int lastIndex = months.length - 1;
if (months[lastIndex] == null
|| months[lastIndex].length() <= 0) { //last item empty
String[] monthStrings = new String[lastIndex];
System.arraycopy(months, 0,
monthStrings, 0, lastIndex);
return monthStrings;
} else { //last item not empty
return months;
}
}
static protected JSpinner addLabeledSpinner(Container c,
String label,
SpinnerModel model) {
JLabel l = new JLabel(label);
c.add(l);
JSpinner spinner = new JSpinner(model);
l.setLabelFor(spinner);
c.add(spinner);
return spinner;
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SpinnerDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.add(new SpinnerDemo(false));
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/*
* SliderDemo.java requires all the files in the images/doggy
* directory.
*/
public class SliderDemo extends JPanel
implements ActionListener,
WindowListener,
ChangeListener {
//Set up animation parameters.
static final int FPS_MIN = 0;
static final int FPS_MAX = 30;
static final int FPS_INIT = 15; //initial frames per second
int frameNumber = 0;
int NUM_FRAMES = 14;
ImageIcon[] images = new ImageIcon[NUM_FRAMES];
int delay;
Timer timer;
boolean frozen = false;
//This label uses ImageIcon to show the doggy pictures.
JLabel picture;
public SliderDemo() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
delay = 1000 / FPS_INIT;
//Create the label.
JLabel sliderLabel = new JLabel("Frames Per Second", JLabel.CENTER);
sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
//Create the slider.
JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL,
FPS_MIN, FPS_MAX, FPS_INIT);
framesPerSecond.addChangeListener(this);
//Turn on labels at major tick marks.
framesPerSecond.setMajorTickSpacing(10);
framesPerSecond.setMinorTickSpacing(1);
framesPerSecond.setPaintTicks(true);
framesPerSecond.setPaintLabels(true);
framesPerSecond.setBorder(
BorderFactory.createEmptyBorder(0,0,10,0));
Font font = new Font("Serif", Font.ITALIC, 15);
framesPerSecond.setFont(font);
//Create the label that displays the animation.
picture = new JLabel();
picture.setHorizontalAlignment(JLabel.CENTER);
picture.setAlignmentX(Component.CENTER_ALIGNMENT);
picture.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLoweredBevelBorder(),
BorderFactory.createEmptyBorder(10,10,10,10)));
updatePicture(0); //display first frame
//Put everything together.
add(sliderLabel);
add(framesPerSecond);
add(picture);
setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
//Set up a timer that calls this object's action handler.
timer = new Timer(delay, this);
timer.setInitialDelay(delay * 7); //We pause animation twice per cycle
//by restarting the timer
timer.setCoalesce(true);
}
/** Add a listener for window events. */
void addWindowListener(Window w) {
w.addWindowListener(this);
}
//React to window events.
public void windowIconified(WindowEvent e) {
stopAnimation();
}
public void windowDeiconified(WindowEvent e) {
startAnimation();
}
public void windowOpened(WindowEvent e) {}
public void windowClosing(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
/** Listen to the slider. */
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusting()) {
int fps = (int)source.getValue();
if (fps == 0) {
if (!frozen) stopAnimation();
} else {
delay = 1000 / fps;
timer.setDelay(delay);
timer.setInitialDelay(delay * 10);
if (frozen) startAnimation();
}
}
}
public void startAnimation() {
//Start (or restart) animating!
timer.start();
frozen = false;
}
public void stopAnimation() {
//Stop the animating thread.
timer.stop();
frozen = true;
}
//Called when the Timer fires.
public void actionPerformed(ActionEvent e) {
//Advance the animation frame.
if (frameNumber == (NUM_FRAMES - 1)) {
frameNumber = 0;
} else {
frameNumber++;
}
updatePicture(frameNumber); //display the next picture
if ( frameNumber==(NUM_FRAMES - 1)
|| frameNumber==(NUM_FRAMES/2 - 1) ) {
timer.restart();
}
}
/** Update the label to display the image for the current frame. */
protected void updatePicture(int frameNum) {
//Get the image if we haven't already.
if (images[frameNumber] == null) {
images[frameNumber] = createImageIcon("images/doggy/T"
+ frameNumber
+ ".gif");
}
//Set the image.
if (images[frameNumber] != null) {
picture.setIcon(images[frameNumber]);
} else { //image not found
picture.setText("image #" + frameNumber + " not found");
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = SliderDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SliderDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SliderDemo animator = new SliderDemo();
//Add content to the window.
frame.add(animator, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
animator.startAnimation();
}
public static void main(String[] args) {
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
需要的图片自己加载了。
import java.awt.Color;
import java.awt.Container;
import java.util.Calendar;
import java.util.Date;
public class SpinnerDemo extends JPanel {
public SpinnerDemo(boolean cycleMonths) {
super(new SpringLayout());
String[] labels = {"Month: ", "Year: ", "Another Date: "};
int numPairs = labels.length;
Calendar calendar = Calendar.getInstance();
JFormattedTextField ftf = null;
//Add the first label-spinner pair.
String[] monthStrings = getMonthStrings(); //get month names
SpinnerListModel monthModel = null;
if (cycleMonths) { //use custom model
monthModel = new CyclingSpinnerListModel(monthStrings);
} else { //use standard model
monthModel = new SpinnerListModel(monthStrings);
}
JSpinner spinner = addLabeledSpinner(this,
labels[0],
monthModel);
//Tweak the spinner's formatted text field.
ftf = getTextField(spinner);
if (ftf != null ) {
ftf.setColumns(8); //specify more width than we need
ftf.setHorizontalAlignment(JTextField.RIGHT);
}
//Add second label-spinner pair.
int currentYear = calendar.get(Calendar.YEAR);
SpinnerModel yearModel = new SpinnerNumberModel(currentYear, //initial value
currentYear - 100, //min
currentYear + 100, //max
1); //step
//If we're cycling, hook this model up to the month model.
if (monthModel instanceof CyclingSpinnerListModel) {
((CyclingSpinnerListModel)monthModel).setLinkedModel(yearModel);
}
spinner = addLabeledSpinner(this, labels[1], yearModel);
//Make the year be formatted without a thousands separator.
spinner.setEditor(new JSpinner.NumberEditor(spinner, "#"));
//Add the third label-spinner pair.
Date initDate = calendar.getTime();
calendar.add(Calendar.YEAR, -100);
Date earliestDate = calendar.getTime();
calendar.add(Calendar.YEAR, 200);
Date latestDate = calendar.getTime();
SpinnerModel dateModel = new SpinnerDateModel(initDate,
earliestDate,
latestDate,
Calendar.YEAR);//ignored for user input
spinner = addLabeledSpinner(this, labels[2], dateModel);
spinner.setEditor(new JSpinner.DateEditor(spinner, "MM/yyyy"));
//Lay out the panel.
SpringUtilities.makeCompactGrid(this,
numPairs, 2, //rows, cols
10, 10, //initX, initY
6, 10); //xPad, yPad
}
/**
* Return the formatted text field used by the editor, or
* null if the editor doesn't descend from JSpinner.DefaultEditor.
*/
public JFormattedTextField getTextField(JSpinner spinner) {
JComponent editor = spinner.getEditor();
if (editor instanceof JSpinner.DefaultEditor) {
return ((JSpinner.DefaultEditor)editor).getTextField();
} else {
System.err.println("Unexpected editor type: "
+ spinner.getEditor().getClass()
+ " isn't a descendant of DefaultEditor");
return null;
}
}
/**
* DateFormatSymbols returns an extra, empty value at the
* end of the array of months. Remove it.
*/
static protected String[] getMonthStrings() {
String[] months = new java.text.DateFormatSymbols().getMonths();
int lastIndex = months.length - 1;
if (months[lastIndex] == null
|| months[lastIndex].length() <= 0) { //last item empty
String[] monthStrings = new String[lastIndex];
System.arraycopy(months, 0,
monthStrings, 0, lastIndex);
return monthStrings;
} else { //last item not empty
return months;
}
}
static protected JSpinner addLabeledSpinner(Container c,
String label,
SpinnerModel model) {
JLabel l = new JLabel(label);
c.add(l);
JSpinner spinner = new JSpinner(model);
l.setLabelFor(spinner);
c.add(spinner);
return spinner;
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SpinnerDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.add(new SpinnerDemo(false));
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/*
* SliderDemo.java requires all the files in the images/doggy
* directory.
*/
public class SliderDemo extends JPanel
implements ActionListener,
WindowListener,
ChangeListener {
//Set up animation parameters.
static final int FPS_MIN = 0;
static final int FPS_MAX = 30;
static final int FPS_INIT = 15; //initial frames per second
int frameNumber = 0;
int NUM_FRAMES = 14;
ImageIcon[] images = new ImageIcon[NUM_FRAMES];
int delay;
Timer timer;
boolean frozen = false;
//This label uses ImageIcon to show the doggy pictures.
JLabel picture;
public SliderDemo() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
delay = 1000 / FPS_INIT;
//Create the label.
JLabel sliderLabel = new JLabel("Frames Per Second", JLabel.CENTER);
sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
//Create the slider.
JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL,
FPS_MIN, FPS_MAX, FPS_INIT);
framesPerSecond.addChangeListener(this);
//Turn on labels at major tick marks.
framesPerSecond.setMajorTickSpacing(10);
framesPerSecond.setMinorTickSpacing(1);
framesPerSecond.setPaintTicks(true);
framesPerSecond.setPaintLabels(true);
framesPerSecond.setBorder(
BorderFactory.createEmptyBorder(0,0,10,0));
Font font = new Font("Serif", Font.ITALIC, 15);
framesPerSecond.setFont(font);
//Create the label that displays the animation.
picture = new JLabel();
picture.setHorizontalAlignment(JLabel.CENTER);
picture.setAlignmentX(Component.CENTER_ALIGNMENT);
picture.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLoweredBevelBorder(),
BorderFactory.createEmptyBorder(10,10,10,10)));
updatePicture(0); //display first frame
//Put everything together.
add(sliderLabel);
add(framesPerSecond);
add(picture);
setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
//Set up a timer that calls this object's action handler.
timer = new Timer(delay, this);
timer.setInitialDelay(delay * 7); //We pause animation twice per cycle
//by restarting the timer
timer.setCoalesce(true);
}
/** Add a listener for window events. */
void addWindowListener(Window w) {
w.addWindowListener(this);
}
//React to window events.
public void windowIconified(WindowEvent e) {
stopAnimation();
}
public void windowDeiconified(WindowEvent e) {
startAnimation();
}
public void windowOpened(WindowEvent e) {}
public void windowClosing(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
/** Listen to the slider. */
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusting()) {
int fps = (int)source.getValue();
if (fps == 0) {
if (!frozen) stopAnimation();
} else {
delay = 1000 / fps;
timer.setDelay(delay);
timer.setInitialDelay(delay * 10);
if (frozen) startAnimation();
}
}
}
public void startAnimation() {
//Start (or restart) animating!
timer.start();
frozen = false;
}
public void stopAnimation() {
//Stop the animating thread.
timer.stop();
frozen = true;
}
//Called when the Timer fires.
public void actionPerformed(ActionEvent e) {
//Advance the animation frame.
if (frameNumber == (NUM_FRAMES - 1)) {
frameNumber = 0;
} else {
frameNumber++;
}
updatePicture(frameNumber); //display the next picture
if ( frameNumber==(NUM_FRAMES - 1)
|| frameNumber==(NUM_FRAMES/2 - 1) ) {
timer.restart();
}
}
/** Update the label to display the image for the current frame. */
protected void updatePicture(int frameNum) {
//Get the image if we haven't already.
if (images[frameNumber] == null) {
images[frameNumber] = createImageIcon("images/doggy/T"
+ frameNumber
+ ".gif");
}
//Set the image.
if (images[frameNumber] != null) {
picture.setIcon(images[frameNumber]);
} else { //image not found
picture.setText("image #" + frameNumber + " not found");
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = SliderDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SliderDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SliderDemo animator = new SliderDemo();
//Add content to the window.
frame.add(animator, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
animator.startAnimation();
}
public static void main(String[] args) {
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
需要的图片自己加载了。
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
试过,完全可以。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询