我正在开发一个可以绘制数学函数图形的swing应用程序。我正在使用getGraghics函数,但我不知道如何删除并重新绘制它们,因此我决定重写paintComponent()方法来实现我正在寻找的内容。添加到面板时,paintComponent()不起作用
我想要做的是在面板中绘制函数图用户点击按钮。但它似乎paintCompnent()不起作用。我完全按照任何现有的教程和堆栈溢出类似的问题,但他们都没有为我工作:(它只是没有意义:(
请帮助我坚持这个问题一整个晚上:(
以下是绘制功能图的代码,但由于它不工作,所以我只剩下绘图坐标系的部分进行测试,之后是如何创建实例并尝试将其添加到我的面板中的代码主类
class drawfunction extends JPanel{
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.drawLine(0, 200, 400, 200);
g.drawLine(200,0 , 200, 400);
}
}
然后在主类中的代码
JPanel panel = new JPanel();
panel.setBounds(14, 104, 400, 400);
contentPane.add(panel);
panel.setBackground(Color.white);
JButton btnNewButton = new JButton("View the graph");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//a= Integer.parseInt(cofficient_a.getText());
//b= Integer.parseInt(cofficient_b.getText());
//c= Integer.parseInt(cofficient_c.getText());
//d= Integer.parseInt(cofficient_d.getText());
//e= Integer.parseInt(cofficient_e.getText());
drawfunction a=new drawfunction();
panel.add(a);
});
谁能告诉我,我应该做些什么来解决这个问题。谢谢 !!!!
好吧,两件事情,一个 - 面板的默认大小为'0x0'和两个 - Swing是懒惰的,你需要调用'revalidate'和'重绘'当你想更新UI – MadProgrammer
另外,类名应该以大写字母开头! – camickr
@MadProgrammer我刚刚尝试使用setPreferredSize()来设置面板的大小,我也尝试添加这两个函数。现在每次按下按钮时都会出现一个小空白方块。 –