How can I animate a drawLine? - java

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Line{
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawLine(150,300,350,300));
frame.setSize(500,500);
frame.setVisible(true);
}
}
class DrawLine extends JPanel{
int x1;
int y1;
int x2;
int y2;
int midx;
int midy;
public DrawLine(int x1, int y1, int x2, int y2){
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
midx = (x1+x2)/2;
midy = (y1+y2)/2;
}
public void animateLine(Graphics g){
g.drawLine(x1,y1,midx,midy);
g.drawLine(x2,y2,midx,midy);
}
public void paintComponent(Graphics g){
final Graphics2D g2d = (Graphics2D)g;
animateLine(g2d);
}
}
So, I have a some pretty basic code here to draw a line from each end towards a middle point. I am trying to make an animation of the middle point's Y value decreasing, so it will make something like an arrow. From what I have gathered I will need to use an action listener and a timer to accomplish this, but I have been unable to figure out exactly how to do it. If someone could please enlighten me on where to place and how to use the timer and repaint() so you can watch the arrow form from the line I would greatly appreciate it. I am trying to use this simple example so I can adapt it into a more complicated animation/drawing.

Update the coordinates in the actionPerformed() method of your javax.swing.Timer and invoke repaint().

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Line{
public static void main(String[] args){
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawLine(150,300,350,300));
frame.setSize(500,500);
frame.setVisible(true);
}
});
}
}
class DrawLine extends JPanel implements ActionListener{
int x1;
int y1;
int x2;
int y2;
int midx;
int midy;
Timer time = new Timer(10, (ActionListener) this);
public DrawLine(int x1, int y1, int x2, int y2){
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
midx = (x1+x2)/2;
midy = (y1+y2)/2;
time.start();
}
public void animateLine(Graphics2D g){
g.drawLine(x1,y1,midx,midy);
g.drawLine(x2,y2,midx,midy);
}
public void actionPerformed(ActionEvent arg0) {
if(midy>123){
midy--;
repaint();
}
}
public void paintComponent(Graphics newG){
super.paintComponent(newG);
Graphics2D g2d = (Graphics2D)newG;
animateLine(g2d);
}
}
I figured it out.

Related

