Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.*;
- import javax.swing.*;
- import java.awt.event.*;
- import java.awt.FlowLayout;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JPanel;
- public class Main extends JPanel {
- private static final int DEFAULT_WIDTH = 800;
- private static final int DEFAULT_HEIGHT = 800;
- private static final Color BACK_COLOR = Color.WHITE;
- private Color curColor = Color.BLACK;
- private int x1, y1, x2, y2;
- private Graphics g;
- public static void main(String[] args) {
- JFrame frame = new JFrame("Paint program simple");
- frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
- JPanel panel = new Main();
- frame.add(panel);
- frame.pack();
- frame.setVisible(true);
- }
- private Main() {
- setBackground(BACK_COLOR);
- setPreferredSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
- MyMouseHandler handler = new MyMouseHandler();
- this.addMouseListener(handler);
- this.addMouseMotionListener(handler);
- this.setFocusable(true);
- this.addKeyListener(new KeyAdapter() {
- @Override
- public void keyPressed(KeyEvent e) {
- // TODO Auto-generated method stub
- int key = e.getKeyCode();
- switch (key) {
- case KeyEvent.VK_Y:
- curColor = Color.YELLOW;
- break;
- case KeyEvent.VK_R:
- curColor = Color.RED;
- break;
- case KeyEvent.VK_G:
- curColor = Color.GREEN;
- break;
- case KeyEvent.VK_O:
- curColor = Color.ORANGE;
- break;
- case KeyEvent.VK_B:
- curColor = Color.BLACK;
- break;
- }
- }
- });
- }
- private class MyMouseHandler extends MouseAdapter {
- public void mousePressed(MouseEvent e) {
- x1 = e.getX();
- y1 = e.getY();
- g = getGraphics();
- x2 = x1;
- y2 = y1;
- }
- public void mouseDragged(MouseEvent e) {
- x1 = e.getX();
- y1 = e.getY();
- g.setColor(curColor);
- g.drawLine(x1, y1, x2, y2);
- x2 = x1;
- y2 = y1;
- }
- }}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement