嘿,大家我正在嘗試創建一個有點動態的程序,您可以在其中添加圖形或圖像到JPanel中,然後在添加圖形後選擇並移動它們。問題是,當我點擊特定的JComponent時沒有任何反應。事實上,單擊我創建的用於測試項目的任何組件都會爲所有JComponents返回false。但是,如果我點擊左上角的JComponent邊界內的所有JComponents,就會返回true,即單擊(0,0,50,68)範圍內的區域。使用鼠標點擊JComponent時出現問題
這個想法是,如果我點擊其中一個JComponents,它會設置該特定的JComponent是可移動的,但我無法超越實際選擇特定JComponent的部分。
這裏是我建重現問題的一個基本SSCE:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class SSCE1 extends JPanel {
private ArrayList<Shape> shapeList = new ArrayList<Shape>();
SSCE1() {
setLayout(null);
/* Debug Stuff */
System.out.println("Debug:");
/* Add The First Shape To The List */
shapeList.add(0, new Shape(100, 100));
add(shapeList.get(0));
shapeList.add(1, new Shape(610, 0));
add(shapeList.get(1));
shapeList.add(2, new Shape(500, 900));
add(shapeList.get(2));
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
for (Shape shape : shapeList) {
if (shape.contains(e.getPoint())) {
System.out.println("Hello");
} else {
System.out.println("Goodbye");
}
}
}
});
}
}
class Shape extends JComponent {
int xLocation, yLocation, xBounds1, yBounds1;
Shape(int xLocation, int yLocation) {
this.xLocation = xLocation;
this.yLocation = yLocation;
this.xBounds1 = 50;
this.yBounds1 = 68;
setBounds(xLocation, yLocation, xBounds1, yBounds1);
setLocation(xLocation, yLocation);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.blue);
g.fillRect(0, 0, 100, 100);
}
}
class Run {
public static void main(String[] args) {
JFrame main = new JFrame();
SSCE1 p1 = new SSCE1();
main.setSize(new Dimension(1000, 1000));
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setLocation(new Point(0, 0));
main.setVisible(true);
main.add(p1);
}
}
什麼形狀,最近怎麼定義之前將鼠標指向
Shape
的背景下翻譯? – MadProgrammer對不起,你的意思是? – Sam
什麼是「形狀」? – MadProgrammer