绘制线条的摆动组件的一个非常简单的示例。它在内部保留一个列表,其中包含使用方法addLine添加的行。每次添加新行时,都会调用重新绘制以告知图形子系统需要新绘制。
该类还包括一些用法示例。
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 LinesComponent 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();}@Overrideprotected 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 LinesComponent comp = new LinesComponent(); comp.setPreferredSize(new Dimension(320, 200)); testframe.getContentPane().add(comp, BorderLayout.CENTER); JPanel buttonsPanel = new JPanel(); JButton newlineButton = new JButton("New Line"); JButton clearButton = new JButton("Clear"); buttonsPanel.add(newlineButton); buttonsPanel.add(clearButton); testframe.getContentPane().add(buttonsPanel, BorderLayout.SOUTH); newlineButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int x1 = (int) (Math.random()*320); int x2 = (int) (Math.random()*320); int y1 = (int) (Math.random()*200); int y2 = (int) (Math.random()*200); Color randomColor = new Color((float)Math.random(), (float)Math.random(), (float)Math.random()); comp.addLine(x1, y1, x2, y2, randomColor); } }); clearButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { comp.clearLines(); } }); testframe.pack(); testframe.setVisible(true);}}


