美好的一天。
我开发的程序在用户点击按钮时必须显示少量形状。至少它没有显示出来。怎么了? 代码是:
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);
//...
}
}
答案 0 :(得分:1)
在可见GUI上添加/删除组件时,代码应为:
panel.add(...);
panel.revalidate();
panel.repaint();
每次点击按钮时添加新面板的设计都不是很好。
相反,您应该创建一个自定义绘画面板并覆盖paintComponent()方法。然后,当您单击按钮时,可以在自定义组件中调用方法来设置要绘制的形状。 paintComponent()方法应该是聪明的,以绘制形状。然后在面板上调用repaint()。
阅读Custom Painting上Swing教程中的部分,了解更多信息和工作示例。