我想在组合框中选择一个城市后在右侧的标签中显示图像,但是尽管代码语法中没有错误,但是该图像没有显示,并且也没有显示错误执行后在图像文件夹的路径中。
任何帮助将不胜感激。
import javax.swing.JFrame;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.util.Hashtable;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class App {
private JFrame frame;
JLabel picture;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
App window = new App();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
private Hashtable subItems = new Hashtable();
public App() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.DARK_GRAY);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
String[] items = { "Select City", "Fes", "Sefrou", "Moulay Yaacoub" };
JComboBox comboBox = new JComboBox(items);
comboBox.setForeground(Color.BLACK);
comboBox.setBackground(Color.WHITE);
comboBox.setBounds(30, 32, 157, 20);
frame.getContentPane().add(comboBox);
String[] subItems1 = { "Select Fes", "1", "2", "3" };
subItems.put(items[1], subItems1);
String[] subItems2 = { "Select Sefrou", "1", "2", "3" };
subItems.put(items[2], subItems2);
String[] subItems3 = { "Select Moulay Yaacoub", "1", "2", "3" };
subItems.put(items[3], subItems3);
comboBox.setSelectedIndex(0);
JComboBox comboBox_1 = new JComboBox(subItems1);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String item = (String)comboBox.getSelectedItem();
Object o = subItems.get( item );
if (o == null)
{
comboBox_1.setModel( new DefaultComboBoxModel() );
}
else
{
comboBox_1.setModel( new DefaultComboBoxModel( (String[])o ) );
}
}
});
comboBox_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String petName = (String)cb.getSelectedItem();
updateLabel(petName);
}
});
comboBox_1.setBounds(30, 63, 157, 20);
frame.getContentPane().add(comboBox_1);
JLabel Picture = new JLabel();
updateLabel(subItems1[comboBox_1.getSelectedIndex()]);
Picture.setBounds(236, 32, 188, 130);
frame.getContentPane().add(Picture);
}
private void updateLabel(String name) {
ImageIcon icon = createImageIcon("images/" + name + ".gif");
picture.setIcon(icon);
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = test.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
}
代码已编辑 执行后,由于此行“ picture.setIcon(icon);”,我得到了“ java.lang.NullPointerException”。 任何想法如何解决该错误?