This is a simplified version of a larger project. I have three JPanels contained in a larger JSplitPane called wholePanel
. The top panel and left panel hold labels and buttons, which I have not included here. The lower right panel, called canvasPanel
, is where I draw shapes. I'm trying to tilt an oval at an angle and I am successful at doing so. However, a problem occurs when I resize canvasPanel
. The oval will jump if you drag the Pane dividers to resize. I believe that what is occurring is that the oval is realigning itself sometimes with respect to the upper left corner of wholePanel
and sometimes with respect to the upper left of canvasPanel. So it has an annoying jump. I want it to always align itself with respect to canvasPanel
, not wholePanel
. This seems to happen because of the AffineTransform, but I don't know why or how to fix it.
My second problem is that sometimes canvasPanel
does not paint until I resize it, leaving a dull gray panel with no background color and no shape. I want it to paint without the user having to do anything. Thank you. Code is below.
package ColorForms;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import javax.swing.*;
import java.util.*;
import java.lang.*;
public class ColorForms extends JFrame
{
LeftPanel leftPanel;
TopPanel topPanel;
CanvasPanel canvasPanel;
JSplitPane wholePanel, bottomPanel;
public static void main (String args[])
{
ColorForms cf = new ColorForms ();
}
public ColorForms ()
{
this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
this.setSize (400, 400);
this.setVisible (true);
leftPanel = new LeftPanel ();
topPanel = new TopPanel ();
canvasPanel = new CanvasPanel ();
bottomPanel = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT, leftPanel, canvasPanel);
bottomPanel.setDividerLocation (50);
wholePanel = new JSplitPane (JSplitPane.VERTICAL_SPLIT, topPanel, bottomPanel);
wholePanel.setDividerLocation (70);
this.getContentPane ().add (wholePanel);
}
}
class LeftPanel extends JPanel
{
public LeftPanel ()
{
}
}
class TopPanel extends JPanel
{
public TopPanel ()
{
}
}
class CanvasPanel extends JPanel
{
public CanvasPanel ()
{
}
public void paintComponent (Graphics g)
{
System.out.println ("I am in CanvasPanel repaint.");
int ovalCenterX = 100;
int ovalCenterY = 100;
int ovalWidth = 200;
int ovalHeight = 100;
int ovalUpperLeftX = ovalCenterX - ovalWidth / 2;
int ovalUpperLeftY = ovalCenterY - ovalHeight / 2;
double angle = 0.5;
super.paintComponent (g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
setBackground(Color.GREEN);
AffineTransform orig = g2.getTransform();
AffineTransform af = new AffineTransform ();
af.rotate(angle, ovalCenterX, ovalCenterY);
g2.setTransform(af);
g2.setColor (Color.BLACK);
g2.fillOval (ovalUpperLeftX, ovalUpperLeftY, ovalWidth, ovalHeight);
g2.setTransform(orig);
}
}