im trying to code a GUI for "Towers of Hanoi" with a Java JFrame. I thought I can just make a array with all rectangles (I use rectangles to display the elements, that the player can move) and then use something like this "recList[1].move()"to move the rectangle on the canvas, but I don't finde a funktion, that can do this. It would be grade, if somebody could say me how i can move a rectangle to specific coordinates.
Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
public class GUIBuilder extends JFrame {
//object classes
public static class Rectangle {
Rectangle2D.Double Rectangle;
public Rectangle(double x, double y, double w, double h) {
Rectangle = new Rectangle2D.Double(x, y, w, h);
}
public void draw(Graphics2D g) {
g.draw(Rectangle);
}
}
public static class Stick {
Line2D.Double stick;
public Stick(double x1, double y1, double x2, double y2) {
this.stick = new Line2D.Double(x1, y1, x2, y2);
}
public void draw(Graphics2D g) {
g.draw(stick);
}
}
//draw
static class DrawPane extends JPanel {
public void paintComponent(Graphics g) {
double s = 3; // s = amount of sticks
double n = 5; // n = amount of elements
//base
Rectangle rectangle = new Rectangle(300, 700, (int) s * 100 + 100, 50);
rectangle.draw((Graphics2D)g.create());
//s sticks
for (int i=0; i<s; i++) {
Stick stick = new Stick(400 + 100 * i, 700 - (25 * (n + 1)), 400 + 100 * i, 700);
stick.draw((Graphics2D)g.create());
}
//n elements
Rectangle[] recList = new Rectangle[(int)n]; //declaration a list for the rectangles
for (int i=0;i<n;i++) {
double w = 90/n*(n-i);
double x = 355+90/n/2*i;
double y = 675-25*i;
double h = 25;
recList[i] = new Rectangle(x, y, w, h);
recList[i].draw((Graphics2D)g.create());
}
}
}
//guibuilder
public GUIBuilder() {
JFrame frame = new JFrame("Towers of Hanoi by ByPander");
frame.setContentPane(new DrawPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setVisible(true);
}
//calling the guibuilder
public static void main(String[] args){
//start the Guibuilder
new GUIBuilder();
}
}