我正在尝试编写一个程序,在屏幕上显示一堆线条,其坐标将从另一个程序确定。
为此,我正在尝试修改jasssuncao在这里的代码,以便我不必点击任何按钮就可以得到线条:如何在Java中绘制线条 以下是我现在拥有的:
然而,这样做并没有显示任何一行。为什么代码没有显示任何内容?谢谢!
为此,我正在尝试修改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);
}
}
}
然而,这样做并没有显示任何一行。为什么代码没有显示任何内容?谢谢!
EventQueue.invokeLater()
示例的链接。 - trashgod