我正在上一门教Java的课程,我们遇到了一个无法解决的问题.我们需要在相反的方向上移动两个矩形.我有完成的代码将执行此操作,但问题是我只能得到一个或没有矩形出现.我尝试过不同的解决方案,例如将矩形添加到JPanel,以及不同的布局但没有成功.
public class RectTimer {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.setTitle("An animated rectangle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final RectangleComponent component = new RectangleComponent();
final RectangleComponent component2 = new RectangleComponent(290,290);
JPanel container = new JPanel();
container.add(component);
container.add(component2);
frame.add(container);
frame.setVisible(true);
class TimerListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent arg0) {
component.moveBy(5, 5);
}
}
class TimerListener2 implements ActionListener{
@Override
public void actionPerformed(ActionEvent arg0) {
component2.moveBy(-5, -5);
}
}
ActionListener l = new TimerListener();
Timer t = new Timer(100, l);
t.start();
ActionListener l2 = new TimerListener2();
Timer t2 = new Timer(100, l2);
t2.start();}
public class RectangleComponent extends JComponent{
private Rectangle box;
public RectangleComponent(){
box = new Rectangle(10,10,20,30);
}
public RectangleComponent(int x, int y){
box = new Rectangle(x,y,20,30);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.draw(box);
g2.dispose();
}
public void moveBy(int dx, int dy){
box.translate(dx, dy);
if(box.getX() > 300 && box.getY() > 300){
box.setLocation(10, 10);
}
if(box.getX() < 0 && box.getY() < 0){
box.setLocation(290, 290);
}
repaint();
}
public void moveTo(int x, int y){
box.setLocation(x, y);
repaint();
}}
Run Code Online (Sandbox Code Playgroud)
但问题是我只能得到一个或没有一个矩形出现.
这可能是因为您仍在使用框架的默认BorderLayout并将组件添加到CENTER.仅显示添加的最后一个组件.
我刚刚使用了OverlayLayout
我建议你这样做,你不想使用OverlayLayout.
因为您使用的是随机运动,所以您只想将组件添加到同一个面板中.然后,您将使用空布局,以便您可以手动控制每个组件的位置.您还将负责设置组件的大小,这是其首选大小.
此外,您需要覆盖getPreferredSize()组件的大小以返回组件所需的大小.首选尺寸将基于您的自定义绘画.因此,在您的情况下,首选大小将是(20,30);. 该框始终绘制在(0,0)处.要移动框,您可以设置框的位置.