Valerie Z Valerie Z - 3 months ago 7
Java Question

Trouble Drawing Line on JFrame

I'm trying to write a program that displays a bunch of lines on a screen, the coordinates of which will be determined from another program.

In doing so, I'm trying to modify jasssuncao's code from here, so that I don't have to click on any buttons in order to get lines: How to draw lines in Java

Here is what I have now:

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);
}
}
}


However, doing so does not display any a line. Why isn't the code displaying anything? Thanks!

Answer

Kudos for a complete example, but a few things bear mentioning:

  • Your JComponent needs to be opaque:

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

    comp.addLine(10, 10, 100, 100, Color.blue);
    
  • Construct and manipulate Swing GUI objects only on the event dispatch thread.

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

image