I am not able to draw after clear my jpanel

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.border.BevelBorder;
public class Cliente extends JPanel {
private JButton adelanteButton;
private JButton undoButton;
private JPanel panel1;
private JPanel panelDibujo;
private Rectangulo rectangulo = new Rectangulo();
Originator originator;
Caretaker caretaker;
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Patron Memento");
Cliente cliente = new Cliente();
frame.setContentPane(cliente.panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (Memento m : caretaker.history) {
System.out.println("forcitooooooo");
dibujar(m.getState(), Color.GREEN);
}
}
public Cliente() {
caretaker = new Caretaker();
originator = new Originator();
createUIComponents();
undoButton.addActionListener(e -> {
caretaker.anterior();
panelDibujo.repaint();
});
panelDibujo.setBackground(Color.WHITE);
panelDibujo.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
panelDibujo.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
MousePressedEvent(e);
}
#Override
public void mouseReleased(MouseEvent e) {
MouseReleasedEvent(e);
}
});
}
private void createUIComponents() {
}
private void MousePressedEvent(MouseEvent e){
rectangulo.setX1(e.getX());
rectangulo.setY1(e.getY());
}
private void MouseReleasedEvent(MouseEvent e){
rectangulo.setX2(e.getX());
rectangulo.setY2(e.getY());
originator.setState(rectangulo);
dibujar(rectangulo, Color.orange);
caretaker.addMemento(originator.CreateMemento());
rectangulo = new Rectangulo();
}
public void dibujar(Rectangulo r, Color c) {
Graphics g = panelDibujo.getGraphics();
g.setColor(c);
g.drawRect(r.getX1(), r.getY1(), r.getX2() - r.getX1(), r.getY2() - r.getY1());
g.dispose();
}
}
Hello i am applying the memento pattern by using a jpanel and drawing some rectangles inside, right now my code is working fine about drawing with the mouse events, but the issue is when i try to undo. My logic so far is clear the jpanel and redo all the rectangles minus the last one.
But after clearing my jpanel is not drawing again :( can someone help me to fix it? thank you
Caretaker.java
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Stack;
public class Caretaker {
LinkedList<Memento> history;
int indice;
public Caretaker(){
history = new LinkedList<>();
indice = 0;
}
void addMemento(Memento m){
if (history.size() == indice || history.isEmpty()){
indice++;
history.add(m);
}else {
indice = history.size()-1;
history.subList(indice +1, history.size()).clear();
}
}
Memento anterior(){
if (history.size() > 0){
indice--;
return history.removeLast();
}
JOptionPane.showMessageDialog(null, "No hay mas wey!");
return null;
}
Memento siguiente(){
if (indice < history.size()+1){
indice++;
return history.get(indice+1);
}
JOptionPane.showMessageDialog(null, "No hay mas wey!");
return null;
}
public void redibujar(JPanel f){
Graphics g = f.getGraphics();
for (Memento m: history) {
g.drawRect(m.getState().getX1(), m.getState().getY1(), m.getState().getX2() - m.getState().getX1(), m.getState().getY2() - m.getState().getY1());
g.dispose();
}
}
public void clear(){
history.clear();
indice = 0;
}
}
Memento.java
public class Memento {
Rectangulo state;
/*
Constructor, unica manera de mandar/crear/guardar los datos
*/
public Memento(Rectangulo state) {
this.state = state;
}
public Memento(){
state = new Rectangulo();
}
Rectangulo getState(){
return state;
}
}
Originator.java
public class Originator {
Rectangulo state;
public void setState(Rectangulo rectangulo){
this.state = rectangulo;
}
public Memento CreateMemento(){
return new Memento(state);
}
public void setMemento(Memento m) {
setState(m.getState());
}
}
Rectangulo.java
import java.awt.*;
public class Rectangulo {
private int x1;
private int x2;
private int y1;
private int y2;
Rectangulo(){
}
public Rectangulo(int x1, int x2, int y1, int y2) {
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
}
public int getX1() {
return x1;
}
public void setX1(int x1) {
this.x1 = x1;
}
public int getX2() {
return x2;
}
public void setX2(int x2) {
this.x2 = x2;
}
public int getY1() {
return y1;
}
public void setY1(int y1) {
this.y1 = y1;
}
public int getY2() {
return y2;
}
public void setY2(int y2) {
this.y2 = y2;
}
public void draw(Graphics g){
g.setColor(Color.orange);
g.drawRect(this.getX1(), this.getY1(), this.getX2() - this.getX1(), this.getY2() - this.getY1());
}
}
Again, you're not drawing correctly. You are trying to render using a JPanel, cliente, that is never added to the GUI, and you're trying to use a Graphics object that is extracted from this unrendered component, making the Graphics object thus obtained short-lived and unstable.
Instead, do all drawing in the paintComponent method. You can use a BufferedImage and draw that in paintComponent if desired, especially if you want images with objects that show different colors, or you can use your List (here a LinkedList, but ArrayList will work) and draw in paintComponent. For instance, something simple like:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class Cliente2 extends JPanel {
private static final int BI_WIDTH = 800;
private static final int BI_HEIGHT = 650;
private Rectangle drawingRect = null;
// private java.util.List<Rectangulo> rectangulos = new ArrayList<>();
List<Rectangulo2> rectangulos = new ArrayList<>();
private JButton clearBtn = new JButton("Clear");
public Cliente2() {
setBackground(Color.WHITE);
MyMouse myMouse = new MyMouse();
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
clearBtn.addActionListener(e -> clear());
add(clearBtn);
}
private void clear() {
rectangulos.clear();
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(BI_WIDTH, BI_HEIGHT);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if (drawingRect != null) {
g2.setColor(Color.LIGHT_GRAY);
g2.draw(drawingRect);
}
for (Rectangulo2 rectangulo : rectangulos) {
rectangulo.draw(g2);
}
}
private class MyMouse extends MouseAdapter {
private Point p0;
#Override
public void mousePressed(MouseEvent e) {
p0 = e.getPoint();
}
#Override
public void mouseDragged(MouseEvent e) {
drawingRect = createDrawingRect(e);
repaint();
}
private Rectangle createDrawingRect(MouseEvent e) {
Point p1 = e.getPoint();
int x = Math.min(p0.x, p1.x);
int y = Math.min(p0.y, p1.y);
int width = Math.abs(p0.x - p1.x);
int height = Math.abs(p0.y - p1.y);
return new Rectangle(x, y, width, height);
}
#Override
public void mouseReleased(MouseEvent e) {
// lets create some random colors:
float hue = (float) Math.random();
float brightness = (float) Math.random();
Color color = Color.getHSBColor(hue, 1f, brightness);
Rectangulo2 rectangulo = new Rectangulo2(color, p0, e.getPoint());
rectangulos.add(rectangulo);
drawingRect = null;
repaint();
}
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Patron Memento");
// Cliente cliente = new Cliente();
// frame.setContentPane(cliente.panel1);
frame.add(new Cliente2());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
class Rectangulo2 {
private static final Stroke STROKE = new BasicStroke(3f);
private Color color;
private Point p0, p1;
public Rectangulo2() {
}
public Rectangulo2(Color color, Point p0, Point p1) {
super();
this.color = color;
this.p0 = p0;
this.p1 = p1;
}
public Color getColor() {
return color;
}
public Point getP0() {
return p0;
}
public Point getP1() {
return p1;
}
public void draw(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(color);
int x = Math.min(p0.x, p1.x);
int y = Math.min(p0.y, p1.y);
int width = Math.abs(p0.x - p1.x);
int height = Math.abs(p0.y - p1.y);
g2.fillRect(x, y, width, height);
g2.setStroke(STROKE);
g2.setColor(Color.BLACK);
g2.drawRect(x, y, width, height);
g2.dispose();
}
}

Java Graphics2D moving object stopped in the middle

I'm having a hard time to figure out why this moving rectangle is stopped right in the middle of the Jpanel. The Timer is not stopped, seems there is a boundary in the middle. Anyone could explain it for me please? and how can I make it move the whole way (800)?
here is my code:
public class TestDemo extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private int x;
private int y;
Timer timer;
TestDemo() {
x = 0;
y = 0;
this.setBackground(Color.BLACK);
timer = new Timer(10, this);
timer.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.scale(1, 1);
g2d.setPaint(Color.RED);
g2d.fill(new Rectangle2D.Double(getX(), getY(), 20, 20));
}
public void actionPerformed(ActionEvent e) {
setX(getX() + 1);
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Moving star");
JPanel testDemo = new TestDemo();
testDemo.setSize(800, 200);
frame.add(testDemo);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
The code is overriding methods that already exist and are used for other purposes. That is the main problem.
For custom painting any JComponent, use paintComponent(..) rather than paint(..)
Here is the (working) code with both changes implemented.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class TestDemo extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private int x1;
private int y1;
Timer timer;
TestDemo() {
x1 = 0;
y1 = 0;
this.setBackground(Color.BLACK);
timer = new Timer(10, this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.scale(1, 1);
g2d.setPaint(Color.RED);
g2d.fill(new Rectangle2D.Double(getX1(), getY1(), 20, 20));
}
public void actionPerformed(ActionEvent e) {
setX1(getX1() + 1);
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Moving star");
JPanel testDemo = new TestDemo();
testDemo.setSize(800, 200);
frame.add(testDemo);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public int getX1() {
return x1;
}
public void setX1(int x1) {
this.x1 = x1;
}
public int getY1() {
return y1;
}
public void setY1(int y1) {
this.y1 = y1;
}
}

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);
}
}

Drawing a circle in Java

I want to draw a circle which has the follow properties:
Center is the point where the user first clicks the mouse on the window
Radius should be the length of the distance between when the mouse is first clicked and when it's released (i.e. mouse dragging).
Here's what I have so far but it's not doing what I need it to do:
package assignment;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class DrawCircle extends JFrame implements MouseListener
{
private int centerX;
private int centerY;
private int endPtX;
private int endPtY;
private double radius;
private double w;
private double h;
private CirclePanel circPanel;
/** constructor **/
public DrawCircle()
{
this.setTitle("Click to Draw Circle");
this.setSize(500, 500);
this.setPreferredSize(new Dimension(500, 500));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setResizable(false);
this.addMouseListener(this);
this.circPanel = new CirclePanel();
this.circPanel.setPreferredSize(new Dimension(500, 500));
this.add(this.circPanel);
pack();
}
public void mousePressed(MouseEvent e)
{
centerX = e.getX();
centerY = e.getY();
circPanel.set(centerX, centerY, radius, radius);
repaint();
pack();
}
public void mouseReleased(MouseEvent e)
{
endPtX = e.getX();
endPtY = e.getY();
radius = Math.sqrt(Math.pow(endPtX - centerX, 2) + Math.pow(endPtY - centerY, 2));
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e){}
//circle panel
private class CirclePanel extends JComponent
{
private int x;
private int y;
private int w;
private int h;
public void set(int x, int y, double width, double height)
{
this.x = x;
this.y = y;
w = (int) width;
h = (int) height;
}
public void paintComponent(Graphics g)
{
g.drawOval(x, y, w, h);
}
}
//main method
public static void main (String [] args)
{
new DrawCircle();
}
}
It looks like you are doing the
circPanel.set(centerX, centerY, radius, radius);
repaint();
pack();
in the wrong place you shouldn't draw the circle until the user lets go of the mouse because that's when the radius is set and before that the radius is 0 so there is nothing drawn. Try moving that to the mouseReleased method.

java/Swing issue with paintComponent

The issue I'm having is issue with is I'm trying to get the paintComponent to draw the circle only when the mouse is clicked, dragged, then let go. However inside my paintPanel class I have to initialize the object I've created (ex. movedCircle myCircle = new movedCircle(0,0,0,0);) just creating the object movedCircle myCircle; gives an error until I actually fully initialize the object with a value.
What I'm looking for:
What's considered the best practice for this issue. I don't want to draw anything unnecessary before it is needed.
The way I know how to fix it:
boolean values inside of paintComponent so that way it doesn't draw until somethings actually there.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class drawCircle extends JFrame{
private JPanel myPanel = new paintPanel();
public drawCircle(){
add(myPanel);
}
private class paintPanel extends JPanel{
private int x1, y1, x2, y2;
movedText myText = new movedText(0,0,0,0);
movedCircle myCircle = new movedCircle(0,0,0,0);
public paintPanel(){
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
x1 = e.getX();
y1 = e.getY();
myCircle = new movedCircle(x1, y1, 0, 0);
repaint();
}
public void mouseReleased(MouseEvent e){
x2 = e.getX();
y2 = e.getY();
myCircle = new movedCircle(x1, y1, x2, y2);
repaint();
}
});
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
x2 = e.getX();
y2 = e.getY();
myText = new movedText(x1, y1, x2, y2);
myCircle = new movedCircle(x1, y1, x2, y2);
repaint();
}
public void mouseMoved(MouseEvent e){
x1 = e.getX();
y1 = e.getY();
x2 = 0;
y2 = 0;
myText = new movedText(x1, y1, x2, y2);
repaint();
}
});
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
//draw oval after mouse released
myText.paintText(g);
myCircle.paintCircle(g);
}
}
class movedCircle{
private int x1, y1, x2, y2;
public movedCircle(int x1, int y1, int x2, int y2){
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public void paintCircle(Graphics g){
g.drawOval(x1, y1, x2 - x1, y2 - y1);
}
}
class movedText{
private int x1, y1, x2, y2;
public movedText(int x1, int y1, int x2, int y2){
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public void paintText(Graphics g){
g.drawString("x1: "+x1+" y1: "+y1+" x2: "+x2+" y2: "+y2, x1, y1);
}
}
class RedSquare{
private int xPos = 50;
private int yPos = 50;
private int width = 20;
private int height = 20;
public void setX(int xPos){
this.xPos = xPos;
}
public int getX(){
return xPos;
}
public void setY(int yPos){
this.yPos = yPos;
}
public int getY(){
return yPos;
}
public int getWidth(){
return width;
}
public int getHeight(){
return height;
}
public void paintSquare(Graphics g){
g.setColor(Color.RED);
g.fillRect(xPos,yPos,width,height);
g.setColor(Color.BLACK);
g.drawRect(xPos,yPos,width,height);
}
}
public static void main(String[] args){
JFrame frame = new drawCircle();
frame.setTitle("Is in ellipse? Demo");
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
I would go with the ifs, but the question is where.
you can add them to paintPanel.paintComponent()
you can add them to movedCircle.paint() and do not draw anything if its coordinates are dummy (for instance <0). The same with movedText
Alternatively, position your figures at sensible start place.
(There is one more solution: to subclass movedCircle with nullMovedCircle that doesn't draw anything and create that at first in your paintPanel. However, creating new class for such a little alteration of behaviour seems overkill for me.)
Not sure if I missed the point, but if you don't want to draw something until it is initialized then don't! Can you not just check if it has been created yet rather than creating a new instance that is not in a usable state after the constructor completes? e.g.
super.paintComponent(g);
myText.paintText(g);
if (myCircle != null) {
myCircle.paintCircle(g);
}

Categories