简体   繁体   English

带Swing的Java线程

[英]Java threads with Swing

I would like to illustrate a project about railroads. 我想举例说明一个有关铁路的项目。

I decided to use Swing. 我决定使用Swing。 I have a background map in a JPanel and I draw little circles that moves on the railroads. 我在JPanel中有一个背景图,并且画了在铁路上移动的小圆圈。 It works perfectly if I have only one train, but I would like to add more trains. 如果我只有一列火车,它可以很好地工作,但是我想增加更多火车。

Here is what I started to do (and works) : 这是我开始做(和工作)的:

public static void main(String[] args) {

  // JFrame and background panel construction
  JFrame frame = new JFrame();
  JLayeredPane lpane = new JLayeredPane();
  ImagePanel panelBg = new ImagePanel(new ImageIcon("map.jpg").getImage());;

  frame.setPreferredSize(new Dimension(1791, 695));
  frame.setLayout(new BorderLayout());
  frame.add(lpane,BorderLayout.CENTER);
  lpane.setBounds(0,0,panelBg.getImg().getWidth(null),panelBg.getImg().getHeight(null));

  panelBg.setBounds(0,0,panelBg.getImg().getWidth(null),panelBg.getImg().getHeight(null));
  panelBg.setOpaque(true);

  lpane.add(panelBg, new Integer(0), 0);

  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.pack();
  frame.setVisible(true);
  go(lpane,panelBg);  
  }

private static void go(JLayeredPane pan,ImagePanel panBg) {

  Parcours panelP = new Parcours();
  panelP.setBounds(0,0,panBg.getImg().getWidth(null),panBg.getImg().getHeight(null));
  panelP.setOpaque(false);
  pan.add(panelP, new Integer(1), 0);

  for(int i=0; i<panelP.getTable().size(); i++){
    panelP.setPosX(panelP.getTable().get(i).getX()-6);
    panelP.setPosY(panelP.getTable().get(i).getY()-6);
    panelP.repaint();
    try{
      Thread.sleep(100);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

"go" reads an ArrayList containing coordinates where my circle should go. “ go”读取一个ArrayList,其中包含我的圆应该去的坐标。

I really don't know how to create several trains. 我真的不知道如何制造多列火车。 Should I create several JPanels or only one with all my circles ? 我应该创建几个JPanels还是与我所有的圈子一起创建一个?

If I remember well, I should use Threads but I tried to implement them and I can't start. 如果我没记错的话,我应该使用线程,但是我尝试实现它们,但无法启动。

Thank you for your help 谢谢您的帮助

You could use a central data object that stores the trains.In every cycle the trains get drawn inside swing. 您可以使用存储火车的中央数据对象。在每个周期中,火车都会在秋千内绘制。 On the other side the trains get updated from your threads. 另一方面,火车会根据您的线程进行更新。

Another approach contains train objects that get drawn and run a thread inside them to update them self. 另一种方法包含绘制训练对象并在其中运行线程以自我更新。

Thank you Robin (see comments of my first post), Swing Timers seem to be the best solution so far. 谢谢Robin(请参阅我的第一篇文章的评论),Swing Timers似乎是迄今为止最好的解决方案。 I removed my awful Thread.sleep and set timers instead, it works, thanks again. 我删除了可怕的Thread.sleep并设置了计时器,它可以正常工作,再次感谢。

Thank you Templar too 也谢谢你圣殿骑士

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM