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);
}
Related
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.
I'm trying to rotate one whole Ellipse2D object based on user key input. If the user presses the right key, rotate right and left key means rotate left. The rotAngle is set to 25. I made a separate drawRotEllipse because otherwise it would have always drawn the original one. I think my confusion is happening with the Graphics and Shapes Objects. Tried the AffineTransform business but that didn't work out either. I just want it to rotate about the center. Thanks for any help!
class Canvas extends JPanel implements java.io.Serializable{
int x1 = (int) (this.getWidth()/2)+100;
int y1 = (int) (this.getHeight()/2)+20;
int x2 = (int) this.getWidth()+100;
int y2 = (int) this.getHeight()+200;
#Override
public void paintComponent(Graphics g){
g.setColor(Color.WHITE);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.RED);
drawEllipse(g);
}
public void drawEllipse (Graphics g){
Graphics2D g2d = (Graphics2D) g;
myShape = new Ellipse2D.Double(x1,y1,x2,y2);
g2d.draw(myShape);
this.repaint();
}
public void drawRotEllipse (Graphics g){
g2d.draw(myShape);
this.repaint();
}
}
private void jPanel1KeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode()==39){
g2d.rotate(Math.toDegrees(rotAngle));
myCanvas.drawRotEllipse(g2d);
}
else if (evt.getKeyCode()==37){
g2d.rotate(Math.toDegrees(-rotAngle));
myCanvas.drawRotEllipse(g2d);
}
}
if (evt.getKeyCode()==39)
Don't use magic numbers. People don't know that means by just looking at the code.
Instead use variable provided by the API:
if (evt.getKeyCode() == KeyEvent.VK_RIGHT)
You KeyEvent code should not do the actual painting. All the code should do is set the "degrees" property of your class. The setDegrees(...) method will then be responsible for invoking repaint(). Now whenever the component is repainted the shape will be painted at its current degrees of rotation.
Here is an example that uses a JSlider to change the rotation degrees of the class.
It rotates an image. You should be able to change the code rotation the image to just draw your shape:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.*;
public class Rotation2 extends JPanel
{
BufferedImage image;
int degrees;
int point = 250;
public Rotation2(BufferedImage image)
{
this.image = image;
setDegrees( 0 );
setPreferredSize( new Dimension(600, 600) );
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g.create();
double radians = Math.toRadians( degrees );
g2.translate(point, point);
g2.rotate(radians);
g2.translate(-image.getWidth(this) / 2, -image.getHeight(this) / 2);
g2.drawImage(image, 0, 0, null);
g2.dispose();
g.setColor(Color.RED);
g.fillOval(point - 5, point - 5, 10, 10);
}
public void setDegrees(int degrees)
{
this.degrees = degrees;
repaint();
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
// String path = "mong.jpg";
String path = "dukewavered.gif";
ClassLoader cl = Rotation2.class.getClassLoader();
BufferedImage bi = ImageIO.read(cl.getResourceAsStream(path));
final Rotation2 r = new Rotation2(bi);
final JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 360, 0);
slider.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
int value = slider.getValue();
r.setDegrees( value );
}
});
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(r));
f.add(slider, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
catch(IOException e)
{
System.out.println(e);
}
}
});
}
}
Here's the class in which I try to draw the lines
package gps;
import java.awt.*;
import java.awt.geom.Line2D;
import java.util.*;
import javax.swing.*;
public class RoadMap extends JPanel {
public void paintComponent(Graphics2D g)
{
super.paintComponent(g);
g.setColor(Color.blue);
for(int i = 0; i < Graph.getEdges().length; i++)
{
Shape s = new Line2D.Double(Graph.vMap.get(Graph.getEdges()[i].i1).x,
Graph.vMap.get(Graph.getEdges()[i].i1).y,
Graph.vMap.get(Graph.getEdges()[i].i2).x,
Graph.vMap.get(Graph.getEdges()[i].i2).y);
g.draw(s);
}
}
}
The Graph.vMap.get(Graph.getEdges()[i].i2).x and Graph.vMap.get(Graph.getEdges()[i].i2).y access the x and y values for the endpoints of the lines and I've tested it and it returned the correct values. However, nothing shows up in my JFrame with this. Trying to draw other lines with set values outside of the for loop actually worked.
x1 = 43.12929, x2 = 43.12976, y1 = -77.626956, y2 = -77.62679
These y values are outside the panel. AWT/Swing component visible coordinate space runs from (0, 0) to (width-1, height-1).
Check where you are computing the values. If you want (0, 0) to be the center, you need to do some arithmetic or a translation via e.g. Graphics2D#translate(int, int).
Furthermore:
public void paintComponent(Graphics2D g)
If you are trying to override paintComponent, you have not done so. paintComponent takes a Graphics, not a Graphics2D:
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Always use the #Override annotation when you attempt to override, because it will cause an error and tell you if it's not an override. See https://docs.oracle.com/javase/tutorial/java/IandI/override.html.
Possibly you mean to use something like this:
public class RoadMap extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.translate(getWidth() / 2, getHeight() / 2);
g2.setColor(Color.blue);
for(int i = 0; i < Graph.getEdges().length; i++) {
Shape s = new Line2D.Double(
Graph.vMap.get(Graph.getEdges()[i].i1).x,
Graph.vMap.get(Graph.getEdges()[i].i1).y,
Graph.vMap.get(Graph.getEdges()[i].i2).x,
Graph.vMap.get(Graph.getEdges()[i].i2).y);
g2.draw(s);
}
g2.dispose();
}
}
I am having some trouble while using swing to draw a diamond inside a square.
My code is this,please some one have a look at it and let me know if you can provide a fullfunctional code which is working in creating a diamond inside a square.
The code is:-
import javax.swing.*;
import java.awt.*;
public class MyDrawing extends JPanel
{
static int width=250;
static int height=250;
static int x=0;
static int y=0;
private void doDrawing(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.blue);
//for (int i = 0; i <= 1000; i++)
g2d.drawRect(x, y, width,height);
g2d.rotate(Math.toRadians(-45));
System.out.println(Math.toRadians(-45));
x=0;
y=height/2;
System.out.println(y);
width=(int)Math.pow(Math.pow((width/2),2)*2,0.5);
height=width;
System.out.println("width:"+width+"height:"+height);
g2d.drawRect(y, x, width,height);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
}
To keep the the diamond inside the sqaure, simply
1. Draw a rectangle
2. Rotate the rectangle about its center.
Rectangle2D rectangle = new Rectangle2D.Double(20, 20, 50, 50);
g2.draw(rectangle);
AffineTransform transform = new AffineTransform();
transform.rotate(Math.PI/4, rectangle.getX() + rectangle.width/2, rectangle.getY() + rectangle.height/2);
g2.draw(transform);
I have this simple application in which a command like RECT 10 20 100 150 draws a rectangle with specified arguments on a DrawPanel(extends JPanel).
Also, after drawing the primitive, it adds it to List<String> cmdList;, so that in
paintComponent(Graphics g) of DrawPanel I iterate through the list, process each command, and draw each of them.
The problem I am facing is that after drawing few shapes, and resizing (or maximizing) the panel becomes empty. And on resizing again several times, all the shpaes get drawn correctly.
This is the screenshot after drawing few primitives.
After stretching window slightly to left, the primitives are gone.
The code for DrawPanel
public class DrawPanel extends JPanel {
private List<String> cmdList;
public final Map<String,Shape> shapes;
public DrawPanel()
{
shapes = new HashMap<String,Shape>();
shapes.put("CIRC", new Circ());
shapes.put("circ", new Circ());
shapes.put("RECT", new Rect());
shapes.put("rect", new Rect());
shapes.put("LINE", new Line());
//... and so on
cmdList = new ArrayList<String>();
}
public void addCmd(String s)
{
cmdList.add(s);
}
public void removeCmd()
{
cmdList.remove(cmdList.size());
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
setBackground(Color.BLACK);
for (int i = 0; i < cmdList.size(); ++i){
StringTokenizer cmdToken = new StringTokenizer(cmdList.get(i));
String cmdShape = cmdToken.nextToken();
int []args = new int[cmdToken.countTokens()];
for(int i1 = 0; cmdToken.hasMoreTokens(); i1++){
args[i1] = Integer.valueOf(cmdToken.nextToken());
}
shapes.get(cmdShape).draw(this, args);
}
}
public void getAndDraw(String cmdShape, int[] args)
{
shapes.get(cmdShape).draw(this, args);
}
public void rect(int x1, int y1, int width, int height)
{
Graphics g = getGraphics();
g.setColor(Color.BLUE);
g.drawRect(x1, y1, width, height);
}
public void circ(int cx, int cy, int radius)
{
Graphics g = getGraphics();
g.setColor(Color.CYAN);
g.drawOval(cx - radius, cy - radius, radius*2, radius*2);
}
}
The partial code for Shape (Interface)
public interface Shape {
void draw(DrawPanel dp, int[] data);
}
class Rect implements Shape {
public void draw(DrawPanel dp, int[] data) {
dp.rect(data[0], data[1], data[2], data[3]);
}
}
Lines used in MainFrame (extends JFrame) to draw after each command is entered.
drawPanel.getAndDraw(cmdShape, args);
drawPanel.addCmd(cmd);
Why is Drawing panel, sometimes painting and other time not, on window resize?
How can I get stable output?
Note : If I have missed anything, please ask.
It's because your using getGraphics() when you should be using the Graphics object passed as an argument to paintComponent.
Oh, and btw, setBackground(Color.BLACK) should be in the constructor, not in the paintComponent method.