2012-03-13 70 views
1

我想通过重新绘制一个框移动到一个JFrame,但由于某种原因,我不知道它不会工作。我知道它可能是一些非常愚蠢的东西,但是这里是我的类:(也抱歉格式化了它在屁股上的痛苦......)它给了我一个关于frame.add(方形)行的错误。奇怪的JFrame问题

import javax.swing.JFrame; 
import javax.swing.WindowConstants; 

public class Runner extends JFrame{ 

final static int FRAME_WIDTH = 1000; 
final static int FRAME_HEIGHT = 600; 
final static int BOX_WIDTH = 50; 
final static int BOX_HEIGHT = 50; 

public static void main (String[] args){ 

    JFrame frame = new JFrame(); 
    frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); 
    frame.setTitle("Animation"); 
    frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); 
    frame.setVisible(true); 

    Component square = new Component(); 
    Dimensions.setBoxDimensions(BOX_WIDTH, BOX_HEIGHT); 

    frame.add(square); 
    frame.setVisible(true); 

    for (int i = 0; i < 100; i++){ 
     Dimensions.setPosition(i,i); 
     square.repaint(); 
     frame.setVisible(true); 
    } 
} 
} 



import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import javax.swing.JFrame; 

public class Component extends JFrame{ 

public void paintComponent (Graphics g){ 
    Graphics2D g2 = (Graphics2D) g; 
    g2.fillRect(Dimensions.xPos, Dimensions.yPos, Dimensions.boxWidth,   Dimensions.boxHeight); 
} 
} 





public class Dimensions { 

public static int boxHeight = 50; 
public static int boxWidth = 50; 
public static int xPos = 0; 
public static int yPos = 0; 

public static void setBoxDimensions(int width, int height){ 
    boxHeight = height; 
    boxWidth = width; 
} 
public static void setPosition(int x, int y){ 
    xPos = x; 
    yPos = y; 
} 
} 

回答

0

由于您的组件类是JFrame,因此无法将JFrame添加到JFrame中。您可能需要将Janel添加到JFrame,然后在JPanel上绘制。

或者您可能打算扩展java.awt.Component?

import javax.swing.JPanel; 
public class MyComponent extends JPanel{ 

    public void paintComponent (Graphics g){ 
      Graphics2D g2 = (Graphics2D) g; 
      g2.fillRect(Dimensions.xPos, Dimensions.yPos, Dimensions.boxWidth,       Dimensions.boxHeight); 
    } 
    } 

而当你想要一个组件,你可以这样做:

JPanel square = new MyComponent(); 
+0

so JPanel panel = new JPanel(); 然后panel.add(square); ?? – Evan 2012-03-13 02:31:49

+0

我添加了一些示例来帮助。 – 2012-03-13 02:35:54

+0

命名您自己的类Component可能会导致一些问题,因为存在java.awt.Component,即使可以完成。所以我为了方便将它重命名为MyComponent。 – 2012-03-13 02:36:57

0

这是更好地覆盖在你的JFrame的“漆”的方法。这很容易做到。

@override 
public void paint(Graphics g){ 
    super(); 
    /* 
     put the code to draw your shape of shapes here 
    */ 
} 

只要你想更新你的JFrame,你可以调用你的JFrame的repaint方法。