How can I rotate rectangle in Java? - java

My rectangle code:
class Rectangle extends JPanel {
int x = 105;
int y= 100;
int width = 50;
int height = 100;
public void paint(Graphics g) {
g.drawRect (x, y, width, height);
g.setColor(Color.WHITE);
}
Rectangle r = new Rectangle();
and I have a button "rotate". When the user presses the button with the mouse, the rectangle must rotate 15 degrees.
This is my action code:
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
if( source == rotate){
AffineTransform transform = new AffineTransform();
transform.rotate(Math.toRadians(15), r.getX() + r.getWidth()/2, r.getY() + height/2);
r.add(transform);
}
}
But the code doesn't work. I don't know why? What do you think?
My edited-action-code part:
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
if( source == rotate){
Paint p = new Paint();
panel1.add(r);
repaint();
}
}
class Paint extends JPanel {
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.WHITE);
g2d.translate(r.getX()+(r.WIDTH/2), r.getY()+(r.HEIGHT/2));
g2d.rotate(Math.toRadians(15));
r.equals(g2d);
repaint();
}
}

Custom painting is done by overriding the paintComponent() method, not paint(). Don't forget the super.paintComponent() at the start.
The paintComponent() method is where the painting is done so that is were you need the rotation code. So you could set a variable to indicate if you need to do the rotation or not. So all the ActionListener does is set the variable and then invoke repaint().
Or, I've never tried applying a rotation directly to the Rectangle (I've always applied it to the Graphics object in the painting method). Maybe you just need to invoke repaint() on the panel in your ActionListener. The panel won't know you've changed the Rectangle, so you need to tell it to repaint itself.

Related

How to prevent shapes in a JFrame from disappearing after resizing the window

public void actionPerformed(ActionEvent e)
{
try
{
//récupérer les coordonnées(x,y) du text area
int x=Integer.parseInt(f.x.getText());
int y=Integer.parseInt(f.y.getText());
int puissance=Integer.parseInt(f.p.getText());
f.APs.add(new AccessPoint (x,y,f.APs.size(),puissance));
String ch="Point d'accés "+String.valueOf(f.APs.size())+" Center xc = "+String.valueOf(x)+" yc= "+String.valueOf(x);
System.out.println(ch);
f.t.add(ch);
Graphics g ;
g= f.getGraphics();
paintComponent(g);
}
catch(Exception e1){System.out.println("Erreur");}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
if(f.APs.size()!=0)
{
try {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
int currPoint =f.APs.size()-1;
int puissance =f.APs.get(currPoint).p;
Color C= new Color(128,puissance,puissance,puissance);
Shape circle = new Ellipse2D.Float(f.APs.get(currPoint).x-(f.APs.get(currPoint).diametre/2),
f.APs.get(currPoint).y-(f.APs.get(currPoint).diametre/2),
f.APs.get(currPoint).diametre,f.APs.get(currPoint).diametre);
g2d.draw(circle);
g2d.setPaint(C);
g2d.fill(circle);
}catch(Exception e2){System.out.println("Erreur");}}
}
g= f.getGraphics();
paintComponent(g);
Don't use getGraphics(). Any painting done using that approach will only be temporary (as you have noticed)
Don't invoke paintComponent() directly. Swing will invoke the paintComponent(...) method as required and pass in the proper Graphics object.
The painting method should only ever do painting. It should not change the state of the component.
So if you want to dynamically add shapes to be painted you have two approaches:
Keep an ArrayList of the shapes to be painted. Create a method like addShape(..) to update the ArrayLIst. Then your painting code will iterate through the ArrayList to paint each shape.
Paint directlyl to a BufferedImage. Then paint the BufferedImage.
Working example of both approaches can be found in Custom Painting Approaches

How to paint components in layers in Java?

