paintComponent和mouseListener

时间:2016-04-24 13:54:00

标签: java paintcomponent mouselistener

我正在尝试用图片上的矩形标记一个三角形(我在图片上标出)。我已设法绘制三角形,但我不能用矩形标记它。 这是我到目前为止编写的代码:

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.*;

abstract class Places extends JComponent {

    private boolean marked;

    private String placeName;
    private PlacePosition position;
    private String placeColor;
    private String placeCategory;

    public Places(String name, String category, PlacePosition position) {

        setBounds(position.x, position.y, 20, 20);

        placeName = name;
        this.position = position;
        placeCategory = category;
        this.placeColor = placeColor;

        mouseListener mL = new mouseListener();
    }

    public Color rightColor() {
        Color c = Color.BLACK;
        switch (placeCategory) {
        case "None":
          c = Color.BLACK;
          break;
        case "Buss":
            c = Color.RED;
            break;
        case "Tunnelbana":
            c = Color.BLUE;
            break;
        case "Tåg":
            c = Color.GREEN;
            break;
        }
        return c;
    }


    public PlacePosition getPosition() {
        return position;
        }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        int[] polyX = { 0, 15, 30 };
        int[] polyY = { 0, 30, 0 };

        setBounds(position.x - 15, position.y - 30, 30, 30);
        setPreferredSize(new Dimension(50, 50));
        setMaximumSize(new Dimension(50, 50));
        setMinimumSize(new Dimension(50, 50));
        g.setColor(rightColor());
        g.fillPolygon(polyX, polyY, 3);

        if (marked) {
            g.drawRect(30, 30, 30, 30);
            g.setColor(Color.YELLOW);
        }

        repaint();
    }

    abstract void printText();

    class mouseListener extends MouseAdapter {
        public void mouseClicked(MouseEvent mE) {
            if (SwingUtilities.isLeftMouseButton(mE)) {
                if (!marked) {
                marked = true;
                } else {
                    marked = false;
                }
            }

            revalidate();
            repaint();
       }
    }
}

我的猜测是有一些东西不适用于mouseListener,但我很不确定。非常感谢帮助!

1 个答案:

答案 0 :(得分:0)

您永远不会将MouseListener添加到任何内容,因此您的MouseAdapter类将无效。要使任何侦听器工作,必须首先将侦听器添加到侦听组件。因此,弄清楚要添加监听器的内容,然后在该组件上调用addMouseListener(...)

侧面推荐:从不从paintComponent方法或任何其他绘画方法中调用repaint()