Как загрузить картинку? - Java
Формулировка задачи:
здраствуйте!!! как загрузить картинку, помогите.
[/JAVA]
[JAVA]
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ComboBox extends JPanel
implements ActionListener {
JLabel picture;
public ComboBoxDemo() {
super(new BorderLayout());
String[] petStrings = { "Птица", "Кошка", "Собака", "Кролик", "Свинья" };
JComboBox petList = new JComboBox(petStrings);
petList.setSelectedIndex(4);
petList.addActionListener(this);
//Set up the picture.
picture = new JLabel();
picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
picture.setHorizontalAlignment(JLabel.CENTER);
updateLabel(petStrings[petList.getSelectedIndex()]);
picture.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
picture.setPreferredSize(new Dimension(177, 122+10));
add(petList, BorderLayout.PAGE_START);
add(picture, BorderLayout.PAGE_END);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String petName = (String)cb.getSelectedItem();
updateLabel(petName);
}
protected void updateLabel(String name) {
ImageIcon icon = createImageIcon("изображения/" + name + ".gif");
picture.setIcon(icon);
picture.setToolTipText("рисунок " + name.toLowerCase());
if (icon != null) {
picture.setText(null);
} else {
picture.setText("Image не найдена");
}
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = ComboBoxDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Не удалось найти файл: " + path);
return null;
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("ComboBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new ComboBoxDemo();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}Решение задачи: «Как загрузить картинку?»
textual
Листинг программы
ImageIcon icon = createImageIcon("images/" + name + ".gif");