package swing.boomlink.jcombobox.t;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
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.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class SelectReportStyel extends JPanel implements ActionListener {
JLabel picture; //定义图片标签
public SelectReportStyel() {
super(new BorderLayout());
//创建combobox选择项,5中报表格式,从0开始
String petStrings[] = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
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(40, 30, 30, 30));
/* 创建一个占用空间但没有绘制的空边框,指定了顶线、底线、左边框线和右边框线的宽度。 */
// The preferred size is hard-coded to be the width of the
// widest image and the height of the tallest image + the border.
picture.setPreferredSize(new Dimension(207, 152 + 40)); // 设置此组件的首选大小
// Lay out the demo.
add(petList, BorderLayout.PAGE_START);
add(picture, BorderLayout.PAGE_END);
setBorder(BorderFactory.createEmptyBorder(90, 90, 90, 90)); //整个窗体大小
}
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
String petName = (String) cb.getSelectedItem();
updateLabel(petName);
}
public void updateLabel(String name) {
ImageIcon icon = createImageIcon("images/" + name + ".gif");
picture.setIcon(icon);
picture.setToolTipText("这是图片的提示文字" + "a drawing of a"
+ name.toLowerCase());
if (icon != null) {
picture.setText(null);
} else {
picture.setText("图片未找到");
}
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = SelectReportStyel.class.getResource(path);
if (imgURL != null) {
System.out.println(imgURL);
return new ImageIcon(imgURL);
} else {
System.err.println("没有找到图片" + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
public static void createAndShowGUI() {
// create and setup the window
JFrame frame = new JFrame("ComboBox的测试例子");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create and set up content pane
JComponent newContentPane = new SelectReportStyel();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
// display the window
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}