重绘Java - 我读过很多问题,但仍然没有用

时间:2014-05-23 18:47:18

标签: java swing repaint

就像在一个主题中一样,我已经为repaint()提供了大部分解决方案,但是对于我的代码,它们不起作用。我是个乞丐,请原谅我代码中的一团糟......

类View.java

public class View extends JFrame{
public void make(){
    setSize(640,480);
    setVisible(true);
    setTitle("Parking");
}

double x_ = MyFrame.x;
double y_ = MyFrame.y;
double odchylenie_ = MyFrame.odchylenie;
int szerokosc = 50;
int wysokosc = 30;

   public void paint(Graphics g){
       Rectangle2D rect = new Rectangle2D.Double(-szerokosc / 2., -wysokosc / 2.,                    szerokosc, wysokosc);
       AffineTransform transform = new AffineTransform();
       transform.translate(x_, y_);
       transform.rotate(Math.toRadians(odchylenie_));
       Shape rotatedRect = transform.createTransformedShape(rect);
       Graphics2D g2 = (Graphics2D)g;
       g2.draw(rotatedRect);
}

我想做的就是用x,y和odchylenie的新值重新绘制这个rotateRect(对不起波兰变量名称)。

我正在计算新的变量值并使用Jbutton重绘它。 这是我的MyFrame.class

public class MyFrame extends javax.swing.JFrame {

static double x,y,odchylenie,kat;

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        View v = new View();
        v.make();
        Fuzzy f = new Fuzzy();
        kat = f.wyjscie(x, odchylenie);
        jLabel5.setText("Kąt: " + Double.toString(kat));
        odchylenie = Fuzzy.wyliczOdchylenie(odchylenie,kat);
        jLabel8.setText("Nowe odchylenie: " + Double.toString(odchylenie));  
        x = Fuzzy.wyliczX(x, 10, kat,odchylenie);
        jLabel6.setText("Nowy x: " + Double.toString(x));
        y = Fuzzy.wyliczY(y,x, 10, kat,odchylenie);
        jLabel7.setText("Nowy y: " + Double.toString(y));
        v.repaint(); //Not works
   }

而不是重新绘制(),新窗口出现,旧窗口停留... 我试图在按钮功能体外声明View v,但它也没有用(没有什么是绘画)。

2 个答案:

答案 0 :(得分:2)

每当你覆盖其中一个paint()方法时,你需要调用super的方法:

public void paint(Graphics g) {
    super.paint(g);
    // your code goes here
}

此外,您应该使用paintComponent(),而不是paint()

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    // your code goes here
}

答案 1 :(得分:1)

不使用paint,而是使用paintComponent

public void paintComponent(Graphics g){
       super.paintComponent(g);
       Rectangle2D rect = new Rectangle2D.Double(-szerokosc / 2., -wysokosc / 2.,                    szerokosc, wysokosc);
       AffineTransform transform = new AffineTransform();
       transform.translate(x_, y_);
       transform.rotate(Math.toRadians(odchylenie_));
       Shape rotatedRect = transform.createTransformedShape(rect);
       Graphics2D g2 = (Graphics2D)g;
       g2.draw(rotatedRect);
}