我正在试图弄清楚如何在鼠标点击时重绘面板。我可以捕获鼠标点击就好了,但不能为我的生活得到组件绘制。这是为简单起见而设置的简化测试类。我的Test类出现了JComponent。
有什么想法吗?
这是我的主要内容:
public static void main(String[] args) {
JFrame frame = new JFrame("Point Capture Test");
frame.setContentPane(new Test().panelMain);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
这是我的Test构造函数:
public Test() {
mPanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JOptionPane.showMessageDialog(panelMain, e.getPoint());
JOptionPane.showMessageDialog(panelMain, "clicked "+ e.getSource() + " at " + e.getPoint());
//removed a bunch of stuff here that captures the clicked coordinates so I can use them to draw lines on the panel
repaint();
}
});
}
这是我的测试paintComponent方法:
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
if (this.mClicks > 2) { //draw polygon
Polygon polyTest = new Polygon();
for (Point point : this.mPntPoints){
polyTest.addPoint(point.x, point.y);
}
g2.setColor(Color.RED);
g2.fill(polyTest);
g2.draw(polyTest);
}
//just added this as a test and it doesn't draw either
g2.drawLine(10, 30, 20, 40);
}