Map存储颜色

来源:互联网 发布:linux判断数值大于0 编辑:程序博客网 时间:2024/06/05 02:23

利用Map存储颜色与串的对应关系,编写一个窗体应用,在窗体中安排若干获取颜色的按钮,按钮名称与Map中颜色串名称一致,点击按钮,则窗体的背景色设为指定的颜色。    Map<String,Color>中含红色、绿色、蓝色、黄色、白色、橙色等。

import java.util.*;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class mapTest {
public static void main(String[] args) {


// TODO Auto-generated method stub

Map〈String,Color> map = new HashMap〈String, Color>();
map.put("black", Color.BLACK);
map.put("red", Color.RED);
map.put("green", Color.GREEN);
map.put("yellow", Color.YELLOW);
map.put("white", Color.WHITE);
map.put("gray", Color.GRAY);

JPanel jp =new JPanel();
JButton jt = new JButton();

jt.setText("颜色1");
jt.setBackground(map.get("black"));
jp.add(jt);
jt.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
jp.setBackground(map.get("black"));

}
});
JButton jt2 = new JButton();
jt2.setText("颜色2");
jt2.setBackground(map.get("red"));
jp.add(jt2);
jt2.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
jp.setBackground(map.get("red"));

}
});
JButton jt3 = new JButton();
jt3.setText("颜色3");
jt3.setBackground(map.get("green"));
jp.add(jt3);
jt3.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
jp.setBackground(map.get("green"));

}
});
JButton jt4 = new JButton();
jt4.setText("颜色4");
jt4.setBackground(map.get("yellow"));
jp.add(jt4);
jt4.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
jp.setBackground(map.get("yellow"));

}
});

JFrame frame = new JFrame("Panel!");
frame.getContentPane().add(jp);
frame.pack();
frame.setVisible(true);

}


}
0 0
原创粉丝点击