📄 paintpanel.java
字号:
import java.awt.event.*;import javax.swing.*;import java.awt.*;public class PaintPanel extends JPanel { public PaintPanel() { setLayout(new BorderLayout()); JPanel p = new JPanel(); p.setLayout(new GridLayout(1, 3)); p.add(new Rectangle()); p.add(new Oval()); p.add(new Line()); add(p, "North"); MouseKeeper k = new MouseKeeper(); addMouseListener(k); addMouseMotionListener(k); } private Image image = null; private Shape currentShape = null; private abstract class Shape extends JButton implements ActionListener { public Shape(String name) { super(name); addActionListener(this); } public abstract void draw(Graphics g, int a, int b, int c, int d); public void actionPerformed(ActionEvent e) { currentShape = this; } } private class Rectangle extends Shape { public Rectangle() { super("Rectangle"); } public void draw(Graphics g, int a, int b, int c, int d) { int w = c - a; int h = d - b; g.drawRect(a, b, w, h); } } private class Oval extends Shape { public Oval() { super("Oval"); } public void draw(Graphics g, int a, int b, int c, int d) { int w = c - a; int h = d - b; g.drawOval(a, b, w, h); } } private class Line extends Shape { public Line() { super("Line"); } public void draw(Graphics g, int a, int b, int c, int d) { g.drawLine(a, b, c, d); } } private class MouseKeeper extends MouseAdapter implements MouseMotionListener { private int startx, starty; private int lastx, lasty; public void mousePressed(MouseEvent e) { lastx = startx = e.getX(); lasty = starty = e.getY() - 50; } private void drawShape(Graphics g) { if (currentShape != null) currentShape.draw(g, startx, starty, lastx, lasty); } public void mouseDragged(MouseEvent e) { Graphics g = image.getGraphics(); g.setXORMode(Color.white); drawShape(g); lastx = e.getX(); lasty = e.getY() - 50; drawShape(g); repaint(); } public void mouseReleased(MouseEvent e) { Graphics g = image.getGraphics(); g.setXORMode(Color.white); drawShape(g); g.setPaintMode(); lastx = e.getX(); lasty = e.getY() - 50; drawShape(g); repaint(); } public void mouseMoved(MouseEvent e) {} } public void paintComponent(Graphics g) { super.paintComponent(g); if(image == null) image = createImage(400,300); if (image!= null) g.drawImage(image, 0, 49, this); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -