Delete all drawn shapes JAVA - java

I need to delete shapes individually or all of them!
please help I've tried deleting all contents from my arrayList "Figuras"
and removeAll from panel
public class PaintRodo extends JFrame {
JButton linea, circulo, rectangulo, trazo, llenar,borrar;
static int seleccion = 1;
Color trazoC = Color.BLACK;
Color llenarC = Color.lightGray;
JMenuBar barra;
public static void main(String[] args) {
new PaintRodo();
}
public PaintRodo() {
this.setSize(1000,700);
this.setTitle("Paint");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(Color.BLACK);
Box miBox = Box.createHorizontalBox();
linea= AgregarIcono("./src/linea.png",2);
circulo= AgregarIcono("./src/circ.png",3);
rectangulo= AgregarIcono("./src/rect.png",4);
trazo = AgregarIconoColor("./src/trazo.png",5,true);
llenar = AgregarIconoColor("./src/llenar.png",6,false);
borrar = AgregarIcono("./src/borrador.png",7);
miBox.add(linea);
miBox.add(circulo);
miBox.add(rectangulo);
miBox.add(llenar);
miBox.add(trazo);
miBox.add(borrar);
panel.add(miBox);
this.add(panel,BorderLayout.NORTH);
this.add(new Lienzo(),BorderLayout.CENTER);
this.setVisible(true);
}
public JButton AgregarIcono (String icono, final int accion){
JButton boton = new JButton();
Icon iconos = new ImageIcon (icono);
boton.setIcon(iconos);
boton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
seleccion =accion;
}
});
return boton;
}
public JButton AgregarIconoColor (String icono, final int accion,final boolean grosor ){
JButton boton = new JButton();
Icon iconos = new ImageIcon (icono);
boton.setIcon(iconos);
boton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(grosor){
trazoC = JColorChooser.showDialog(null,"Elige el Contorno",Color.BLACK);
}
else{
llenarC = JColorChooser.showDialog(null,"Elige el Relleno",Color.BLACK);
}
}
});
return boton;
}
public class Lienzo extends JComponent{
ArrayList<Shape> figuras = new ArrayList<Shape>();
ArrayList<Color> arrLleno = new ArrayList<Color>();
ArrayList<Color> arrTrazo = new ArrayList<Color>();
Point inicio,fin;
public Lienzo(){
this.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e){
if (seleccion!=1){
inicio = new Point (e.getX(),e.getY());
fin=inicio;
repaint();
}
}
public void mouseReleased(MouseEvent e){
if (seleccion!=1){
Shape SAVEfig=null;
if (seleccion==2){
SAVEfig = crearLinea(inicio.x,inicio.y,e.getX(),e.getY());
}
else if (seleccion==3){
SAVEfig = crearCirculo(inicio.x,inicio.y,e.getX(),e.getY());
}
figuras.add(SAVEfig);
arrLleno.add(llenarC);
arrTrazo.add(trazoC);
repaint();
}
}
});//mouselistener
this.addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
fin= new Point (e.getX(),e.getY());
repaint();
}
});//MotionListener
}//constructor lienzo
public void paint (Graphics g){
Graphics2D graFig = (Graphics2D)g;
graFig.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
graFig.setStroke (new BasicStroke(2));
Iterator<Color>contadorTrazo= arrTrazo.iterator();
Iterator<Color>contadorLleno= arrLleno.iterator();
graFig.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,1.0f));
this.setBackground(Color.LIGHT_GRAY);
for (Shape i: figuras){
graFig.setPaint(contadorTrazo.next());
graFig.draw(i);
graFig.setPaint(contadorLleno.next());
graFig.fill(i);
}
if (inicio!=null&&fin!=null){
graFig.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.40f));
graFig.setPaint(Color.LIGHT_GRAY);
Shape SAVEfig=null;
if (seleccion==2){
SAVEfig=crearLinea(inicio.x,inicio.y,fin.x,fin.y);
}
else if (seleccion==3){
SAVEfig=crearCirculo(inicio.x,inicio.y,fin.x,fin.y);
}
graFig.draw(SAVEfig);
}
}
private Rectangle2D.Float crearRectangulo(int x1, int y1,int x2 , int y2){
int x =Math.min(x1, x2);
int y = Math.min(y1, y2);
int ancho = Math.abs(x1-x2);
int alto = Math.abs(y1-y2);
return new Rectangle2D.Float(x,y,ancho,alto);
}
private Line2D.Float crearLinea(int x1, int y1, int x2, int y2){
return new Line2D.Float(x1, y1, x2, y2);
}
private Ellipse2D.Float crearCirculo( int x1, int y1, int x2, int y2){
int x = Math.min(x1, x2);
int y = Math.min(y1, y2);
int ancho = Math.abs(x1 - x2);
int alto = Math.abs(y1 - y2);
return new Ellipse2D.Float(x, y, ancho, alto);
}
}//classLienzo
}//MainClass Paint rodo
I need to delete shapes individually or all of them!
Please help; I've tried deleting all contents from my arrayList "Figuras"
and (removeAll) from panel

Related

Painting with paintComponent in Java