I have big problem with coding graphic part of my app, where I need to have components one on top of each other:
First I have JFrame (with fixed size)
In it I have two JPanel components. I want them to have colour background.
That's the easy part.
On one of the JPanel components I want to draw fixed shapres - rectangles, lanes, etc. Here I have problem, that I have two classes: one extends JPanel and is background for this part and second extends JComponent and represents element I draw (there is several elements). I don't know how to draw the elements in the JPanel - I tried several methods and nothing showed up. It's important to me that the JComponents should be drawn and conected only with this JPanel, not with whole frame.
On top of that I want to have moving shapes. It's easy when I have only frame and let's say rectangle, because I only change position and call repaint() method, but how to do this to make the moving shapes be connected to and be inside JPanel and to left previous layers in their place?
For my tries I created few classes with rectangles:
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
public class Main{
public Main() {
JFrame frame = new JFrame();
frame.setSize(1200, 900);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
JPanel background = new JPanel();
background.setBackground(Color.lightGray);
GreenRect gr = new GreenRect();
gr.setPreferredSize(new Dimension(500,800));
background.add(gr, BorderLayout.WEST);
RedRect rr = new RedRect();
rr.setPreferredSize(new Dimension(500,800));
background.add(rr, BorderLayout.EAST);
frame.add(background);
}
public static void main(String[] args) {
new Main();
}
}
class GreenRect extends JPanel {
ArrayList<BlackRect> r = new ArrayList<>();
ArrayList<MovingRec> m = new ArrayList<>();
public GreenRect() {
setBackground(Color.green);
addRec(10,10);
addRec(50,50);
addRec(100,100);
addRec(1000,1000);
}
public void addRec(int x, int y) {
r.add(new BlackRect(x,y));
}
}
class RedRect extends JPanel {
public RedRect() {
setBackground(Color.red);
}
}
class BlackRect extends JComponent {
int x, y;
int w = 100, h = 100;
public BlackRect (int x, int y){
this.x = x;
this.y = y;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.fillRect(x, y, w, h);
}
}
class MovingRec extends JComponent {
int x, y;
int w = 20, h = 20;
public MovingRec (int x, int y){
this.x = x;
this.y = y;
}
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLUE);
g2d.fillRect(x, y, w, h);
}
public void update() {
x += 5;
y += 5;
}
}
and now I have problems with points 3 and 4, because I can't place black rectangles on background and moving rectangles on the top.
I will be grateful for all help :)
You do not need to (and shouldn’t) extend BlackRect and MovingRect from JComponent.
For example, BlackRect could be a simple object, like:
class BlackRect {
int x, y;
int w = 100, h = 100;
public BlackRect(int x, int y) {
this.x = x;
this.y = y;
}
public void paint(Graphics2D g2d) {
g2d.setColor(Color.BLACK);
g2d.fillRect(x, y, w, h);
}
}
You should override GreenRect’s paint method, to paint rectangles on that panel:
public GreenRect extends JPanel {
// Existing members
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (BlackRect black_rect : r) {
black_rect.paint(g2d);
}
// Also paint list of moving rectangles here
}
}
When GreenRect.repaint() is called, it will paint its background, and all rectangles from the r (and m list when you add that code). If the m rectangles have had their positions updated, they will be drawn at their new positions, so they will appear to be moving. Since moving rectangles are drawn last, they would appear “on top”.
Use a Swing Timer to drive the animation. When the timer expires, it should move all of the moving rectangles slightly (ie, call MovingRec.update()), and call repaint() on GreenRect.

Repaint Java - I've read many questions, but still not working

