我正在尝试解决Java教科书中的问题。用户要求两个矩形在单个帧中以相反方向移动的问题请求。到目前为止,我附上了我的代码。但是,当我运行代码时,框架不显示任何内容,甚至不显示静止的矩形。此外,我没有收到任何有助于深入了解手头问题的错误。谢谢!
import java.awt.Graphics;
import javax.swing.JComponent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.JPanel;
public class RectangleComponent extends JComponent
{
private static final int RECTANGLE_WIDTH = 20;
private static final int RECTANGLE_HEIGHT = 30;
private int xLeft;
private int yTop;
public RectangleComponent(int x, int y)
{
xLeft = x;
yTop = y;
}
public void paintComponent(Graphics g)
{
g.fillRect(xLeft, yTop, RECTANGLE_WIDTH, RECTANGLE_HEIGHT);
}
/**
* Moves the rectangle by a given amount
* @return dx the amount to move in the x-direction
* @return dy the amount to move in the y-direction
*/
public void moveRectangleBy(int dx, int dy)
{
xLeft = xLeft + dx;
yTop = yTop + dy;
repaint();
}
}
public class RectangleFrame extends JFrame
{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 400;
private RectangleComponent rec1;
private RectangleComponent rec2;
class TimerListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
rec1.moveRectangleBy(1, 1);
rec2.moveRectangleBy(-1, -1);
}
}
public RectangleFrame()
{
createPanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
ActionListener listener = new TimerListener();
final int DELAY = 100; //Milliseconds between timer ticks
Timer t = new Timer (DELAY, listener);
t.start();
}
public void createPanel()
{
JPanel panel = new JPanel();
rec1 = new RectangleComponent(0,0);
rec2 = new RectangleComponent(280,470);
panel.add(rec1);
panel.add(rec2);
add(panel);
}
}
public class RectangleFrameViewer
{
public static void main (String[] args)
{
JFrame rectangleFrame = new RectangleFrame();
rectangleFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rectangleFrame.setVisible(true);
}
}
在回顾了MadProgrammer的建议后,我将RectangleComponent类更改为以下内容:
public class RectangleComponent extends JComponent
{
private static final int RECTANGLE_WIDTH = 20;
private static final int RECTANGLE_HEIGHT = 30;
private int xLeft1;
private int yTop1;
private int xLeft2;
private int yTop2;
public RectangleComponent()
{
xLeft1 = 0;
yTop1 = 0;
xLeft2 = 250;
yTop2 = 350;
}
public void paintComponent(Graphics g)
{
g.fillRect(xLeft1, yTop1, RECTANGLE_WIDTH, RECTANGLE_HEIGHT);
g.fillRect(xLeft2, yTop2, RECTANGLE_WIDTH, RECTANGLE_HEIGHT);
}
/**
* Moves the rectangle by a given amount
* @return dx the amount to move in the x-direction
* @return dy the amount to move in the y-direction
*/
public void moveRectangleBy(int dx, int dy)
{
xLeft1 = xLeft1 + dx;
yTop1 = yTop1 + dy;
xLeft2 = xLeft2 - dx;
yTop2 = yTop2 - dy;
repaint();
}
}