17.下拉框选择一项,显示对应的图片
效果:

package com.lvshitech.gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JComBoxDemo extends JPanel {
JLabel picture, text;
public JComBoxDemo() {
// 字符数组
String []pStrings = {"cup", "cat", "boy", "girl"};
// ComBox
JComboBox pList = new JComboBox(pStrings);
pList.setSelectedIndex(0);
pList.addActionListener(new PictureSourceActionListener());
// picture
picture = new JLabel(new ImageIcon("images/" + pStrings[pList.getSelectedIndex()] + ".JPG"));
picture.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
picture.setPreferredSize(new Dimension(180, 140));
// text
text = new JLabel(pStrings[pList.getSelectedIndex()], JLabel.CENTER);
setLayout(new BorderLayout());
// 添加到容器
add(pList, BorderLayout.NORTH);
add(picture, BorderLayout.CENTER);
add(text, BorderLayout.SOUTH);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
public static void main(String[] args) {
JFrame frame = new JFrame("使用JComBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JComBoxDemo());
frame.pack();
frame.setVisible(true);
}
private class PictureSourceActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String pName = (String)cb.getSelectedItem();
picture.setIcon(new ImageIcon("images/" + pName + ".JPG"));
text.setText(pName);
text.setHorizontalAlignment(JLabel.CENTER);
}
}
}

浙公网安备 33010602011771号