在JFrame上绘制线条出现问题

4
我正在尝试编写一个程序,在屏幕上显示一堆线条,其坐标将从另一个程序确定。
为此,我正在尝试修改jasssuncao在这里的代码,以便我不必点击任何按钮就可以得到线条:如何在Java中绘制线条 以下是我现在拥有的:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class LineDrawing extends JComponent{

  private static class Line{
      final int x1; 
      final int y1;
      final int x2;
      final int y2;   
      final Color color;

      public Line(int x1, int y1, int x2, int y2, Color color) {
          this.x1 = x1;
          this.y1 = y1;
          this.x2 = x2;
          this.y2 = y2;
          this.color = color;
      }               
  }

  private final LinkedList<Line> lines = new LinkedList<Line>();

  public void addLine(int x1, int x2, int x3, int x4) {
      addLine(x1, x2, x3, x4, Color.black);
  }

  public void addLine(int x1, int x2, int x3, int x4, Color color) {
      lines.add(new Line(x1,x2,x3,x4, color));        
      repaint();
  }

  public void clearLines() {
      lines.clear();
      repaint();
  }

  @Override
  protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      for (Line line : lines) {
          g.setColor(line.color);
          g.drawLine(line.x1, line.y1, line.x2, line.y2);
      }
  }

  public static void main(String[] args) {
      JFrame testFrame = new JFrame();
      testFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      final LineDrawing comp = new LineDrawing();
      comp.setPreferredSize(new Dimension(1000, 400));
      testFrame.getContentPane().add(comp, BorderLayout.CENTER);
      comp.addLine(100, 100, 100, 100, new Color(24, 24, 24));
    testFrame.pack();
    testFrame.setVisible(true);
  }
  }
}

然而,这样做并没有显示任何一行。为什么代码没有显示任何内容?谢谢!
1个回答

6

感谢提供完整的示例,但是有几点需要说明:

  • Your line needs a non-zero size; note the coordinates required by drawLine():

    comp.addLine(10, 10, 100, 100, Color.blue);
    
  • Your JComponent may need to be opaque:

    comp.setOpaque(true);
    
  • Construct and manipulate Swing GUI objects only on the event dispatch thread, for example.

  • Don't use setPreferredSize() when you really mean to override getPreferredSize().

image


非常感谢您的帮助。我阅读了您关于事件分派线程的链接,如果我没有错的话,我只需要安排任务,对吗?如果是这样,为什么我的代码不在事件分派线程上运行?我很难理解如何在主线程中创建某些内容与在事件分派线程中构建它有何区别。 - Valerie Z
很高兴能帮忙;我已经添加了一个 EventQueue.invokeLater() 示例的链接。 - trashgod

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接