I have a problem with my code.
We have to code a Game called "Mühle" as our project for this semester.
My problem is, that I want to draw my game token on the field and it does not work although the tokens are added to the board and you can click them but they are not visible and I don't know what I can do.
This is the important part frow my GUI Class:
public class GUIMühle extends JFrame {
static JLabel spieler1, spieler2;
static JFrame frame;
static JButton[] button;
static JButton btnReset;
static int x, y;
static int gewinner = 0;
static int player = 2;
static Buttons[] buttons;
static Steine[] steine1;
static Steine[] steine2;
public GUIMühle(){
InitUI();
}
private void InitUI(){
MouseEvents ME = new MouseEvents();
frame = new JFrame("Mühle");
frame.setSize(960, 540);
frame.setLocationRelativeTo(null);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.CYAN);
frame.setResizable(false);
DrawSpielbrett spielbrett = new DrawSpielbrett();
spielbrett.setBounds(0,0,960,540);
spielbrett.setVisible(true);
frame.add(spielbrett);
spieler1 = new JLabel("Spieler 1");
spieler1.setBounds(590, 50, 150, 35);
spieler1.setFont(new Font("Arial", Font.BOLD, 30));
frame.add(spieler1);
spieler2 = new JLabel("Spieler 2");
spieler2.setBounds(785, 50, 150, 35);
spieler2.setFont(new Font("Arial", Font.BOLD, 30));
frame.add(spieler2);
// Spielsteine
steine1 = Steine.Erstellen(Color.white, 9, 665, 85);
steine2 = Steine.Erstellen(Color.black, 9, 860, 85);
DrawSteine[] drawSteine1 = new DrawSteine[9];
DrawSteine[] drawSteine2 = new DrawSteine[9];
for(int i = 0; i < steine1.length; i++){
steine1[i].setBounds(steine1[i].getX(),steine1[i].getY(),30,30);
steine1[i].addMouseListener(ME);
steine1[i].setVisible(true);
frame.add(steine1[i]);
}
for(int i = 0; i < steine2.length; i++){
steine2[i].setBounds(860,85+(i*32),30,30);
steine2[i].addMouseListener(ME);
frame.add(steine2[i]);
}
And this is the part from my game token class:
public class Steine extends JLabel{
private Color farbe;
private int x;
private int y;
public Steine(Color farbe, int x, int y){
this.farbe = farbe;
this.x = x;
this.y = y;
}
public static Steine[] Erstellen(Color farbe, int anzahl, int x, int y){
Steine[] steine = new Steine[anzahl];
for(int i = 0; i < steine.length; i++){
steine[i] = new Steine(farbe,x,y);
y = y + 32;
}
return steine;
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(this.farbe);
g.fillOval(this.x, this.y, 30, 30);
repaint();
}
/*public static void DrawSteine(Steine stein){
GUIMühle.frame.add(stein);
}*/
public Color getFarbe() {
return this.farbe;
}
#Override
public int getX() {
return this.x;
}
public void setX(int x) {
this.x = x;
}
#Override
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
I hope somebody can help me with this problem.
Thank you in advance.

How to draw curved lines on the screen with LinkedList and MouseListeners?

I am new to Java, as for my class's final project, I am developing a paint application that enables users to draw rich curved lines and common geometric shapes like rectangle and oval, also users can undo their shape drawing.
My app worked well on shape drawing. When I want to draw shapes, the shapes I want to draw are stored in the LinkedList which will be called to draw shapes on the screen When I applied this LinkedList concept to draw curved lines on the screen. I modified shape drawing code to draw curved lines. I ran to a problem; The result I got was little dots on the screen. If I tried to copy similar code that draws shapes for drawing curved lines, I would get straight lines instead of the curved lines.
I think this problem is related to MouseListener interfaces. I need some suggestions on how can I modify my MouseListener methods so that I can draw the curved lines on the screen properly.
Changes to my source code are welcome:
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PaintAppPlusSecondDraft extends JApplet implements ActionListener {
private static final long serialVersionUID = 1L;
private JMenuBar menuBar = new JMenuBar();
private JMenu mainMenu = new JMenu("Main menu");
private JMenuItem howToUse = new JMenuItem("How to use?");
private JMenuItem toDefaultMode = new JMenuItem("Return to default mode");
private JMenu boardSettings = new JMenu("Paint board settings");
private JMenuItem clearBoard = new JMenuItem("Clear screen");
private JMenuItem toDefaultBoard = new JMenuItem("Set to default paint board");
private JMenuItem bCustom = new JMenuItem("Set background colour");
private JMenu brushSettings = new JMenu("Paintbrush settings");
private JMenuItem eraser = new JMenuItem("Eraser");
private JMenuItem toDefaultBrush = new JMenuItem("Set to default paintbrush");
private JMenu setBrushSize = new JMenu("Set paintbrush size");
private JMenuItem Two = new JMenuItem("2 pixels");
private JMenuItem Four = new JMenuItem("4 pixels");
private JMenuItem Six = new JMenuItem("6 pixels");
private JMenuItem Eight = new JMenuItem("8 pixels");
private JMenuItem Ten = new JMenuItem("10 pixels");
private JMenu setBrushType = new JMenu("Set paintbrush type");
private JMenuItem defaultType1 = new JMenuItem("Default");
private JMenuItem defaultType2 = new JMenuItem("Default (light stroke)");
private JMenuItem Custom = new JMenuItem("Set paintbrush colour");
private JMenu drawShapes = new JMenu("Draw shapes");
private JMenuItem undoShape = new JMenuItem("Undo shape drawing");
private JMenuItem StraightLine = new JMenuItem("Straight line");
private JMenuItem Rectangle = new JMenuItem("Rectangle");
private JMenuItem Oval = new JMenuItem("Oval");
private JMenuItem filledRectangle = new JMenuItem("Filled rectangle");
private JMenuItem filledOval = new JMenuItem("Filled oval");
private int prevBrushSize = PaintBoard.brushSize;
private int prevBrushType = PaintBoard.brushType;
private Color prevBrushColour = PaintBoard.currentColour; /* For better user experience */
public void init() {
Frame frame = (Frame) getParent().getParent();
frame.setTitle("JAVA Paint plus");
frame.setResizable(false);
this.setSize(600, 400);
this.setContentPane(new PaintBoard());
mainMenu.add(howToUse);
mainMenu.add(toDefaultMode);
mainMenu.add(about);
boardSettings.add(clearBoard);
boardSettings.add(toDefaultBoard);
boardSettings.add(bCustom);
brushSettings.add(eraser);
brushSettings.add(toDefaultBrush);
setBrushSize.add(Two);
setBrushSize.add(Four);
setBrushSize.add(Six);
setBrushSize.add(Eight);
setBrushSize.add(Ten);
brushSettings.add(setBrushSize);
setBrushType.add(defaultType1);
setBrushType.add(defaultType2);
setBrushType.add(waterColourBrush);
setBrushType.add(triangleType);
setBrushType.add(squareType);
setBrushType.add(hexagonType);
setBrushType.add(starType);
setBrushType.add(heartType);
brushSettings.add(setBrushType);
brushSettings.add(Custom);
drawShapes.add(undoShape);
drawShapes.add(StraightLine);
drawShapes.add(Rectangle);
drawShapes.add(Oval);
drawShapes.add(filledRectangle);
drawShapes.add(filledOval);
menuBar.add(mainMenu);
menuBar.add(boardSettings);
menuBar.add(brushSettings);
menuBar.add(drawShapes);
howToUse.addActionListener(this);
toDefaultMode.addActionListener(this);
clearBoard.addActionListener(this);
toDefaultBoard.addActionListener(this);
bCustom.addActionListener(this);
eraser.addActionListener(this);
toDefaultBrush.addActionListener(this);
Two.addActionListener(this);
Four.addActionListener(this);
Six.addActionListener(this);
Eight.addActionListener(this);
Ten.addActionListener(this);
defaultType1.addActionListener(this);
defaultType2.addActionListener(this);
Custom.addActionListener(this);
undoShape.addActionListener(this);
StraightLine.addActionListener(this);
Rectangle.addActionListener(this);
Oval.addActionListener(this);
filledRectangle.addActionListener(this);
filledOval.addActionListener(this);
this.setJMenuBar(menuBar);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == howToUse) {
JOptionPane.showMessageDialog(null, "Press your mouse on the board and drag to draw!", "How to use?", JOptionPane.INFORMATION_MESSAGE);
}
if (e.getSource() == toDefaultMode) {
PaintBoard.canvasColour = Color.WHITE;
PaintBoard.brushSize = prevBrushSize = 6;
PaintBoard.brushType = prevBrushType = 1;
PaintBoard.currentColour = prevBrushColour = Color.BLACK;
PaintBoard.shapes.makeEmpty();
repaint();
}
if (e.getSource() == clearBoard) {
PaintBoard.shapes.makeEmpty();
repaint();
}
if (e.getSource() == toDefaultBoard) {
PaintBoard.canvasColour = Color.WHITE;
repaint();
}
if (e.getSource() == bCustom) {
try {
Color customColour = JColorChooser.showDialog(null, "Select colour:", PaintBoard.canvasColour);
PaintBoard.canvasColour = customColour;
PaintBoard.shapes.makeEmpty();
repaint();
} catch (NullPointerException ex) {
}
}
if (e.getSource() == eraser) {
prevBrushSize = PaintBoard.brushSize;
prevBrushType = PaintBoard.brushType;
prevBrushColour = PaintBoard.currentColour;
PaintBoard.brushSize = 44;
PaintBoard.brushType = 1;
PaintBoard.currentColour = PaintBoard.canvasColour;
}
if (e.getSource() == toDefaultBrush) {
PaintBoard.brushSize = prevBrushSize = 6;
PaintBoard.brushType = prevBrushType = 1;
PaintBoard.currentColour = prevBrushColour = Color.BLACK;
}
if (e.getSource() == Two) {
PaintBoard.brushSize = prevBrushSize = 2;
PaintBoard.brushType = prevBrushType;
PaintBoard.currentColour = prevBrushColour;
}
if (e.getSource() == Four) {
PaintBoard.brushSize = prevBrushSize = 4;
PaintBoard.brushType = prevBrushType;
PaintBoard.currentColour = prevBrushColour;
}
if (e.getSource() == Six) {
PaintBoard.brushSize = prevBrushSize = 6;
PaintBoard.brushType = prevBrushType;
PaintBoard.currentColour = prevBrushColour;
}
if (e.getSource() == Eight) {
PaintBoard.brushSize = prevBrushSize = 8;
PaintBoard.brushType = prevBrushType;
PaintBoard.currentColour = prevBrushColour;
}
if (e.getSource() == Ten) {
PaintBoard.brushSize = prevBrushSize = 10;
PaintBoard.brushType = prevBrushType;
PaintBoard.currentColour = prevBrushColour;
}
if (e.getSource() == defaultType1) {
PaintBoard.brushSize = prevBrushSize;
PaintBoard.brushType = prevBrushType = 1;
PaintBoard.currentColour = prevBrushColour;
}
if (e.getSource() == defaultType2) {
PaintBoard.brushSize = prevBrushSize;
PaintBoard.brushType = prevBrushType = 2;
PaintBoard.currentColour = prevBrushColour;
}
if (e.getSource() == Custom) {
try {
Color customColour = JColorChooser.showDialog(null, "Select colour:", PaintBoard.currentColour);
PaintBoard.brushSize = prevBrushSize;
PaintBoard.brushType = prevBrushType;
PaintBoard.currentColour = prevBrushColour = customColour;
} catch (NullPointerException ex) {
}
}
if (e.getSource() == undoShape) {
try {
PaintBoard.shapes.removeFront();
repaint();
} catch (NullPointerException ex) {
}
}
if (e.getSource() == StraightLine) {
PaintBoard.brushSize = prevBrushSize;
PaintBoard.currentColour = prevBrushColour;
PaintBoard.shapeType = 1;
}
if (e.getSource() == Rectangle) {
PaintBoard.currentColour = prevBrushColour;
PaintBoard.shapeType = 2;
PaintBoard.filled = false;
}
if (e.getSource() == Oval) {
PaintBoard.currentColour = prevBrushColour;
PaintBoard.shapeType = 3;
PaintBoard.filled = false;
}
if (e.getSource() == filledRectangle) {
PaintBoard.currentColour = prevBrushColour;
PaintBoard.shapeType = 2;
PaintBoard.filled = true;
}
if (e.getSource() == filledOval) {
PaintBoard.currentColour = prevBrushColour;
PaintBoard.shapeType = 3;
PaintBoard.filled = true;
}
}
abstract static class brushLine {
private int brushSize;
private int brushType;
private Color brushColour;
public brushLine() {
brushSize = 6;
brushType = 1;
brushColour = Color.BLACK;
}
public brushLine(int brushSize, int brushType, Color brushColour) {
this.brushSize = brushSize;
this.brushType = brushType;
this.brushColour = brushColour;
}
public void setBrushSize(int brushSize) {
this.brushSize = brushSize;
}
public void setBrushType(int brushType) {
this.brushType = brushType;
}
public void setBrushColour(Color brushColour) {
this.brushColour = brushColour;
}
public int getBrushSize() {
return brushSize;
}
public int getBrushType() {
return brushType;
}
public Color getBrushColour() {
return brushColour;
}
abstract void show(Graphics window);
}
static class paintBrushLine extends brushLine {
private int x1, y1, x2, y2;
public paintBrushLine() {
super();
x1 = 0;
y1 = 0;
x2 = 0;
y2 = 0;
}
public paintBrushLine(int brushSize, int brushType, Color brushColour, int x1, int y1, int x2, int y2) {
super(brushSize, brushType, brushColour);
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public void setX1(int x1) {
this.x1 = x1;
}
public void setY1(int y1) {
this.y1 = y1;
}
public void setX2(int x2) {
this.x2 = x2;
}
public void setY2(int y2) {
this.y2 = y2;
}
public int getX1() {
return x1;
}
public int getY1() {
return y1;
}
public int getX2() {
return x2;
}
public int getY2() {
return y2;
}
public void show(Graphics window) {
window.setColor(getBrushColour());
switch (getBrushType()) {
case 1://Default brush
((Graphics2D) window).setStroke(new BasicStroke(getBrushSize(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
window.drawLine(getX1(), getY1(), getX2(), getY2());
break;
case 2://Default brush (light stroke) --> Makes empty squares with few randomly positioned pixels
int[] pixelPos = new int[2];
for (int i = 0; i < ((getBrushSize()*getBrushSize()) / 10); i++) {
pixelPos[0] = new Random().nextInt(getBrushSize());
pixelPos[1] = new Random().nextInt(getBrushSize());
window.drawRect(getX1() + pixelPos[0], getY1() + pixelPos[1], 1, 1);
}
break;
}
}
}
abstract static class Shape {
private int x1, y1, x2, y2;
private int thickness;
private Color shapeColour;
public Shape() {
x1 = 0;
y1 = 0;
x2 = 0;
y2 = 0;
shapeColour = Color.BLACK;
}
public Shape(int x1, int y1, int x2, int y2, int thickness, Color shapeColour)
{
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.thickness = thickness;
this.shapeColour = shapeColour;
}
public void setX1(int x1) {
this.x1 = x1;
}
public void setY1(int y1) {
this.y1 = y1;
}
public void setX2(int x2) {
this.x2 = x2;
}
public void setY2(int y2) {
this.y2 = y2;
}
public void setThickness(int thickness) {
this.thickness = thickness;
}
public void setShapeColour(Color shapeColour) {
this.shapeColour = shapeColour;
}
public int getX1() {
return x1;
}
public int getY1() {
return y1;
}
public int getX2() {
return x2;
}
public int getY2() {
return y2;
}
public int getThickness() {
return thickness;
}
public Color getShapeColour() {
return shapeColour;
}
abstract void sketch(Graphics window);
}
abstract static class boundedShape extends Shape {
private int shapeType;
private boolean filled;
public boundedShape() {
super();
filled = false;
}
public boundedShape(int x1, int y1, int x2, int y2, int thickness, Color shapeColour, int shapeType, boolean filled) {
super(x1, y1, x2, y2, thickness, shapeColour);
this.shapeType = shapeType;
this.filled = filled;
}
public void setShapeType(int shapeType) {
this.shapeType = shapeType;
}
public void setFilled(boolean filled) {
this.filled = filled;
}
public int getUpperLeftX() {
return Math.min(getX1(), getX2());
}
public int getUpperLeftY() {
return Math.min(getY1(), getY2());
}
public int getWidth() {
return Math.abs(getX1() - getX2());
}
public int getHeight() {
return Math.abs(getY1() - getY2());
}
public int getShapeType() {
return shapeType;
}
public boolean getFilled() {
return filled;
}
abstract public void sketch(Graphics window);
}
static class geometricShape extends boundedShape {
public geometricShape() {
super();
}
public geometricShape(int x1, int y1, int x2, int y2, int thickness, Color shapeColour, int shapeType, boolean filled) {
super(x1, y1, x2, y2, thickness, shapeColour, shapeType, filled);
}
public void sketch(Graphics window) {
window.setColor(getShapeColour());
switch(getShapeType()) {
case 1://Straight line
((Graphics2D) window).setStroke(new BasicStroke(getThickness(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
window.drawLine(getX1(), getY1(), getX2(), getY2());
break;
case 2://Rectangle
if (getFilled())
window.fillRect(getUpperLeftX(), getUpperLeftY(), getWidth(), getHeight());
else {
((Graphics2D) window).setStroke(new BasicStroke(getThickness(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
window.drawRect(getUpperLeftX(), getUpperLeftY(), getWidth(), getHeight());
}
break;
case 3://Oval
if (getFilled())
window.fillOval(getUpperLeftX(), getUpperLeftY(), getWidth(), getHeight());
else {
((Graphics2D) window).setStroke(new BasicStroke(getThickness(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
window.drawOval(getUpperLeftX(), getUpperLeftY(), getWidth(), getHeight());
}
break;
}
}
}
static class PaintBoard extends JPanel implements MouseMotionListener, MouseListener {
private static final long serialVersionUID = 1L;
private boolean painting;
private int prevX, prevY;
private static Color canvasColour = Color.WHITE;
private static int brushSize = 6;
private static int brushType = 1;
private static Color currentColour = Color.BLACK;
private static LinkedList<brushLine> brushLines = new LinkedList<>();
private brushLine currentBrushLine;
private static LinkedList<Shape> shapes = new LinkedList<>();
private static int shapeType = 0;
private Shape currentShape = null;
private static boolean filled;
private JLabel mouseCoordinates = new JLabel("X: 0 pixels Y: 0 pixels");
public PaintBoard() {
setSize(getWidth(), getHeight());
setLayout(new BorderLayout());
add(mouseCoordinates, BorderLayout.SOUTH);
addMouseMotionListener(this);
addMouseListener(this);
}
#Override
public void paintComponent(Graphics board) {
super.paintComponent(board);
board.setColor(canvasColour);
board.fillRect(0, 0, getWidth(), getHeight());
ArrayList<brushLine> linesToDraw = brushLines.getArray();
for (int i = linesToDraw.size() - 1; i >= 0; i--)
linesToDraw.get(i).show(board);
if (currentBrushLine != null)
currentBrushLine.show(board);
ArrayList<Shape> shapesToDraw = shapes.getArray();
for (int j = shapesToDraw.size() - 1; j >= 0; j--)
shapesToDraw.get(j).sketch(board);
if (currentShape != null)
currentShape.sketch(board);
}
public void mouseDragged(MouseEvent e) {
mouseCoordinates.setText(String.format("X: %d pixels Y: %d pixels", e.getX(), e.getY()));
if (shapeType > 0) {
currentShape.setX2(e.getX());
currentShape.setY2(e.getY());
repaint();
} else {
if (!painting)
return;
((paintBrushLine) currentBrushLine).setX1(prevX);
((paintBrushLine) currentBrushLine).setY1(prevY);
((paintBrushLine) currentBrushLine).setX2(e.getX());
((paintBrushLine) currentBrushLine).setY2(e.getY());
repaint();
prevX = e.getX();
prevY = e.getY();
}
}
public void mouseMoved(MouseEvent e) {
mouseCoordinates.setText(String.format("X: %d pixels Y: %d pixels", e.getX(), e.getY()));
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
switch (shapeType) {
case 0://Curved line
if (painting)
return;
prevX = e.getX();
prevY = e.getY();
currentBrushLine = new paintBrushLine(brushSize, brushType, currentColour, prevX, prevY, prevX, prevY);
painting = true;
break;
default://Other shapes
currentShape = new geometricShape(e.getX(), e.getY(), e.getX(), e.getY(), brushSize, currentColour, shapeType, filled);
painting = false;
break;
}
}
public void mouseReleased(MouseEvent e) {
if (shapeType > 0) {
currentShape.setX2(e.getX());
currentShape.setY2(e.getY());
shapes.addFront(currentShape);
currentShape = null;
shapeType = 0;
repaint();
} else {
if (!painting)
return;
((paintBrushLine) currentBrushLine).setX2(e.getX());
((paintBrushLine) currentBrushLine).setY2(e.getY());
brushLines.addFront(currentBrushLine);
currentBrushLine = null;
painting = false;
repaint();
}
}
}
}
LinkedList class:
import java.util.ArrayList;
class LinkedList<T> {
private int numberOfNodes = 0;
private ListNode<T> front = null;
// Returns true if the linked list has no nodes, or false otherwise.
public boolean isEmpty() {
return (front == null);
}
// Deletes all of the nodes in the linked list.
// Note: ListNode objects will be automatically garbage collected by JVM.
public void makeEmpty() {
front = null;
numberOfNodes = 0;
}
// Returns the number of nodes in the linked list
public int size() {
return numberOfNodes;
}
// Adds a node to the front of the linked list.
public void addFront( T element ) {
front = new ListNode<T>( element, front );
numberOfNodes++;
}
// Returns a reference to the data in the first node, or null if the list is empty.
public T peek() {
if (isEmpty())
return null;
return front.getData();
}
// Removes a node from the front of the linked list (if there is one).
// Returns a reference to the data in the first node, or null if the list is empty.
#SuppressWarnings("unchecked")
public T removeFront() {
T tempData;
if (isEmpty())
return null;
tempData = front.getData();
front = front.getNext();
numberOfNodes--;
return tempData;
}
#SuppressWarnings("unchecked")
public void removeEnd(T element) {
ListNode<T> node=front;
while(node.getNext() != null)
{
node = node.getNext();
}
node.setNext(new ListNode<T>((T)element, null));
}
// Return array filled with T objects
#SuppressWarnings("unchecked")
public ArrayList<T> getArray() {
ArrayList<T> shapeArray=new ArrayList<T>();
ListNode<T> node=front;
while (node!=null)
{
shapeArray.add(node.getData());
node = node.getNext();
}
return shapeArray;
}
}
ListNode class:
public class ListNode<T> {
private T data;
private ListNode next;
// Constructor: No reference to next node provided so make it null
public ListNode( T nodeData ) {
this( nodeData, null);
}
// Constructor: Set data and reference to next node.
public ListNode( T nodeData, ListNode nodeNext ) {
data = nodeData;
next = nodeNext;
}
// Accessor: Return the data for current ListNode object
public T getData() {
return data;
}
// Accessor: Return reference to next ListNode object
public ListNode getNext() {
return next;
}
// Mutator: Set new data for current ListNode object
public void setData( T newData ) {
data = newData;
}
// Mutator: Set new reference to the next node object
public void setNext( ListNode newNext ) {
next = newNext;
}
}
Both your shapes and your lines only store a start and end point.
abstract static class Shape {
private int x1, y1, x2, y2;
private int thickness;
private Color shapeColour;
So how does your paint method know what to do? How can it draw a curve when it only ever knows two points?
What you need to do:
Once you have the shape completed you need to do some math to work out the radius and coordinates of each arc based on the coordinates of the previous and next segment, and then in your paint method you can draw lots and lots of small lines so that it appears a nice smooth arc.
Also, add some debugging code to find out what values your paint method is using, you may find that the reason you only see dots or small lines is because the values for each shape/line is not being stored correctly.

Drawing both statically and dynamically in java

I made a paint application. And need your help to solve a problem. As you can see this code draws the shapes again and again when paint event is called. When there is many shapes, the preview rectangle feature becomes slow and doesn't work smoothly. Is there any way to draw shapes only when mouse pressing and releasing? When I tried shapes began to disappear while mouse dragging and appears when mouse Released.
Here is Essential code:
private class drawer extends JComponent{
ArrayList<Shape> shapes = new ArrayList<Shape>();
ArrayList<Color> fillcolo = new ArrayList<Color>();
ArrayList<Color> strokecolo = new ArrayList<Color>();
Point drawst, drawend;
public drawer(){
this.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
drawst = new Point(e.getX(), e.getY());
drawend = drawst;
if(currentaction == 0){
ArrayList<Shape> availables = new ArrayList<Shape>();
for(Shape s : shapes){
if(s.contains(drawst)){
availables.add(s);
}
}
if(!availables.isEmpty()){
int tmpindex = shapes.indexOf(availables.get(availables.size() -1));
shapes.remove(tmpindex);
fillcolo.remove(tmpindex);
strokecolo.remove(tmpindex);
}
}
flowthrough = true;
repaint();
}
public void mouseReleased(MouseEvent e){
switch (currentaction){
case 0:
break;
case 1:
break;
case 4:
Shape shape01 = drawellipse(drawst.x,drawst.y,e.getX(),e.getY());
shapes.add(shape01);
fillcolo.add(fillcol);
strokecolo.add(strokecol);
break;
case 3:
Shape shape = drawrect(drawst.x,drawst.y,e.getX(),e.getY());
shapes.add(shape);
fillcolo.add(fillcol);
strokecolo.add(strokecol);
break;
}
drawst = null; drawend = null;
flowthrough = true;
repaint();
}
});
this.addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
drawend = new Point(e.getX(), e.getY());
repaint();
}
}
);
}
public void paint(Graphics g){
Graphics2D graph = (Graphics2D)g;
graph.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graph.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
graph.setStroke(new BasicStroke(2));
if(flowthrough){
Iterator<Color> strokecounter = strokecolo.iterator();
Iterator<Color> fillcounter = fillcolo.iterator();
for(Shape s : shapes){
graph.setPaint(strokecounter.next());
graph.draw(s);
graph.setPaint(fillcounter.next());
graph.fill(s);
}
}
if(drawst != null && drawend != null){
switch (currentaction){
case 4:
graph.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.40f));
graph.setPaint(Color.LIGHT_GRAY);
Shape bshape = drawellipse(drawst.x, drawst.y, drawend.x, drawend.y);
graph.draw(bshape);
break;
case 3:
graph.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.40f));
graph.setPaint(Color.LIGHT_GRAY);
Shape ashape = drawrect(drawst.x, drawst.y, drawend.x, drawend.y);
graph.draw(ashape);
break;
}
}
}
private Rectangle2D.Float drawrect(int x1, int y1, int x2, int y2){
int x = Math.min(x1, x2);
int y = Math.min(y1, y2);
int width = Math.abs(x1-x2);
int height = Math.abs(y1-y2);
return new Rectangle2D.Float(x,y,width,height);
}
private Ellipse2D.Float drawellipse(int x1, int y1, int x2, int y2){
int x = Math.min(x1, x2);
int y = Math.min(y1, y2);
int width = Math.abs(x1 - x2);
int height = Math.abs(y1 - y2);
return new Ellipse2D.Float(x,y,width,height);
}
}
Here is full code(I minimized it a bit):
public class Basics extends JFrame {
JButton brushbut, shapebut, linebut, strokecolbut, fillcolbut;
int currentaction = 1;
int strokesize = 2;
boolean flowthrough = false;
Color strokecol = Color.black, fillcol = Color.darkGray;
public Basics(){
this.setBounds(new Rectangle(50,50,1000,600));
this.setTitle("Dandle");
JPanel buttonpanel = new JPanel();
Box thebox = Box.createHorizontalBox();
brushbut = makebutton("/home/kamal/Pictures/brushicon(sized).png", 4);
shapebut = makebutton("/home/kamal/Pictures/shapeicon(sized).png", 3);
linebut = makebutton("/home/kamal/Pictures/vector-path-lineicon(sized).png",0);
strokecolbut = makebutton("/home/kamal/Pictures/strokecolor(sized).png", true);
fillcolbut = makebutton("/home/kamal/Pictures/fill-coloricon(sized).png", false);
thebox.add(brushbut);
........
buttonpanel.add(thebox);
this.add(buttonpanel, BorderLayout.SOUTH);
this.add(new drawer(), BorderLayout.CENTER);
}
private JButton makebutton(String icon, final int num){
JButton thebut = new JButton();
........
thebut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
currentaction = num;
}
});
return thebut;
}
private JButton makebutton(String icon, final boolean stroke){
JButton thebut = new JButton();
thebut.setIcon(new ImageIcon(icon));
thebut.setSize(50,50);
thebut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
if(stroke) strokecol = JColorChooser.showDialog(null, "Pick a stroke", strokecol);
..........
}
});
return thebut;
}
public static void main(String[] args){
new Basics().setVisible(true);
}
private class drawer extends JComponent{
ArrayList<Shape> shapes = new ArrayList<Shape>();
ArrayList<Color> fillcolo = new ArrayList<Color>();
ArrayList<Color> strokecolo = new ArrayList<Color>();
Point drawst, drawend;
public drawer(){
this.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
drawst = new Point(e.getX(), e.getY());
drawend = drawst;
if(currentaction == 0){
ArrayList<Shape> availables = new ArrayList<Shape>();
for(Shape s : shapes){
if(s.contains(drawst)){
availables.add(s);
}
}
if(!availables.isEmpty()){
int tmpindex = shapes.indexOf(availables.get(availables.size() -1));
shapes.remove(tmpindex);
fillcolo.remove(tmpindex);
strokecolo.remove(tmpindex);
}
}
flowthrough = true;
repaint();
}
public void mouseReleased(MouseEvent e){
switch (currentaction){
case 0:
break;
case 1:
break;
case 4:
Shape shape01 = drawellipse(drawst.x,drawst.y,e.getX(),e.getY());
shapes.add(shape01);
fillcolo.add(fillcol);
strokecolo.add(strokecol);
break;
case 3:
Shape shape = drawrect(drawst.x,drawst.y,e.getX(),e.getY());
shapes.add(shape);
fillcolo.add(fillcol);
strokecolo.add(strokecol);
break;
}
drawst = null; drawend = null;
flowthrough = true;
repaint();
}
});
this.addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
drawend = new Point(e.getX(), e.getY());
repaint();
}
}
);
}
public void paint(Graphics g){
Graphics2D graph = (Graphics2D)g;
graph.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graph.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
graph.setStroke(new BasicStroke(2));
if(flowthrough){
Iterator<Color> strokecounter = strokecolo.iterator();
Iterator<Color> fillcounter = fillcolo.iterator();
for(Shape s : shapes){
graph.setPaint(strokecounter.next());
graph.draw(s);
graph.setPaint(fillcounter.next());
graph.fill(s);
}
}
if(drawst != null && drawend != null){
switch (currentaction){
case 4:
graph.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.40f));
graph.setPaint(Color.LIGHT_GRAY);
Shape bshape = drawellipse(drawst.x, drawst.y, drawend.x, drawend.y);
graph.draw(bshape);
break;
case 3:
graph.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.40f));
graph.setPaint(Color.LIGHT_GRAY);
Shape ashape = drawrect(drawst.x, drawst.y, drawend.x, drawend.y);
graph.draw(ashape);
break;
}
}
}
private Rectangle2D.Float drawrect(int x1, int y1, int x2, int y2){
..........
return new Rectangle2D.Float(x,y,width,height);
}
private Ellipse2D.Float drawellipse(int x1, int y1, int x2, int y2){
..........
return new Ellipse2D.Float(x,y,width,height);
}
}
}

