I've drawn an image and some strings on this jpanel, and when the JSplit pane's divider is pulled to the right, it moves the image painted at 0,0 but not the strings! As a result, the strings are drawn in the wrong place on the image! Why does it do this?
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.image.*;
import java.io.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.border.*;
public class TestResize extends JPanel
{
public void paintComponent(Graphics g)
{
Graphics2D graphics = ( Graphics2D ) g;
//Location
int x = 35;
int y = 35;
//Draw background image
BufferedImage image = null;
try
{
image = ImageIO.read( new File( "someimage.jpg" ).toURI().toURL() );
}
catch (Exception e)
{
e.printStackTrace();
}
g.drawImage( image, 0, 0, 340, 340, getBackground(), null );
//I have to rotate it (so that's why I'm including it in this SSCCE)
double theta = Math.toRadians( 15 );
AffineTransform transform = AffineTransform.getRotateInstance( theta, ( double ) x, ( double ) y );
//Set the transform
graphics.setTransform( transform );
//Draw normally
graphics.drawString( "Some string", x, y );
//Now adjust the transform to scale it
transform.scale( 2.464788732394366, 2.464788732394366 );
graphics.setTransform( transform );
graphics.drawString( "Some string", x, y );
}
private static void setExactSize(JComponent component, int width, int height)
{
//The size dimensions
Dimension dim = new Dimension( width, height );
//Set size max, min, etc as the same
component.setPreferredSize( dim );
component.setMaximumSize( dim );
component.setMinimumSize( dim );
component.setSize( width, height );
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Display image");
TestResize panel = new TestResize();
setExactSize( panel, 340, 340 );
JSplitPane pane = new JSplitPane();
JPanel leftSide = new JPanel( true );
Insets margins = new Insets( 5, 5, 5, 5 );
leftSide.setLayout( new BoxLayout( leftSide, BoxLayout.Y_AXIS ) );
leftSide.setBorder( new EmptyBorder( margins ) );
leftSide.add( panel );
pane.setLeftComponent( leftSide );
pane.setDividerLocation( 350 );
frame.getContentPane().add(pane);
frame.setSize( 704, 560);
frame.setVisible( true );
}
}