/******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class DibujoTableta extends JPanel implements KeyListener {
private int x = 250, y = 250; // Posición inicial del cursor
private final int STEP = 10; // Tamaño del paso
private ArrayList<Point> points = new ArrayList<>(); // Lista de puntos dibujados
public static void main(String[] args) {
JFrame frame = new JFrame("Tableta de Dibujo");
DibujoTableta panel = new DibujoTableta();
JButton clearButton = new JButton("Limpiar");
clearButton.addActionListener(e -> panel.limpiarPantalla());
frame.setLayout(new BorderLayout());
frame.add(panel, BorderLayout.CENTER);
frame.add(clearButton, BorderLayout.SOUTH);
panel.setPreferredSize(new Dimension(500, 500));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public DibujoTableta() {
setFocusable(true);
addKeyListener(this);
}
@Override //sobrescritura de métodos
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
for (int i = 1; i < points.size(); i++) {
Point p1 = points.get(i - 1);
Point p2 = points.get(i);
g.drawLine(p1.x, p1.y, p2.x, p2.y);
}
}
@Override //sobrescritura de métodos
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_UP) {
y -= STEP;
} else if (keyCode == KeyEvent.VK_DOWN) {
y += STEP;
} else if (keyCode == KeyEvent.VK_LEFT) {
x -= STEP;
} else if (keyCode == KeyEvent.VK_RIGHT) {
x += STEP;
}
points.add(new Point(x, y));
repaint();
}
public void limpiarPantalla() {
points.clear();
x = 250;
y = 250;
repaint();
}
@Override //sobrescritura de métodos
public void keyReleased(KeyEvent e) {}
@Override //sobrescritura de métodos
public void keyTyped(KeyEvent e) {}
}