栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何用Java画线

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何用Java画线

绘制线条的摆动组件的一个非常简单的示例。它在内部保留一个列表,其中包含使用方法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);}}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/437530.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号