62,614
社区成员
发帖
与我相关
我的任务
分享
package test;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
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;
public class colorApp extends JFrame implements ActionListener {
private String[] color = { "红", "黄", "蓝", "绿", "黑", "白" };
JLabel picture;
JComboBox imgList;
public int count = 0;
public colorApp() {
imgList = new JComboBox();
for (int i = 1; i < 7; i++)
imgList.addItem(color[count++]);
imgList.addActionListener(this);
Container cp = getContentPane();
cp.add(imgList);
picture = new JLabel(
new ImageIcon("image/" + imgList.getSelectedItem()));
picture.setOpaque(true); // JLabel默认是透明的,所以直接setBackground()没用.需加入此句
picture.setBackground(Color.red);
picture.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
getContentPane().add(imgList, BorderLayout.NORTH);
getContentPane().add(picture, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(240, 200);
}
public void actionPerformed(ActionEvent e) {
JComboBox jb = (JComboBox) e.getSource();
String s = jb.getSelectedItem().toString();
if (s == "红") {
picture.setOpaque(true);
picture.setBackground(Color.red);
}
if (s == "黄") {
picture.setOpaque(true);
picture.setBackground(Color.yellow);
}
if (s == "蓝") {
picture.setOpaque(true);
picture.setBackground(Color.blue);
}
if (s == "绿") {
picture.setOpaque(true);
picture.setBackground(Color.green);
}
if (s == "黑") {
picture.setOpaque(true);
picture.setBackground(Color.black);
}
if (s == "白") {
picture.setOpaque(true);
picture.setBackground(Color.white);
}
}
public static void main(String[] args) {
colorApp frame = new colorApp();
frame.setVisible(true);
}
}