如何使用一个方法从一个已经存在的Cotainer中放入JLabel?

How to use a method from an already to Cotainer put JLabel?

我必须对 Shikaku-Game 进行编程,我没有遇到无法使用 [=21= 的 mouseReleased-Method 中的 ViewIcon-Class 中的 setLine-Methods 之一的问题] 我的鼠标适配器。 您知道如何使用其中一种方法吗?

谢谢和干杯, 我

Class MouseMain 和 Class MyMouseAdapter:

class MouseMain extends JFrame{

Container cont;

public MouseMain () {
    super("Test");
    cont = getContentPane();
    p1 = new defaultPaterns(2);
    p1.setLayout(new GridLayout(2, 2, 1, 1));
    for (int i = 0; i < gameSize; i++) {
        for (int j = 0; j < gameSize; j++) {
            JLabel label = new JLabel(new ViewIcon());
            label.setName (j + ";" + i);
            label.addMouseListener(new MyMouseAdapter());
            p1.add(label);
            myLabels[j][i] = label;
        }
    }
    cont.add(p1, BorderLayout.CENTER );

    JPanel p2 = new JPanel();
    cont.add(p2, BorderLayout.SOUTH);
    setVisible(true);
}

public class MyMouseAdapter extends MouseAdapter {

    public void mouseEntered(MouseEvent e) {
        lastEntered = e.getComponent();
    }

    public void mousePressed(MouseEvent e) {
        mousePressed = e.getComponent();
        coordPressed = new Coordinate(mousePressed.getName());
        System.out.println("mousePressed " + mousePressed.getName());
    }

    public void mouseReleased(MouseEvent e) {
        mouseReleased = lastEntered;
        coordReleased = new Coordinate(mouseReleased.getName());
        System.out.println("mouseReleased " + mouseReleased.getName());
        if (mouseReleased.getName().equals("0;0")) {
            mouseReleased.setForeground(Color.RED);
            mouseReleased.repaint();
        }
    }
}

Class 视图图标:

class ViewIcon extends JLabel implements Icon {

    Graphics2D g2;
    int width;
    int height;

public void paintIcon(Component c, Graphics g, int x, int y) {

    g2 = (Graphics2D) g;
    width = c.getWidth();
    height = c.getHeight();
    g2.setColor(Color.LIGHT_GRAY);
    g2.fillRect(0, 0, width, height);
}

public void setLeftLine() {

    g2.setStroke (new BasicStroke (10));
    g2.setColor(Color.RED);
    g2.drawLine(0, 0, 0, height);
}

}
class ViewIcon extends JLabel implements Icon {

不要扩展 JLabel。您所有的代码都在实现 Icon 接口。

I can not use one of the setLine-Methods from the ViewIcon-Class

自定义绘画只能在 paintIcon(...) 方法中完成。你不应该直接调用绘画方法。

如果你想改变你画的外观,那么你需要设置图标的属性。例如,要绘制重命名的顶行并将 setTopLine(...) 方法更改为如下所示:

public void setTopLinePainted(boolean topLinePainted)
{
    this.topLinePainted = topLinePainted;
} 

然后在 paintIcon(...) 方法中你有这样的代码:

g2.fillRect(0, 0, width, height);

if (topLinePainted)
{
    g2.setStroke (new BasicStroke (10));
    g2.setColor(Color.RED);
    g2.drawLine(0, 0, width, 0);
}

然后在您的 mouseReleased(...) 代码中执行如下操作:

JLabel label = (JLabel)lastEntered;
ViewIcon icon = (ViewIcon)label.getIcon();
icon.setTopLinePainted( true );
label.repaint();