JList

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class test1 extends JFrame
{
 final JTextField tf;
 final JList jl;
 final JPanel p1;
 public test1()
 {
  tf=new JTextField(20);
  tf.setEditable(false);  //设置JTextField为不可编辑
  Color[] colors={Color.BLACK,Color.BLUE,Color.RED,Color.MAGENTA,Color.green}; //初始化黑色,蓝色,红色,粉红色,绿色
  jl=new JList(colors);   //把刚刚初始化的五种颜色放到JList中
  jl.setCellRenderer(new test2());
  p1=new JPanel();
  p1.setPreferredSize(new Dimension(20,20));
 
  this.getContentPane().add(tf,"North");
  this.getContentPane().add(jl,"Center");
  this.getContentPane().add(p1,"South");
 
  this.setSize(300,200);
  this.setLocation(200,200);
  this.setTitle("JList test example");    //设置标题为 JList test example
  this.setVisible(true);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   //设置JFrame关闭事件
  jl.addListSelectionListener(new ListSelectionListener()
  {
   public void valueChanged(ListSelectionEvent e)
   {
    Color c=(Color)jl.getSelectedValue();
    tf.setText("您选择的是 R="+c.getRed()+",G="+c.getGreen()+",B="+c.getBlue());
    p1.setBackground(c);
   
   }
  });
 }
 public static void main(String args[])
 {
  new test1();
 }
}
class test2 extends JLabel implements ListCellRenderer
{
 /**
  * Method getListCellRendererComponent
  *
  *
  * @param list
  * @param value
  * @param index
  * @param isSelected
  * @param cellHasFocus
  *
  * @return
  *
  */
 public Component getListCellRendererComponent(JList list, Object value,
     int index, boolean isSelected, boolean cellHasFocus) {
  // TODO: Add your code here
  if(isSelected||cellHasFocus)
  {
   this.setBorder(new MatteBorder(2,10,2,10,list.getSelectionBackground()));
  }
  else
  {
   this.setBorder(new MatteBorder(2,10,2,10,list.getBackground()));
  }
  Color c=(Color)value;
  this.setForeground(c);
  this.setText(c.toString());
  return this;
 }
 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值