Like in a topic, I've readed the most of all solutions for repaint() but for my code their are not working. I'm a begginer so forgive me a mess in my code..
class View.java
public class View extends JFrame{
public void make(){
setSize(640,480);
setVisible(true);
setTitle("Parking");
}
double x_ = MyFrame.x;
double y_ = MyFrame.y;
double odchylenie_ = MyFrame.odchylenie;
int szerokosc = 50;
int wysokosc = 30;
public void paint(Graphics g){
Rectangle2D rect = new Rectangle2D.Double(-szerokosc / 2., -wysokosc / 2., szerokosc, wysokosc);
AffineTransform transform = new AffineTransform();
transform.translate(x_, y_);
transform.rotate(Math.toRadians(odchylenie_));
Shape rotatedRect = transform.createTransformedShape(rect);
Graphics2D g2 = (Graphics2D)g;
g2.draw(rotatedRect);
}
All I want to do to re-paint this rotatedRect with new values of x,y and odchylenie (sorry for polish variable names).
I'm calculating new variable values and using Jbutton to redraw it.
Here is my MyFrame.class
public class MyFrame extends javax.swing.JFrame {
static double x,y,odchylenie,kat;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
View v = new View();
v.make();
Fuzzy f = new Fuzzy();
kat = f.wyjscie(x, odchylenie);
jLabel5.setText("Kąt: " + Double.toString(kat));
odchylenie = Fuzzy.wyliczOdchylenie(odchylenie,kat);
jLabel8.setText("Nowe odchylenie: " + Double.toString(odchylenie));
x = Fuzzy.wyliczX(x, 10, kat,odchylenie);
jLabel6.setText("Nowy x: " + Double.toString(x));
y = Fuzzy.wyliczY(y,x, 10, kat,odchylenie);
jLabel7.setText("Nowy y: " + Double.toString(y));
v.repaint(); //Not works
}
Instead of doing repaint(), the new window appears, and old one stays...
I have tried to declare View v outside the button function body, but it not worked too(nothing is painting).
Whenever you override one of the paint() methods, you need to make a call to the super's method:
public void paint(Graphics g) {
super.paint(g);
// your code goes here
}
Further, you should really be using paintComponent(), not paint().
public void paintComponent(Graphics g) {
super.paintComponent(g);
// your code goes here
}
Instead of using paint, use paintComponent:
public void paintComponent(Graphics g){
super.paintComponent(g);
Rectangle2D rect = new Rectangle2D.Double(-szerokosc / 2., -wysokosc / 2., szerokosc, wysokosc);
AffineTransform transform = new AffineTransform();
transform.translate(x_, y_);
transform.rotate(Math.toRadians(odchylenie_));
Shape rotatedRect = transform.createTransformedShape(rect);
Graphics2D g2 = (Graphics2D)g;
g2.draw(rotatedRect);
}

how to use method of one class in another class

here is first class
// extending class from JPanel
public class MyPanel extends JPanel {
// variables used to draw oval at different locations
int mX = 200;
int mY = 0;
// overriding paintComponent method
public void paintComponent(Graphics g) {
// erasing behaviour – this will clear all the
// previous painting
super.paintComponent(g);
// Down casting Graphics object to Graphics2D
Graphics2D g2 = (Graphics2D) g;
// changing the color to blue
g2.setColor(Color.blue);
// drawing filled oval with blue color
// using instance variables
g2.fillOval(mX, mY, 40, 40);
now i want to use the method g2.setColot(Colot.blue) in the following where the question marks are.
// event handler method
public void actionPerformed(ActionEvent ae) {
// if ball reached to maximum width of frame minus 40 since diameter of ball is 40 then change the X-direction of ball
if (f.getWidth() - 40 == p.mX) {
x = -5;
????? set the color as red ????????
}
Add a Color member to your class. When you want to change the color, change to value of the member and call repaint():
public class MyPanel extends JPanel {
int mX = 200;
int mY = 0;
Color myColor = Color.blue; //Default color is blue,
//but make it whatever you want
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(myColor);
g2.fillOval(mX, mY, 40, 40);
}
public void actionPerformed(ActionEvent ae) {
if (f.getWidth() - 40 == p.mX) {
x = -5;
myColor = Color.red;
repaint();
}
}
If I understand what you need is to make Graphics2D g2 a class attribute. This way all the methods in your class can access that "global" variable:
public class MyPanel extends JPanel {
Graphics2D g2;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g2 = (Graphics2D) g;
...
}
public void actionPerformed(ActionEvent ae) {
g2.setColor(...);
}
}

java.awt.Graphics change color after drawing

I have asked a similar question a while ago here, but didn't get an answer. The original question was about changing the color of a shape after clicking on it. But I am puzzled on how to access the shape at all after it is drawn.
This is my paintComponent method
#Override
protected void paintComponent(Graphics graph) {
super.paintComponent(graph);
Graphics2D g = (Graphics2D) graph;
// smooth graphics
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// moving to the middle of the panel
g.translate(this.getWidth()/2, this.getHeight()/2);
// painting colored arcs
for(int i = 0; i < 4; i++) {
g.setColor(dimColors[i]);
g.fill(arcs[i]);
}
// painting borders
g.setColor(Color.BLACK);
g.setStroke(new BasicStroke(5F));
g.drawLine(-98, 0, 98, 0);
g.drawLine(0, -98, 0, 98);
g.draw(circle);
// painting central white circle
g.setColor(Color.WHITE);
g.fill(smallCircle);
g.setColor(Color.BLACK);
g.draw(smallCircle);
}
the arcs[] array contains a bunch of Arc2D's that are drawn on the panel. My question is now, if I want to change the color of, for example arcs[0], how do I do that?
Thanks!
EDIT: I now have this MouseAdapter event
private class MyMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
Component c = getComponentAt(p);
Graphics g = c.getGraphics();
dimColors[1] = Color.RED;
paintComponent(g);
}
}
And it works, it changes the color of arc[1] because arcs[1] has dimColors[1] set as color when drawing it.
However, I still can't figure out how to check wether the right arc was clicked. Right now you just click anywhere on the graphics panel and it changes the color of that specific arc
This doesn't answer your earlier question, however it does answer your question of click detection. To do this it is best to use Graphics2D because it is a lot easier to write than most other options. Here is an example:
public class GraphicsPanel extends JPanel implements MouseListener
{
private Rectangle2D rect;
First we create our Graphics2D rectangle rect.
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)(g);
g2d.setColor(Color.GREEN);
rect = new Rectangle2D.Double(70, 70, 100, 100);
g2d.fill(rect);
this.addMouseListener(this);
}
And then we override the paintComponent method and create our new Rectangle2D.Double object.
We then fill the rectangle with g2d.fill() and then add a mouse listener to the JPanel.
public void mousePressed(MouseEvent e)
{
if(rect.contains(e.getX(), e.getY()))
System.out.println("Rectangle clicked");
}
}
Finally, we need to see if that rectangle contains the point where the user clicked. To do this, simply see if the rectangle we created contains the user's click location by using the Rectangle2D.double's contains(int x, int y) method. That's it!
if I want to change the color of, for example arcs[0], how do I do that?
A line (or whatever) only exists as a bunch of pixels that were painted in the original color. To change its color you must change the current color and draw it again.

Categories

Resources