gpt4 book ai didi

java - JComponent 未注册

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

所以我有以下类(class)。我过度简化了代码,因为放置 500 多行代码不是一个选项。它基本上是一个非常奇特的正方形:

public class ModuleGui extends JComponent implements ElementInterface {

private String name;

private Rectangle2D s = new Rectangle2D.Double();
private Rectangle2D[] points;
private int resizeSize = 10;

private final ShapeResizeHandler shapeResizeHandler = new ShapeResizeHandler();

public ModuleGui(int x, int y){

this.addMouseListener(shapeResizeHandler);
this.addMouseMotionListener(shapeResizeHandler);

this.x = x;
this.x = y;

points = new Rectangle2D[2];
points[0] = new Rectangle2D.Double(x,y,1,1);
points[1] = new Rectangle2D.Double(x + width, y + height, resizeSize, resizeSize);

this.name = new String("Gate" + Integer.toString(namingCounter++));
}

public void paintComponent(Graphics g){
super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

g2d.fill(points[1]);

//Set the main rectangle, fill it and draw it
s.setRect(points[0].getX(), points[0].getY(),
Math.abs(points[1].getCenterX() - points[0].getCenterX()),
Math.abs(points[1].getCenterY() - points[0].getCenterY()));
g2d.setColor(Color.WHITE);
g2d.fill(s);
g2d.setColor(Color.BLACK);
g2d.draw(s);
//Main rectangle draw end

//Add the name and the & symbol
g2d.drawString(this.name, (int) (s.getCenterX()), (int) (s.getY() + this.height/10));
}


private class ShapeResizeHandler extends MouseAdapter{
public void mousePressed(MouseEvent e){
System.out.println("Funny");
}

public void mouseReleased(){
//Do more stuff
}

public void mouseDragged(MouseEvent e){
//Do Stuff
repaint();
}
}
}

现在我在 JPanel 中有这个 JComponent..但我似乎没有捕获任何鼠标事件。鼠标事件显示在 JPanel 中,但不显示在 JComponent 中。我试图制作一个简单的鼠标监听器来打印一些东西,但同样的情况发生了。

最佳答案

确保您的组件可见并且具有非零尺寸。这是适合我的代码:

public class MouseTest extends JComponent {
public MouseTest () {
addMouseListener (new MouseAdapter () {
@Override
public void mousePressed (MouseEvent e) {
System.out.println ("Mouse pressed");
e.consume();
}
});
}

@Override
public Dimension getPreferredSize() {
return new Dimension (320, 240);
}

@Override
public void paint(Graphics g) {
g.setColor (Color.cyan);
g.fillRect (getX (), getY (), getWidth (), getHeight ());
}

public static void main(String[] args) {
JFrame frame = new JFrame ("Mouse Test");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane ().setLayout (new BorderLayout ());
frame.getContentPane ().add (new MouseTest (), BorderLayout.CENTER);
frame.pack ();
frame.setVisible (true);
}
}

关于java - JComponent 未注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14979722/

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