1
在我的課中,我想添加到主要JPanel其他JPanel對象在子類中創建,並捕獲鼠標事件,知道obj如何生成它。 我嘗試通過創建一個子類DoSquare(JPanel擴展),添加監聽器,創建objs並繪製該子類的圖形,但是當我運行程序並單擊其中一個DoSquare obj創建時,e.getSource()總是返回SubObj對象代替點擊的元素。 我如何區分聽衆事件中選定的組件?來自子類的Java陷阱事件obj
這裏我的代碼:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SubObj extends JPanel {
Listener listener = new Listener();
DoSquare firstQ = new DoSquare(100, 50);
DoSquare secondQ = new DoSquare(200, 70);
public static void main(String[] args) {
JFrame panel = new JFrame();
SubObj content = new SubObj();
panel.setContentPane(content);
panel.setFocusable(true);
panel.setSize(400, 400);
panel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setVisible(true);
}
SubObj() {
addMouseListener(listener);
addFocusListener(listener);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
firstQ.draw(g, Color.BLACK);
secondQ.draw(g, Color.CYAN);
}
private class DoSquare extends JPanel {
private int coordX;
private int coordY;
Listener squareLis = new Listener();
DoSquare(int X, int Y) {
addMouseListener(squareLis);
addFocusListener(squareLis);
coordX = X;
coordY = Y;
}
void draw(Graphics g, Color c) { // Draw the square
g.setColor(c);
g.fillRect(coordX, coordY, 50, 50);
}
}
public class Listener implements MouseListener, FocusListener {
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
System.out.println(e.getSource());
}
public void mouseReleased(MouseEvent e) {}
public void focusGained(FocusEvent e) {}
public void focusLost(FocusEvent e) {}
}
}
在此先感謝
AM
嗨,謝謝你的回覆,我儘量改變聽衆的建議,但結果不會改變。 – AleMal
@almal它的工作原理,嘗試我更新的代碼。 –
太棒了,它的工作!再次感謝 – AleMal