How to pass Graphics objects between classes and methods to draw lines

I am making a gui program with the mouseListener and mouseMotionListener. I have the following Line class
public class Line {
private int x1, x2, y1, y2;
private Color color;
public Line(int x1, int x2, int y1, int y2, Color color)
{
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
this.color = color;
}
public void draw(Graphics page)
{
page.drawLine(x1, y1, x2, y2);
page.setColor(color);
}
}
here is my mouseReleased where i get the final points of the desired line.
public void mouseReleased (MouseEvent event)
{ // ending points
moving = false;
Point p2 = event.getPoint();
x2 = p2.x;
y2 = p2.y;
line = new Line(x1,x2,y1,y2,currentColor);
lineList.add(line);
canvas.paintComponent(??????????);
Here is the canvas method that should draw all of these lines in the array list "lineList". to the canvas
private class CanvasPanel extends JPanel
{
//this method draws all shapes specified by a user
public void paintComponent(Graphics page)
{
super.paintComponent(page);
setBackground(Color.WHITE);
for(int i = 0; i <lineList.size()-1;i++)
{
line.draw(page);
}
However I do not know how to pass the graphics object to the canvas class in order to actually draw my lines on the JPanel. Assuming i have all other info correct(initial line points, JPanel set correctly, and buttons set up) how do i pass these to actually make it draw the lines to the canvas. Thank you!
No, you don't want to pass a Graphics object anywhere, and in fact you don't paint from within the MouseListener or MouseMotionListener. Instead you change fields from within those classes, call repaint() and then use the field results in your paintComponent method.
In fact in your code, if CanvasPanel has access to the lineList, all you need to do is call repaint() on it after adding a new line into the lineList collection. That's it.
Also, don't set background within paintComponent but rather within the constructor. Also you need to swap your method calls in the Line's draw method. You need to set the color before drawing the line.
e.g.,
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class Drawing extends JPanel {
public static final Color BG = Color.WHITE;
public static final Color LINE_COLOR = Color.RED;
public static final Color CURRENT_LINE_COLOR = Color.LIGHT_GRAY;
public static final int PREF_W = 800;
public static final int PREF_H = PREF_W;
private List<Line> lineList = new ArrayList<>();
private Line currentLine = null;
private CanvasPanel canvasPanel = new CanvasPanel();
public Drawing() {
MyMouse myMouse = new MyMouse();
canvasPanel.addMouseListener(myMouse);
canvasPanel.addMouseMotionListener(myMouse);
setLayout(new BorderLayout());
add(canvasPanel);
}
private class CanvasPanel extends JPanel {
public CanvasPanel() {
setBackground(BG);
}
public void paintComponent(Graphics page) {
super.paintComponent(page);
// setBackground(Color.WHITE); // !! no, not here
for (Line line : lineList) {
line.draw(page);
}
if (currentLine != null) {
currentLine.draw(page);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
}
private class MyMouse extends MouseAdapter {
private int x1;
private int y1;
#Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
x1 = e.getX();
y1 = e.getY();
currentLine = null;
canvasPanel.repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
Line line = createLine(e, LINE_COLOR);
lineList.add(line);
currentLine = null;
canvasPanel.repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
currentLine = createLine(e, CURRENT_LINE_COLOR);
repaint();
}
private Line createLine(MouseEvent e, Color currentColor) {
int x2 = e.getX();
int y2 = e.getY();
return new Line(x1, x2, y1, y2, currentColor);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Drawing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Drawing());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class Line {
private int x1, x2, y1, y2;
private Color color;
public Line(int x1, int x2, int y1, int y2, Color color) {
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
this.color = color;
}
public void draw(Graphics page) {
// swap these calls!
page.setColor(color); //!! This first!
page.drawLine(x1, y1, x2, y2); // **Then** this
// !! page.setColor(color);
}
}

Java - Pulling line animation lags and invisible

I have a problem in my program with the custom drawing part.
I want the user to click on the interface and then drag while the program draw a line which follow the cursor.
But the problem is, I can barely see it. Also, the line won't stay after the cursor's button release.
Custom draw line code:
public void drawTemporaryLine(int x1,int y1,int x2,int y2,ArrayList<Line> lines){
repaint();
g2d = (Graphics2D) getGraphics();
g2d.setStroke(new BasicStroke(3));
g2d.setColor(Color.black);
for(Line l:lines){
g2d.drawLine(l.getX1(),l.getY1(),l.getX2(),l.getY2());
}
g2d.drawLine(x1, y1, x2, y2);
}
Mouse listener code:
#Override
public void mousePressed(MouseEvent e){
if(draw_on){
x = e.getX();
y = e.getY();
}
}
#Override
public void mouseDragged(MouseEvent e){
if(draw_on){
drawPanel.drawTemporaryLine(x, y, e.getX(), e.getY(),lines);
}
}
#Override
public void mouseReleased(MouseEvent e){
if(draw_on){
lines.add(new Line(x,y,e.getX(),e.getY()));
optionButtons[0].setSelected(false);
draw_on = false;
}
}
Is there any way to fix it? Thanks.
Try to override paintComponent.
I tried to reproduce it myself:
Try this :)
DrawPanel (extends JPanel)
private ArrayList<Line> lines = new ArrayList<Line>();
private Line tmpLine = null;
public DrawPanel() {
initComponents();
}
public void drawTemporaryLine(int x1, int y1, int x2, int y2) {
tmpLine = new Line(x1, y1, x2, y2);
}
public void setTemporaryLine(int x1, int y1, int x2, int y2) {
lines.add(new Line(x1, y1, x2, y2));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(3));
g2d.setColor(Color.black);
for (Line l : lines) {
g2d.drawLine(l.getX1(), l.getY1(), l.getX2(), l.getY2());
}
if (tmpLine != null) {
g2d.drawLine(tmpLine.getX1(), tmpLine.getY1(), tmpLine.getX2(), tmpLine.getY2());
}
}
NewJFrame (extends JFrame):
private DrawPanel draw = new DrawPanel();
private int x = 0;
private int y = 0;
public NewJFrame() {
initComponents();
setSize(800,600);
add(draw);
draw.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
draw.setTemporaryLine(x, y, evt.getX(), evt.getY());
draw.repaint();
}
public void mousePressed(java.awt.event.MouseEvent evt) {
x = evt.getX();
y = evt.getY();
}
});
draw.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
draw.drawTemporaryLine(x, y, evt.getX(), evt.getY());
draw.repaint();
}
});
}

Categories