Why can’t I access my panel’s getWidth() and getHeight() functions?

Swing components have no width or height until they’ve been rendered. This occurs if you call pack() or setVisible(true) on a root container. Consider placing your x y int initialization code in the componentResized method of a ComponentListener that is added to your JPanel. e.g., import java.awt.event.*; import java.awt.*; import javax.swing.*; public class TestLinePanel { … Read more

Rotate an image in java by the specified angle

Precedence matters… In your second example, you’re apply a rotation AFTER you’ve drawn everything. This is not how graphics works. You need to apply the transformation first, then everything that follows will use that transformation. public class TestRotateImage { public static void main(String[] args) { new TestRotateImage(); } public TestRotateImage() { EventQueue.invokeLater(new Runnable() { @Override … Read more

How to use AffineTransform.quadrantRotate to rotate a bitmap?

The order of your transformation matters. Basically your example code is saying “rotate the image by 90 degrees AND then translate it….” So, using your code (rotate, then translate) produces… Switching the order (translate then rotate) produces … import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.File; import … Read more

Rotate a buffered image in Java

As always, the Internet to the rescue. So, this is some code which I hobbled together from other resources/post/blogs which will return a new image which is sized so it will contain the rotated image public BufferedImage rotateImageByDegrees(BufferedImage img, double angle) { double rads = Math.toRadians(angle); double sin = Math.abs(Math.sin(rads)), cos = Math.abs(Math.cos(rads)); int w … Read more

Infinite background for game

Have a look through this source which behaves in a more predictable manner, and also includes a nice tweak to the chopper image (animated). 😉 import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.image.BufferedImage; import java.net.URL; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; public class MainFrame { public MainFrame() { JFrame f = new JFrame(“Helicopter Background Test”); … Read more

Rotate a Java Graphics2D Rectangle?

For images you have to use drawImage method of Graphics2D with the relative AffineTransform. For shape you can rotate Graphics2D itself: public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D)g; g2d.setColor(Color.WHITE); Rectangle rect2 = new Rectangle(100, 100, 20, 20); g2d.rotate(Math.toRadians(45)); g2d.draw(rect2); g2d.fill(rect2); } And btw, you should override paintComponent method instead of paint. Citing … Read more