Jspinner显示文件

时间:2017-05-23 04:33:35

标签: java swing jspinner

我有一个关于Jspinner的问题,如何从jspinner显示图像?

在jspinner中我们将选择image1,image2,image3 ...... 在面板上,我们将显示从文件中的jspinner中选择的image1。

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以向JSpinner添加数字范围,然后使用if条件检查更改值。

为了获得更改价值,您可以使用addChangeListener

以下是我为适合您的方案而创建的程序。我添加了评论以了解那里发生的事情。您只需对代码进行一些更改即可,您可以阅读评论并了解最新情况。

package stack;

import java.awt.GridBagLayout;

import javax.swing.*;
import javax.swing.event.*;

public class Spinner {

    public static void main(String[] args) {

        //for all the images you have
        ImageIcon icon, icon2;

        //here change image path to yours
        icon = new ImageIcon(new Object().getClass().getResource("/stack/Untitled-1.jpg"));
        //here change image path to yours
        icon2 = new ImageIcon(new Object().getClass().getResource("/stack/watermark.jpg"));

        //to display images
        JLabel label = new JLabel();
        label.setSize(300, 300);

        //if you want a image to show when window open
        //label.setIcon(iconName);
        label.setText("Switch");

        //create a jpanel to add the all component into layout
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setSize(300, 300);
        panel.add(label);

        //using spinner model you can change to fit your requirements
        SpinnerModel model = new SpinnerNumberModel(0, // initial value
                0, // minimum value
                2, // maximum value
                1); // step

        //create new spinner according to model that we create above
        JSpinner spinner = new JSpinner(model);
        spinner.setBounds(100, 100, 50, 30);

        //crete jframe and add that panel we create before
        JFrame f = new JFrame("Change images from spinner");
        f.add(panel);
        panel.add(spinner);

        f.setSize(300, 300);
        f.setLayout(null);
        f.setVisible(true);

        //To change images when changing values add ChangeListener
        spinner.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                //when number changed get that number and convert into integer
                int count = Integer.parseInt("" + ((JSpinner) e.getSource()).getValue());

                //when spinner values change you can check using count and place image you want
                if (count == 1) {
                    //set image to jLabel
                    label.setIcon(icon);
                } else if (count == 2) {
                    label.setIcon(icon2);
                }
            }
        });

    }
}

希望这就是你要求的。