请给出一个画图程序,要求如下:java 语言,建立窗体JFrame,里面添加面板JPanel,在面板上绘制一个矩形 。import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test
{
public static void main(String[] args) throws Exception
{
JFrame frame = new JFrame();
final RectanglePanel panel = new RectanglePanel();
frame.add(panel, BorderLayout.CENTER);
JPanel paramPanel = new JPanel();
paramPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
final JTextField widthField = new JTextField(5);
final JTextField heightField = new JTextField(5);
paramPanel.add(widthField);
paramPanel.add(heightField);
JButton button = new JButton("Draw");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int width = Integer.parseInt(widthField.getText());
int height = Integer.parseInt(heightField.getText());
panel.setRectangleSize(width, height);
panel.repaint();
} catch (Exception ex) {}
}
});
paramPanel.add(button);
frame.add(paramPanel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
}
class RectanglePanel extends JPanel {
int width = 0, height = 0;
void setRectangleSize(int width, int height) {
this.width = width;
this.height = height;
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLACK);
g.drawRect(1, 1, width, height);
}
}
GUI画图板(绘图板)设计,用Java编写程序代码?。⌒恍唬 。?/h2>只有矩形有圆形能移动,其它实现起来麻烦点,办法有的只是代码太多 。
画圆弧改成了画曲线,圆弧稍麻烦,当然方法是很简单的,你可以自己思考一下 。
双击13个颜色中的任意一个都会弹出颜色选择器 。
有保存与打开功能 。扩展名请用 .jdr
基本满足条件,细节可能不是很好,另,代码比较乱,怕不好看懂咯,呼呼 。
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
public class JDraw {
public static void main(String[] args) {
JFrame f=new JFrame();
f.setDefaultCloseOperation(3);
f.setSize(880,600);
f.setLocationRelativeTo(null);
f.getContentPane().add(M.c);
f.getContentPane().add(M.m,"South");
f.setVisible(true);
}
}
class CVS extends Component implements ComponentListener,MouseListener,MouseMotionListener{
public void componentHidden(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {}
public void componentResized(ComponentEvent e) {resized();}
public void componentShown(ComponentEvent e) {}
private void resized() {
int w=this.getWidth();
int h=this.getHeight();
tbuff=new BufferedImage(w,h,3);
makeBuff(w,h);
}
private void makeBuff(int w,int h) {
Graphics g = tbuff.getGraphics();
g.drawImage(buff,0,0,null);
g.dispose();
buff=new BufferedImage(w,h,3);
g=buff.getGraphics();
g.drawImage(tbuff,0,0,null);
g.dispose();
}
BufferedImage buff,tbuff;
CVS(){
this.addComponentListener(this);
this.addMouseListener(this);
this.addMouseMotionListener(this);
buff=new BufferedImage(1,1,3);
}
public void paint(Graphics gr){
Graphics2D g = buff.createGraphics();
g.setBackground(new Color(0xff000000,true));
g.clearRect(0,0,getWidth(),getHeight());
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
M.sa.drawAll(g);
if(M.ts!=null)
M.ts.draw(g);
g.dispose();
gr.drawImage(buff,0,0,this);
gr.dispose();
}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
M.mp(e.getPoint());
}
public void mouseReleased(MouseEvent e) {
M.mr(e.getPoint());
}
public void mouseDragged(MouseEvent e) {
M.md(e.getPoint());
}
public void mouseMoved(MouseEvent e) {}
}
class Menu extends JComponent implements MouseListener,ActionListener{
JComboBox sbox,method;
CLabel[] cl;
JCheckBox fillC,drawB;
JRadioButton fc,bc;
ButtonGroup bg;
JButton clear,up,down,save,load;
Menu(){
this.setLayout(new FlowLayout());
method=new JComboBox(new Object[]{"draw","move","erase",});
add(method);
sbox=new JComboBox(new Object[]{"Pt","Ln","Rect","Cir","Arc",});
add(sbox);
cl=new CLabel[13];
for(int i=0; icl.length; i){
cl[i]=new CLabel();
cl[i].addMouseListener(this);
add(cl[i]);
}
fc=new JRadioButton("fc",true);
bc=new JRadioButton("bc");
bg=new ButtonGroup();
bg.add(fc);bg.add(bc);
add(fc);add(bc);
fc.setOpaque(true);
bc.setOpaque(true);
fc.setBackground(Color.white);
bc.setBackground(Color.blue);
fillC=new JCheckBox("Fill",true);
drawB=new JCheckBox("Draw",true);
fillC.addActionListener(this);
drawB.addActionListener(this);
add(fillC);add(drawB);
clear=new JButton("clear");
clear.addActionListener(this);
add(clear);
up=new JButton("zUp");
up.addActionListener(this);
add(up);
down=new JButton("zDown");
down.addActionListener(this);
add(down);
save=new JButton("Save");
save.addActionListener(this);
add(save);
load=new JButton("Load");
load.addActionListener(this);
add(load);
}
public void mouseClicked(MouseEvent e) {
JLabel l=(JLabel)e.getSource();
if(e.getClickCount()==2){
Color sc=JColorChooser.showDialog(null, "Color chooser", l.getBackground());
l.setBackground(sc);
mousePressed(e);
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
Color c=((JLabel)e.getSource()).getBackground();
if(fc.isSelected())
fc.setBackground(c);
else if(bc.isSelected())
bc.setBackground(c);
M.cp();
}
public void mouseReleased(MouseEvent e) {}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==clear)M.clear();
else if(e.getSource()==up)M.up();
else if(e.getSource()==down)M.down();
else if(e.getSource()==save)M.save();
else if(e.getSource()==load)M.load();
else if(e.getSource()==fillC||e.getSource()==drawB)M.cp();
}
}
class CLabel extends JLabel{
static Color[] cs={Color.red,Color.orange,Color.yellow,Color.green,Color.cyan,
Color.blue,Color.magenta,Color.magenta.brighter(),
Color.white,Color.black,Color.gray,Color.LIGHT_GRAY,Color.DARK_GRAY,};
static int i;
CLabel(){
this.setOpaque(true);
this.setBackground(cs[i]);
this.setBorder(BorderFactory.createLineBorder(Color.black));
this.setPreferredSize(new Dimension(10,20));
}
}
class M{
static JFileChooser jfc=new JFileChooser();
static Menu m=new Menu();
static CVS c=new CVS();
static SA sa=new SA();
static S ts=null,selected=null;
static Color fc,bc;
static void clear(){
sa.ss.clear();
c.repaint();
}
public static void cp() {
System.out.println(selected);
if(selected!=null){
selected.fillColor=m.fc.getBackground();
selected.borderColor=m.bc.getBackground();
selected.fc=m.fillC.isSelected();
selected.db=m.drawB.isSelected();
c.repaint();
}
}
public static void up() {
if(selected!=null){
sa.upZ(selected);
c.repaint();
}
}
public static void down(){
if(selected!=null){
sa.downZ(selected);
c.repaint();
}
}
static{
jfc.setFileFilter(new FileNameExtensionFilter("JDraw file (*.jdraw,*.jdr)","jdr","jdraw"));
}
static void save(){
int x=jfc.showSaveDialog(c);
if(x==JFileChooser.APPROVE_OPTION){
File f = jfc.getSelectedFile();
try{
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(sa);
oos.flush();
oos.close();
}catch(Exception e){}
}
}
static void load(){
int x=jfc.showOpenDialog(c);
if(x==JFileChooser.APPROVE_OPTION){
File f = jfc.getSelectedFile();
try{
ObjectInputStream oos=new ObjectInputStream(new FileInputStream(f));
Object r=oos.readObject();
if(r!=null){
sa=(SA)r;
c.repaint();
}
oos.close();
}catch(Exception e){e.printStackTrace();}
}
}
static int mx,my,tx,ty,ox,oy;
static int pc=0,pmax;
static int sm;
static boolean ne=true;
static int mid;
static void mp(Point p){
mid=m.method.getSelectedIndex();
if(mid==0){
if(ne){
mx=p.x;my=p.y;
pc=0;
sm=m.sbox.getSelectedIndex();
pmax=sm==4?2:1;
ne=false;
}
pc;
}
else if(mid==1){
checkSel(p);
mx=p.x;my=p.y;
}
else if(mid==2){
checkSel(p);
if(selected!=null){
sa.ss.remove(selected);
c.repaint();
}
}
}
private static void checkSel(Point p) {
selected=null;
for(int i=sa.ss.size();i0; i--)
if(sa.ss.get(i-1).shape.contains(p)){
selected=sa.ss.get(i-1);break;
}
sa.select(selected);
c.repaint();
}
static void mt(){
Shape s=null;
int cx,cy,cw,ch;
switch(sm){
case 0:
case 2:
cx=Math.min(mx,tx);
cy=Math.min(my,ty);
cw=Math.abs(mx-tx);
ch=Math.abs(my-ty);
if(sm==0)
s=new Ellipse2D.Double(cx,cy,cw,ch);
else
s=new Rectangle(cx,cy,cw,ch);
break;
case 1:
s=new Line2D.Float(mx,my,tx,ty);
break;
case 3:
cw=Math.abs(mx-tx);
ch=Math.abs(my-ty);
int cd=(int)Math.sqrt(Math.pow(mx-tx,2) Math.pow(my-ty,2))*2;
cx=mx-cd/2;
cy=my-cd/2;
s=new Ellipse2D.Double(cx,cy,cd,cd);
break;
case 4:
Path2D p=new Path2D.Double();
p.moveTo(mx,my);
if(pc==1){
p.lineTo(tx, ty);
}
else{
p.quadTo(ox,oy,tx,ty);
}
s=p;
break;
}
ts=new S(s,m.fc.getBackground(),m.bc.getBackground(),m.fillC.isSelected(),m.drawB.isSelected(),null);
c.repaint();
}
static void md(Point p){
if(mid==0){
if(!sa.ss.isEmpty()){
sa.ss.get(sa.ss.size()-1).sel=false;
}
if(pc1){
ox=p.x;oy=p.y;
}
else{
tx=p.x;ty=p.y;
}
mt();
}
else if(mid==1){
if(selected!=null){
moveTo(selected,p);
c.repaint();
}
}
else if(mid==2){
checkSel(p);
if(selected!=null){
sa.ss.remove(selected);
c.repaint();
}
}
}
static void moveTo(S s, Point p) {
if(s.shape instanceof Rectangle){
Rectangle r=(Rectangle)s.shape;
r.setLocation(r.x p.x-mx,r.y p.y-my);
mx=p.x;my=p.y;
}
else if(s.shape instanceof Ellipse2D){
Ellipse2D e=(Ellipse2D)s.shape;
e.setFrame(e.getX() p.x-mx,e.getY() p.y-my,e.getWidth(),e.getHeight());
mx=p.x;my=p.y;
}
}
static void mr(Point p) {
if(pc==pmax){
pc=0;
ne=true;
sa.add(ts);
selected=ts;
ts=null;
}
}
}
class S implements Serializable{
boolean fc,db,sel=true;
Shape shape;
Color fillColor,borderColor;
Stroke stroke;
static Stroke bstroke=new MyBasicStroke();
static Stroke selectStroke=new BasicStroke(1,BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER,1,new float[]{5,2},1);
S(Shape s,Color c,Color b,boolean f,boolean d,Stroke k){
this.shape=s;this.fillColor=c;this.borderColor=b;this.fc=f;this.db=d;this.stroke=k==null?bstroke:k;
}
void draw(Graphics2D g){
if(fc){
g.setColor(fillColor);
g.fill(shape);
}
if(db){
g.setColor(borderColor);
g.setStroke(stroke);
g.draw(shape);
}
if(sel){
g.setColor(Color.green);
g.setStroke(selectStroke);
g.draw(shape.getBounds());
}
}
}
class MyBasicStroke extends BasicStroke implements Serializable{}
class SA implements Serializable{
ArrayListS ss=new ArrayListS();
void add(S s){
if(s!=null){
for(S sx:ss)
sx.sel=false;
ss.add(s);
}
}
S remove(int i){
return ss.remove(i);
}
void remove(S s){
ss.remove(s);
}
void upZ(S s){
indexZ(s,1);
}
void downZ(S s){
indexZ(s,-1);
}
void indexZ(S s, int i) {
int si=ss.indexOf(s);
if(si i0||si iss.size()-1)return;
swap(s,ss.get(si i));
}
void swap(S a,S b){
int ai=ss.indexOf(a);
int bi=ss.indexOf(b);
ss.set(ai,b);
ss.set(bi,a);
}
void select(S s){
for(S x:ss)
x.sel=false;
if(s!=null)
s.sel=true;
}
void drawAll(Graphics2D g){
for(S s:ss)
s.draw(g);
}
}
java画图的程序import java.awt.*;
import javax.swing.*;
public class TankWar extends JFrame {
public TankWar (String title) {
super(title);
this.setSize(600,500);
this.setLocationRelativeTo(null); //设置窗口的位置屏幕中间
this.setResizable(false); //设置为不可改变大小
this.setDefaultCloseOperation(EXIT_ON_CLOSE); //设置关闭事件
MyJPanel myJPanel = new MyJPanel(); //创建一个MyJPanel实例对象myJPanel
myJPanel.setBackground(Color.blue);//设置myJPanel的背景颜色
this.add(myJPanel);
this.setVisible(true);
}
/*内部继承JPanel类*/
class MyJPanel extends JPanel {
protected void paintComponent(Graphics g) {
g.setClip(30,30,300,300);
Color c = g.getColor();
g.setColor(Color.red);
g.fillOval(200, 100, 300, 300);
g.setColor(c);
}
}
public static void main(String args[]){
new TankWar ("坦克大战");
}
}
求Java画图版,能画正多边形的代码!public class MiniDraw implements ActionListener, MouseListener{// Fieldsprivate JFrame frame = new JFrame("MiniDraw");
private DrawingCanvas canvas = new DrawingCanvas();private JButton colorButton;// the button for colour, so we can change its background to the current color.
private JTextField textField;// the field for entering text to put on the canvas// fields for recording the information needed to perform the next action
private enum Action {Line,Rect, Oval, Triangle, Text, Dot, Move, Delete, Push, Pull};private int pressedX;//where the mouse was pressed
private int pressedY;//where the mouse was pressed
private Action currentAction = Action.Line;
private Color currentColor = Color.black;private ListShape shapes = new ArrayList Shape();
/** Constructor sets up the GUI. */
public MiniDraw(){
frame.setSize(800,600); //The graphics area
canvas.addMouseListener(this);
frame.getContentPane().add(canvas, BorderLayout.CENTER); //The buttons
JPanel topPanel = new JPanel( );
frame.getContentPane().add(topPanel, BorderLayout.NORTH);
JPanel botPanel = new JPanel( );
frame.getContentPane().add(botPanel, BorderLayout.SOUTH);
addButton(topPanel, "New");
addButton(topPanel, "Open");
addButton(topPanel, "Save");
addButton(topPanel, "Delete");
addButton(topPanel, "Move");
colorButton = addButton(topPanel, "Color");// remember the button so we can change its colour
addButton(topPanel, "Push");
addButton(topPanel, "Pull");
addButton(topPanel, "Reverse");
addButton(topPanel, "Quit"); botPanel.add(new JLabel("Shapes: "));
addButton(botPanel, "Line");
addButton(botPanel, "Rect");
addButton(botPanel, "Oval");
addButton(botPanel, "Triangle");
addButton(botPanel, "Dot");
addButton(botPanel, "Text");
textField = new JTextField("Enter text", 12);
botPanel.add(new JLabel(" : "));
botPanel.add(textField); frame.setVisible(true);
}/** Utility method to make new button and add it to the panel
Returns the button, in case we need it.*/
private JButton addButton(JPanel panel, String name){
JButton button = new JButton(name);
button.addActionListener(this);
panel.add(button);
return button;
}/** Respond to button presses */public void actionPerformed(ActionEvent e){
String button = e.getActionCommand();
//System.out.printf("Button: %s\n", button);//for debugging
if (button.equals("New") )
newDrawing();
else if (button.equals("Open") )
openDrawing();
else if (button.equals("Save") )
saveDrawing();
else if (button.equals("Color") )
selectColor();
else if (button.equals("Reverse") )
reverseDrawing();
else if (button.equals("Quit") )
frame.dispose();
else{ //
currentAction = Action.valueOf(button);// converts the String to an Action.
}
}/** Sets the current color.
* Also changes the color of the Color button and sets the background color of the canvas */
private void selectColor(){
Color newColor = JColorChooser.showDialog(frame,"Choose Color for new shapes", currentColor);
if (newColor!=null){
currentColor=newColor;
colorButton.setBackground(currentColor);
}
}// Respond to mouse events
/** When mouse is pressed, remember the position in order to construct the Shape when
* the mouse is released. */
public void mousePressed(MouseEvent e) {
int x = e.getX(); int y = e.getY();
//System.out.printf("Pressed at (%d, %d)\n", x, y);//for debugging
pressedX = x;
pressedY = y;
}/** When the Mouse is released, depending on the currentAction,
*either construct the shape that was being drawn, or perform the
*action (delete or move) on the shape under the point where the mouse was pressed.*/
public void mouseReleased(MouseEvent e) {
int x = e.getX(); int y = e.getY();
//System.out.printf("Released at (%d, %d)\n", x, y);//for debugging
if (currentAction==Action.Move)
moveShape(pressedX, pressedY, x, y);
else if (currentAction==Action.Delete)
deleteShape(x, y);
else if (currentAction==Action.Push)
pushShapeBackward(x, y);
else if (currentAction==Action.Pull)
pullShapeForward(x, y);
else
addShape(pressedX, pressedY, x, y);
}public void mouseClicked(MouseEvent e) {}//needed to satisfy interface
public void mouseEntered(MouseEvent e) {}//needed to satisfy interface
public void mouseExited(MouseEvent e) {}//needed to satisfy interface
// Helper methods for implementing the button and mouse actions
/** Start a new drawing. */
public void newDrawing(){
shapes = new ArrayListShape();
canvas.clear();
}
/** Open a file, and read all the shape descriptions into the current drawing. */
public void openDrawing(){
String fname = FileChooser.open();
if (fname==null) return;
try {
Scanner file = new Scanner(new File(fname));
//System.out.printf("Opening file %s\n", fname);
shapes = new ArrayListShape();
while (file.hasNext()){
String shapetype = file.next().toLowerCase();
if (shapetype.equals("oval"))
shapes.add(new Oval(file));
else if (shapetype.equals("rectangle"))
shapes.add(new Rectangle(file));
if (shapetype.equals("line"))
shapes.add(new Line(file));
if (shapetype.equals("textshape"))
shapes.add(new TextShape(file));
else if (shapetype.equals("triangle"))
shapes.add(new Triangle(file));
else if (shapetype.equals("dot"))
shapes.add(new Dot(file));
}
render();
}
catch(IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}/** Save the current drawing to a file. */
public void saveDrawing(){
String fname =FileChooser.save();
if ( fname == null )
return;
try{
PrintStream f = new PrintStream( new File( fname ));
for ( Shape shape : shapes )
f.println( shape.toString());
f.close ();
}
catch(IOException ex){
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
/** Returns the shape under the position (x y), or null if no such shape */
public Shape findShape(int x, int y){
for (int i = shapes.size()-1; i=0; i--){ // must go backwards, so can't use foreach
Shape shape = shapes.get(i);
if (shape.pointOnShape(x, y))
return shape;
}
return null;// no shape found at position
}
/** Moves the shape that was under the mousePressed position (pressedX, pressedY)
to where the mouse was released.
Ie, move it by (newX-pressedX) and (newY-pressedY)
*/
public void moveShape(int fromX, int fromY, int toX, int toY){
//System.out.printf("Moving shape under (%d, %d) to (%d, %d)\n", pressedX, pressedY, newX, newY);//for debugging
Shape shape = findShape(fromX, fromY);
if (shape!= null)
shape.moveBy((toX-fromX), (toY-fromY));
render();
}/** Deletes the shape that was under the mouseReleased position (x, y)
*/
public void deleteShape(int x, int y){ for ( Shape shape : shapes) {
if ( shape.pointOnShape(x, y ))
shapes.remove ( shape );
}
render();
}
/** Pull the shape under the mouse one position closer to the "front"
of the drawing */
public void pullShapeForward(int x, int y){
// System.out.printf("Pulling shape under (%d, %d) forward\n", x, y);//for debugging
// YOUR CODE HERE
Shape shape = findShape( x, y );
if (shape!=null ) {
int index = shapes.indexOf(shape);
if ( index shapes.size()-1){
shapes.remove(index);
shapes.add( index 1,shape);
}
render();
}
}
/** Push the shape under the mouse one position further from the "front"
of the drawing */
public void pushShapeBackward(int x, int y){
//System.out.printf("Pushing shape under (%d, %d) backward\n", x, y);//for debugging
// YOUR CODE HERE
Shape shape = findShape(x, y );
if ( shape!=null ){
int index = shapes.indexOf(shape);
if( index0 )
【java复杂画图程序代码 java编写画图程序】shapes.remove( index);
shapes.add( index-1, shape);
}
render();
}
/** Reverse the order of the shapes in the drawing */
public void reverseDrawing(){ ListShapetemp = new ArrayListShape();
while ( shapes.size()0 ) {
temp.add ( shapes.remove(shapes.size()-1));
}
shapes= temp;
render();
}
/** Construct a new Shape object of the appropriate kind (depending on currentAction)
Uses the appropriate constructor of the Line, Rectangle, Oval, TextShape, or Triangle classes.
adds the shape it to the collection of shapes in the drawing, and
renders the shape on the canvas */
public void addShape(int x1, int y1, int x2, int y2){
//System.out.printf("Drawing shape %s, at (%d, %d)-(%d, %d)\n", currentAction, pressedX, pressedY, x, y);//for debugging
Shape shape = null;
if (currentAction==Action.Line)
shapes.add(new Line(x1, y1, x2, y2, currentColor));
if (currentAction==Action.Triangle)
shapes.add(new Triangle(x1, y1, x2, y2, currentColor));
if (currentAction==Action.Dot)
shapes.add(new Dot(x2, y2, currentColor));
else if (currentAction==Action.Text)
shapes.add(new TextShape(x2, y2, textField.getText(), currentColor));
else{
int left= Math.min(x1, x2);
int top= Math.min(y1, y2);
int width= Math.abs(x1 - x2);
int height= Math.abs(y1 - y2);
if (currentAction==Action.Rect)
shapes.add(new Rectangle(left, top, width, height, currentColor));
else if (currentAction==Action.Oval)
shapes.add(new Oval(left, top, width, height, currentColor));
}
render();
}public void render(){
canvas.clear(false);
for (Shape shape : shapes){
shape.render(canvas);
}
canvas.display();
}public static void main(String args[]){
new MiniDraw();
}}
求java版画图程序的源代码找到了 , 很久以前写的一个简单画图 , 呵呵~当时要求用AWT写 , 很难受 。
package net.miqiang.gui;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
/**
* 简单画图板程序
* 好久没用 AWT 了,写起来真别扭,如果用 swing 会很舒服,有空再改写吧 。
*
* @author 米强
*
*/
public class TestMain extends Frame {
// 画板
private Palette palette = null;
// 显示当前颜色的面板
private Panel nonceColor = null;
// 画笔粗细
private Label drawWidth = null;
// 画笔端点的装饰
private Label drawCap = null;
// 选取颜色按钮的监听事件类
private ButtonColorAction buttonColorAction = null;
// 鼠标进入按钮后光标样式的监听事件类
private ButtonCursor buttonCursor = null;
// 画笔样式的监听事件
private ButtonStrokeAction buttonStrokeAction = null;
/**
* 构造方法
*
*/
public TestMain() {
// 设置标题栏文字
super("简易画图板");
// 构造一个画图板
palette = new Palette();
Panel pane = new Panel(new GridLayout(2, 1));
// 画笔颜色选择器
Panel paneColor = new Panel(new GridLayout(1, 13));
// 12 个颜色选择按钮
Button [] buttonColor = new Button[12];
Color [] color = {Color.black, Color.blue, Color.cyan, Color.darkGray, Color.gray, Color.green, Color.magenta, Color.orange, Color.pink, Color.red, Color.white, Color.yellow};
// 显示当前颜色的面板
nonceColor = new Panel();
nonceColor.setBackground(Color.black);
paneColor.add(nonceColor);
buttonColorAction = new ButtonColorAction();
buttonCursor = new ButtonCursor();
for(int i = 0; ibuttonColor.length; i){
buttonColor[i] = new Button();
buttonColor[i].setBackground(color[i]);
buttonColor[i].addActionListener(buttonColorAction);
buttonColor[i].addMouseListener(buttonCursor);
paneColor.add(buttonColor[i]);
}
pane.add(paneColor);
// 画笔颜色选择器
Panel paneStroke = new Panel(new GridLayout(1, 13));
// 控制画笔样式
buttonStrokeAction = new ButtonStrokeAction();
Button [] buttonStroke = new Button[11];
buttonStroke[0] = new Button("1");
buttonStroke[1] = new Button("3");
buttonStroke[2] = new Button("5");
buttonStroke[3] = new Button("7");
buttonStroke[4] = new Button("9");
buttonStroke[5] = new Button("11");
buttonStroke[6] = new Button("13");
buttonStroke[7] = new Button("15");
buttonStroke[8] = new Button("17");
buttonStroke[9] = new Button("■");
buttonStroke[10] = new Button("●");
drawWidth = new Label("3", Label.CENTER);
drawCap = new Label("●", Label.CENTER);
drawWidth.setBackground(Color.lightGray);
drawCap.setBackground(Color.lightGray);
paneStroke.add(drawWidth);
for(int i = 0; ibuttonStroke.length; i){
paneStroke.add(buttonStroke[i]);
buttonStroke[i].addMouseListener(buttonCursor);
buttonStroke[i].addActionListener(buttonStrokeAction);
if(i = 8){
buttonStroke[i].setName("width");
}else{
buttonStroke[i].setName("cap");
}
if(i == 8){
paneStroke.add(drawCap);
}
}
pane.add(paneStroke);
// 将画笔颜色选择器添加到窗体中
this.add(pane, BorderLayout.NORTH);
// 将画图板添加到窗体中
this.add(palette);
// 添加窗口监听,点击关闭按钮时退出程序
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// 设置窗体 ICON 图标
this.setIconImage(Toolkit.getDefaultToolkit().createImage("images/palette.png"));
// 设置窗口的大小
this.setSize(new Dimension(400, 430));
// 设置窗口位置 , 处于屏幕正中央
this.setLocationRelativeTo(null);
// 显示窗口
this.setVisible(true);
}
/**
* 程序入口
*
* @param args
*字符串数组参数
*/
public static void main(String[] args) {
new TestMain();
}
/**
* 选取颜色按钮的监听事件类
* @author 米强
*
*/
class ButtonColorAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
Color color_temp = ((Button)e.getSource()).getBackground();
nonceColor.setBackground(color_temp);
palette.setColor(color_temp);
}
}
/**
* 鼠标进入按钮变换光标样式监听事件类
* @author 米强
*
*/
class ButtonCursor extends MouseAdapter {
public void mouseEntered(MouseEvent e) {
((Button)e.getSource()).setCursor(new Cursor(Cursor.HAND_CURSOR));
}
public void mouseExited(MouseEvent e) {
((Button)e.getSource()).setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
/**
* 设置画笔的监听事件类
* @author 米强
*
*/
class ButtonStrokeAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
Button button_temp = (Button) e.getSource();
String name = button_temp.getName();
if(name.equalsIgnoreCase("width")){
drawWidth.setText(button_temp.getLabel());
palette.setStroke(Float.parseFloat(button_temp.getLabel()));
}else if(name.equalsIgnoreCase("cap")){
drawCap.setText(button_temp.getLabel());
if(button_temp.getLabel().equals("■")){
palette.setStroke(BasicStroke.CAP_SQUARE);
}else if(button_temp.getLabel().equals("●")){
palette.setStroke(BasicStroke.CAP_ROUND);
}
}
}
}
}
/**
* 画板类
*
* @author 米强
*
*/
class Palette extends Panel implements MouseListener, MouseMotionListener {
// 鼠标 X 坐标的位置
private int mouseX = 0;
// 上一次 X 坐标位置
private int oldMouseX = 0;
// 鼠标 Y 坐标的位置
private int mouseY = 0;
// 上一次 Y 坐标位置
private int oldMouseY = 0;
// 画图颜色
private Color color = null;
// 画笔样式
private BasicStroke stroke = null;
// 缓存图形
private BufferedImage image = null;
/**
* 构造一个画板类
*
*/
public Palette() {
this.addMouseListener(this);
this.addMouseMotionListener(this);
// 默认黑色画笔
color = new Color(0, 0, 0);
// 设置默认画笔样式
stroke = new BasicStroke(3.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
// 建立 1280 * 1024 的 RGB 缓存图象
image = new BufferedImage(1280, 1024, BufferedImage.TYPE_INT_RGB);
// 设置颜色
image.getGraphics().setColor(Color.white);
// 画背景
image.getGraphics().fillRect(0, 0, 1280, 1024);
}
/**
* 重写 paint 绘图方法
*/
public void paint(Graphics g) {
super.paint(g);
// 转换为 Graphics2D
Graphics2D g2d = (Graphics2D) g;
// 获取缓存图形 Graphics2D
Graphics2D bg = image.createGraphics();
// 图形抗锯齿
bg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 设置绘图颜色
bg.setColor(color);
// 设置画笔样式
bg.setStroke(stroke);
// 画线 , 从上一个点到新的点
bg.drawLine(oldMouseX, oldMouseY, mouseX, mouseY);
// 将缓存中的图形画到画板上
g2d.drawImage(image, 0, 0, this);
}
/**
* 重写 update 方法
*/
public void update(Graphics g) {
this.paint(g);
}
/**
* @return stroke
*/
public BasicStroke getStroke() {
return stroke;
}
/**
* @param stroke 要设置的 stroke
*/
public void setStroke(BasicStroke stroke) {
this.stroke = stroke;
}
/**
* 设置画笔粗细
* @param width
*/
public void setStroke(float width) {
this.stroke = new BasicStroke(width, stroke.getEndCap(), stroke.getLineJoin());
}
/**
* 设置画笔端点的装饰
* @param cap 参考 java.awt.BasicStroke 类静态字段
*/
public void setStroke(int cap) {
this.stroke = new BasicStroke(stroke.getLineWidth(), cap, stroke.getLineJoin());
}
/**
* @return color
*/
public Color getColor() {
return color;
}
/**
* @param color 要设置的 color
*/
public void setColor(Color color) {
this.color = color;
}
public void mouseClicked(MouseEvent mouseEvent) {
}
/**
* 鼠标按下
*/
public void mousePressed(MouseEvent mouseEvent) {
this.oldMouseX = this.mouseX = mouseEvent.getX();
this.oldMouseY = this.mouseY = mouseEvent.getY();
repaint();
}
public void mouseReleased(MouseEvent mouseEvent) {
}
/**
* 鼠标进入棋盘
*/
public void mouseEntered(MouseEvent mouseEvent) {
this.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
}
/**
* 鼠标退出棋盘
*/
public void mouseExited(MouseEvent mouseEvent) {
this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
/**
* 鼠标拖动
*/
public void mouseDragged(MouseEvent mouseEvent) {
this.oldMouseX = this.mouseX;
this.oldMouseY = this.mouseY;
this.mouseX = mouseEvent.getX();
this.mouseY = mouseEvent.getY();
repaint();
}
public void mouseMoved(MouseEvent mouseEvent) {
}
}
java复杂画图程序代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java编写画图程序、java复杂画图程序代码的信息别忘了在本站进行查找喔 。
推荐阅读
- jquery控制visible属性,利用jquery控制div显示和隐藏
- 安卓7.0系统电话拦截,安卓70系统电话拦截怎么设置
- 如何找个电商平台,如何找电商货源
- jquery不显示滚动,jqgrid滚动条
- python函数测验题 python函数的例题
- c.net框架在哪里找,net框架组成
- 电脑外设键盘怎么发光,电脑外设键盘怎么发光的
- python绘制常函数 python 函数绘制
- 什么cpu可以装鸿蒙,哪些型号可以装鸿蒙