Java Swing库-我无法绘制组件,有什么想法吗?
我想知道如何用鼠标点击重新绘制面板。我可以很好地捕捉鼠标点击,但我一生都无法绘制组件。为了简单起见,这是一个简化的测试类I设置。我的测试类扩展了JComponent 有什么想法吗 以下是我的主要观点:Java Swing库-我无法绘制组件,有什么想法吗?,java,swing,paintcomponent,mouselistener,Java,Swing,Paintcomponent,Mouselistener,我想知道如何用鼠标点击重新绘制面板。我可以很好地捕捉鼠标点击,但我一生都无法绘制组件。为了简单起见,这是一个简化的测试类I设置。我的测试类扩展了JComponent 有什么想法吗 以下是我的主要观点: public static void main(String[] args) { JFrame frame = new JFrame("Point Capture Test"); frame.setContentPane(new Test().panelMain);
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);
}
下面是我的测试构造函数:
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();
}
});
}
以下是我的测试组件方法:
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);
}
为了获得更好的帮助,请尽快发布一个简短、可运行、可编译的文件,您错过了super.paintComponent(g)代码>@Eng.Fouad你说得对-就是这样!