在JFrame上绘制麻烦线

时间:2016-08-31 02:14:06

标签: java swing jframe line

我试图编写一个在屏幕上显示一串行的程序,其坐标将由另一个程序确定。

这样做,我试图从这里修改jasssuncao的代码,这样我就不必点击任何按钮来获取行:How to draw lines in Java < / p>

以下是我现在所拥有的:

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 个答案:

答案 0 :(得分:6)

感谢一个完整的例子,但有一些事情值得一提:

  • 您的行需要非零大小;请注意this change所需的坐标:

    comp.addLine(10, 10, 100, 100, Color.blue);
    
  • 您的JComponent可能需要drawLine()

    comp.setOpaque(true);
    
  • opaque上为event dispatch thread构建和操作仅的Swing GUI对象

  • 如果您真的要覆盖example,请不要使用setPreferredSize()

getPreferredSize()