【问题标题】:add 2 objects to JFrame on a specific location在特定位置向 JFrame 添加 2 个对象
【发布时间】:2012-10-04 11:29:16
【问题描述】:

这是我的课程,它创建了一个具有特定 x 和 y 坐标的圆形。同样,我有另一个相同的类,但 x 和 y 坐标位置不同。我为每个类创建 1 个对象,并希望将它们显示在 JFrame 上的特定位置。当我将第二个对象添加到 JFrmae 时,它​​会覆盖第一个对象。我尝试了不同的 JFrmae 布局,但没有奏效。

  class Ballbewegung2 extends JPanel implements Runnable {  
    int x_pos = 10; int y_pos = 100; int radius = 20; 
    public void init() { 
    setBackground (Color.blue); } 
    public void start () { 
    Thread th = new Thread (this); 
    th.start (); } 
    public void run () { 
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY); 
    while (true) { 
       x_pos ++; if(x_pos >= 400) x_pos = 10; 
       repaint();
       try { Thread.sleep (20); } 
       catch (InterruptedException ex) {}       thread.currentThread().setPriority(Thread.MAX_
PRIORITY); } } public void paint (Graphics g) { g.setColor (Color.red); g.fillOval (x_pos - radius, y_pos - radius, 2 * radius, 2 * radius); } }

【问题讨论】:

  • 所以你是从一个单独的线程重新绘制?这是其他圈子班的样子吗?我不得不说我有点困惑。
  • 另一个类是完全相同的,但y坐标的位置不同。即在其他类中,我只是改变了y_pos的值,其余的都是一样的。
  • "Swing 程序应该覆盖paintComponent(),而不是覆盖paint()。"—Painting in AWT and Swing: The Paint Methods

标签: java multithreading swing concurrency event-dispatch-thread


【解决方案1】:

如果您将 JFrame 的布局设为 null,您将能够显式控制您添加的任何组件的位置。还要确保您要添加到 JFrame 的内容窗格中。

【讨论】:

  • 这能解决你的问题吗?如果可以,请您选择这个作为答案。如果没有,请解释为什么它没有帮助。
  • 澄清 - 我怀疑面板实际上被覆盖了,只是布局将它们放在彼此之上。使布局为空,然后指定 x 和 y 应该可以正常工作。
猜你喜欢
  • 2012-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多