Java Jspinner显示文件中的图像
我有一个关于Jspinner的问题,如何显示来自Jspinner的图像 在jspinner中,我们将选择image1、image2、image3。。。 在面板上,我们将显示从文件的jspinner中选择的image1Java Jspinner显示文件中的图像,java,swing,jspinner,Java,Swing,Jspinner,我有一个关于Jspinner的问题,如何显示来自Jspinner的图像 在jspinner中,我们将选择image1、image2、image3。。。 在面板上,我们将显示从文件的jspinner中选择的image1 您可以将数字范围添加到JSpinner中,然后使用if条件检查值的变化 为了获得更改值,您可以使用addChangeListener 下面是我为适应您的场景而创建的程序。我添加了评论以了解那里发生了什么。您只需对代码做一些小的更改,就可以阅读注释并理解发生了什么 package s
您可以将数字范围添加到
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);
}
}
});
}
}
希望这就是您所要求的。请阅读这篇文章@MadProgrammer我认为有一个特殊的模型和一个不可编辑的编辑器字段是可能的。@Sergiymedvynsky但是
JTextField
不显示图像-此外,为了工作量,一个标签和几个按钮会更简单:P@MadProgrammer我理解了他的问题,他想在spiner和其他地方的图标中显示一个字符串。@Sergiymedvynskey好吧,我只是感到困惑,我以为他们想要一个JSpinner
来显示图像-但我知道什么-此外,我错了,您可以使用JSpinner
来执行此操作:P