gpt4 book ai didi

java - 如何使用已从 Cotainer 放置 JLabel 的方法?

转载 作者:行者123 更新时间:2023-12-01 11:41:41 25 4
gpt4 key购买 nike

我必须编写 Shikaku-Game 程序,但我没有遇到无法使用 MyMouseAdapter 类的 mouseReleased-Method 中 ViewIcon-Class 中的 setLine-Methods 之一的问题。您知道如何使用其中一种方法吗?

谢谢和干杯,我

MouseMain 类和 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();
}
}
}

类ViewIcon:

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 接口(interface)。

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();

关于java - 如何使用已从 Cotainer 放置 JLabel 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29473595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com