我试图让一个盒子通过重新绘制来移动JFrame,但由于某种原因我无法弄清楚它不会起作用。我知道它可能是非常愚蠢的东西,但这里是我的课程:(也很抱歉格式化它在屁股上的痛苦...)它在frame.add(方形)线上给了我一个错误。
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 :(得分:0)
由于您的组件类是JFrame,因此无法将JFrame添加到JFrame。您可能希望将JPanel添加到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();
答案 1 :(得分:0)
最好覆盖JFrame中的“paint”方法。这样做要容易得多。
@override
public void paint(Graphics g){
super();
/*
put the code to draw your shape of shapes here
*/
}
只要您想更新JFrame,就可以调用JFrame的重绘方法。