突出显示JList

时间:2018-04-18 15:38:48

标签: java swing

我编写了一个java程序来绘制一个矩形,并用java列表中颜色的选定颜色填充它,并且它的工作非常好,只是当我点击它时所选的值不会突出显示。

但是,我可以使用箭头键上下移动,但我不知道我在哪里。

我的Java代码:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Rectangle2D;
import java.util.HashMap;
import javax.swing.*;

import javax.swing.event.ListSelectionListener;

public class Test extends JApplet {

    private JList list;
    private String[] colors = {"pink","lightGreen","orange","lightRed"}
    private HashMap<String, Color> colorsMap= new HashMap<>();

    public Test(){

     setLayout(new FlowLayout());

     colorsMap.put("pink",Color.PINK);
     colorsMap.put("lightGreen",new Color(202,230,147));
     colorsMap.put("orange",Color.ORANGE);
     colorsMap.put("lightRed",new Color(255,144,133));

    list = new JList(colors);
    list.setVisibleRowCount(2);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    add(new JScrollPane(list));

    list.addListSelectionListener(
        new ListSelectionListener(){
         public void valueChanged(ListSelectionEvent event){
             getContentPane().setFocusable(true);
             repaint();
         }  
        }
        );

    }

    public void paint(Graphics g) {

      Graphics2D g2 = (Graphics2D) g;

      int x = 5;
      int y = 110;

      g2.setPaint(colorsMap.get(list.getSelectedValue()));
      g2.fill(new Rectangle2D.Double(x, y, 490, 360));

  }

  public static void main(String s[]) {
    JFrame f = new JFrame("Colors");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JApplet applet = new Test();
    f.add(applet);
    f.pack();
    f.setSize(new Dimension(500, 500));
    f.setVisible(true);

  }
}

1 个答案:

答案 0 :(得分:1)

public void paint(Graphics g) {
    // ..

应该是:

public void paint(Graphics g) {
    super.paint(g);
    // ..

调用super方法是在自定义绘制组件中实现绘制链的正确方法。