JAVA单击按钮绘制形状时出现问题
你好
我开发的程序必须显示一些形状,当用户点击按钮。至少它没有表现出来。怎么了? 代码是:
public class ShowFrame extends JFrame
{
public ShowFrame()
{
this.setTitle("Show data"); //Title
this.setSize( DEF_WIDTH, DEF_HEIGHT ); //Size of frame
this.setResizable(false);
//...
JButton testButton = new JButton("Test");
buttonPanel.add(testButton);
this.add(buttonPanel, BorderLayout.SOUTH);
testButton.addActionListener( new ActionListener() { //Add listener
public void actionPerformed(ActionEvent e) {
DrawStuff stuff = new DrawStuff(); //Create class which draws shapes
add(stuff, BorderLayout.CENTER);
System.out.println("Test Button");
}
} );
}
public static final int DEF_WIDTH = 600;
public static final int DEF_HEIGHT = 400;
private JPanel buttonPanel = new JPanel();
}
绘制形状的类:
public class DrawStuff extends JComponent
{
public void paintComponent( Graphics g )
{
Graphics2D g2 = (Graphics2D) g;
//...
Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
Line2D line = new Line2D.Double(leftX, topY, 0, 0);
//...
g2.draw(rect);
g2.draw(line);
//...
}
}
# 1 楼答案
在可见GUI上添加/删除组件时,代码应为:
每次单击按钮时添加新面板的设计不是很好
相反,您应该创建一个自定义绘制面板并重写paintComponent()方法。然后,单击按钮时,可以调用自定义组件中的方法来设置要绘制的形状。paintComponent()方法应该足够智能,可以绘制形状。然后在面板上调用repaint()
阅读Swing教程中关于Custom Painting的部分,了解更多信息和工作示例