I have an animation, and would like to make it disappear progressively when it reaches the left side of the display area.
AffineTransform at = new AffineTransform();
at.scale(-1, 1);
at.translate((-clip.x + (clip.x - xPositionToPixel(imgX))), clip.y - 1);
if ((clip.x - clip.width) < (at.getTranslateX() - bufImg.getWidth())) {
g2d.drawImage(bufImg, at, null);
} else {
at = new AffineTransform();
at.scale(-1, 1);
at.translate((-clip.x + (clip.x - xPositionToPixel(imgX))), clip.y - 1);
g2d.drawImage(bufImg, (int)at.getTranslateX(), clip.y - 1, (int)(bufImg.getWidth() - (xPositionToPixel(imgX) + bufImg.getWidth())), clip.height, null);
}
I'm drawing the animation from right to left, that is the reason why i scale and translate each the coordinate. clip.x is the start of the display area, and imgX is the new x coordinate.
Thanks for your help.
I tried several way of achieving what i want and the closest is this :
AffineTransform at = new AffineTransform();
at.scale(-1, 1);
at.translate((-clip.x + (clip.x - xPositionToPixel(imgX))), clip.y - 1);
if ((clip.x - clip.width) < (at.getTranslateX() - bufImg.getWidth())) {
g2d.drawImage(bufImg, at, null);
} else {
at = new AffineTransform();
at.scale(-1, 1);
at.translate((-clip.x + (clip.x - xPositionToPixel(imgX))), clip.y - 1);
g2d.drawImage(bufImg, (int)at.getTranslateX(), clip.y - 1, (int)(bufImg.getWidth() - (xPositionToPixel(imgX) + bufImg.getWidth())), clip.height, null);
}
But still not a good soluation has i'm just shrinking the width of my image, but still draw it entirely.
Still don't know what exactly the problem is (animation or transform?), here's a simple snippet to play with:
final JButton button = new JButton("Swinging!");
button.setSize(button.getPreferredSize());
button.doLayout();
final BufferedImage image = new BufferedImage(
button.getWidth(), button.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
button.paint(g);
g.dispose();
final Point location = new Point(500, 100);
final JPanel panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D gd = (Graphics2D) g.create();
gd.translate(location.x, location.y);
gd.scale(-1, 1);
gd.drawImage(image, 0, 0, this);
gd.dispose();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(button.getWidth()* 10, button.getHeight() * 20);
}
};
ActionListener l = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
location.x -= 5;
panel.repaint();
if (location.x < - button.getWidth()) {
((Timer) e.getSource()).stop();
}
}
};
new Timer(100, l).start();
Related
I've created this custom JToolTip for my application. When the tooltip is entirely diplayed inside a JFrame, no background is visible (expected), but when the tooltip is displayed outside the JFrame, the background will be visible. How can I have it removed either way?
I've tried setBackground(new Color(255, 255, 255, 0)); with the '0' alpha value to make sure the background is transparent, but that didn't do the trick.
The tooltip inside the frame, as expected:
The tooltip exceeding the JFrame, with the unwanted background:
The custom JTooltip:
public class DefaultToolTip extends JToolTip {
public DefaultToolTip() {
setOpaque(false);
setPreferredSize(new Dimension(275, 30));
setBackground(new Color(255, 255, 255, 0));
}
#Override
public void addNotify() {
super.addNotify();
setOpaque(false);
Component parent = this.getParent();
if (parent != null) {
if (parent instanceof JComponent) {
JComponent jparent = (JComponent) parent;
jparent.setOpaque(false);
}
}
}
#Override
public void paint(Graphics g) {
String text = getComponent().getToolTipText();
addNotify();
Graphics2D g2d = drawComponent(g);
drawText(text, g2d);
g2d.dispose();
}
private void drawText(String text, Graphics2D g2d) {
//Draw the text
int cHeight = getComponent().getHeight();
FontMetrics fm = g2d.getFontMetrics();
g2d.setColor(Color.WHITE);
if (cHeight > getHeight())
g2d.drawString(text, (getWidth() - fm.stringWidth(text)) / 2, (getHeight() + fm.getAscent()) / 2 + 2);
else
g2d.drawString(text, (getWidth() - fm.stringWidth(text)) / 2, (cHeight + fm.getAscent()) / 2 + 2);
}
private Graphics2D drawComponent(Graphics g) {
//Create a round rectangle
Shape round = new RoundRectangle2D.Float(0, 8, getWidth(), getHeight(), 8, 8);
//Draw the background
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.GRAY);
g2d.fill(round);
//Draw the left triangle
Point p1 = new Point(getWidth() / 2, getHeight() - 30);
Point p2 = new Point(getWidth() / 2 + 8, getHeight() - 20);
Point p3 = new Point(getWidth() / 2 - 8, getHeight() - 20);
int[] xs = {p1.x, p2.x, p3.x};
int[] ys = {p1.y, p2.y, p3.y};
Polygon triangle = new Polygon(xs, ys, xs.length);
g2d.fillPolygon(triangle);
return g2d;
}
}
Solution
A few things have changed to have the tooltip behave as expected. the paint method has been replaced by the paintComponent method, the addNotify call was removed, the method updated to fetch the window of the component and to give it a transparent background. setBorder(BorderFactory.createEmptyBorder()); was also needed to remove the components default border.
public class DefaultToolTip extends JToolTip {
public DefaultToolTip() {
setOpaque(false);
setPreferredSize(new Dimension(275, 30));
setBackground(new Color(255, 255, 255, 0));
setBorder(BorderFactory.createEmptyBorder());
}
#Override
public void addNotify() {
super.addNotify();
setOpaque(false);
Component parent = this.getParent();
if (parent != null) {
if (parent instanceof JComponent) {
JComponent jparent = (JComponent) parent;
jparent.setOpaque(false);
}
}
Window window = SwingUtilities.windowForComponent(this);
try {
window.setBackground(new Color(255, 255, 255, 0));
} catch (IllegalComponentStateException e) {
//Do nothing
}
}
#Override
public void paintComponent(Graphics g) {
//super.paintComponent(g);
String text = getComponent().getToolTipText();
Graphics2D g2d = drawComponent(g);
drawText(text, g2d);
g2d.dispose();
}
private void drawText(String text, Graphics2D g2d) {
//Draw the text
int cHeight = getComponent().getHeight();
FontMetrics fm = g2d.getFontMetrics();
g2d.setColor(Color.WHITE);
if (cHeight > getHeight())
g2d.drawString(text, (getWidth() - fm.stringWidth(text)) / 2, (getHeight() + fm.getAscent()) / 2 + 2);
else
g2d.drawString(text, (getWidth() - fm.stringWidth(text)) / 2, (cHeight + fm.getAscent()) / 2 + 2);
}
private Graphics2D drawComponent(Graphics g) {
//Create a round rectangle
Shape round = new RoundRectangle2D.Float(0, 8, getWidth(), getHeight(), 8, 8);
//Draw the background
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.GRAY);
g2d.fill(round);
//Draw the left triangle
Point p1 = new Point(getWidth() / 2, getHeight() - 30);
Point p2 = new Point(getWidth() / 2 + 8, getHeight() - 20);
Point p3 = new Point(getWidth() / 2 - 8, getHeight() - 20);
int[] xs = {p1.x, p2.x, p3.x};
int[] ys = {p1.y, p2.y, p3.y};
Polygon triangle = new Polygon(xs, ys, xs.length);
g2d.fillPolygon(triangle);
return g2d;
}
}
A note however, super.paintComponent(g) was commented out, since it would draw text another time.
Don't know if any of these will help but:
Don't override paint(...). Custom painting is done by overriding paintComponent(...).
Invoke super.paintComponent(...) as the first statement
Don't invoke addNotify() in a painting method. A painting method is for painting only.
with the '0' alpha value to make sure the background is transparent,
Swing components don't know how to handle transparent backgrounds. Just make the component non-opaque.
When the tooltip overlaps the component. The tooltip is actually added to a JWindow before it is displayed. So in your addNotify() logic, you can search for the window and make it transparent.
Check out:
Window window = SwingUtilities.windowForComponent(...);
I am trying to display two rotating wheels with diameter 512untis at different rates but i am not able to remove the previous drawn image graphics and set the rotated graphics at the correct position.
For now i am doing a rotation with arbitrary angle.
I tried affineTransform and got the rotations but it was weird like all pixels spread away.
Im using a while loop with thread.sleep(). The following is the code :
//The drawSmallCircle and drawBigCircle return two images.
class MyFramePart2 extends JFrame
{
String name;
JPanel big_obj_panel,small_obj_panel;
JLabel bigLabel,smallLabel;BufferedImage imgRet,imgRetSmall;
static double radians,angle,rev,fps,smallAngle,smallRadians;
int numLines,i=0;
MyFramePart2(String frameName,int numStrokes,double revolutions,double frameps)
{
numLines=numStrokes;
smallAngle=smallRadians=angle=radians=Math.toRadians(360/numLines);
rev=revolutions;
fps=frameps;
setSize(1240,720);
setLocation(0,0);
setLayout(null);
getContentPane().setBackground(Color.WHITE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
big_obj_panel=new JPanel();
big_obj_panel.setLayout(null);
big_obj_panel.setSize(512,512);
big_obj_panel.setLocation(100,100);
big_obj_panel.setBackground(Color.white);
add(big_obj_panel);
imgRet=drawBigCircle();
bigLabel = new JLabel(new ImageIcon(imgRet));
bigLabel.setLayout(null);
bigLabel.setLocation(0,0);
bigLabel.setSize(512,512);
bigLabel.setOpaque(true);
bigLabel.setBackground(Color.white);
big_obj_panel.add(bigLabel);
small_obj_panel=new JPanel();
small_obj_panel.setLayout(null);
small_obj_panel.setSize(512,512);
small_obj_panel.setLocation(700,100);
small_obj_panel.setBackground(Color.white);
add(small_obj_panel);
imgRetSmall=drawSmallCircle();
smallLabel = new JLabel(new ImageIcon(imgRetSmall));
smallLabel.setLayout(null);
smallLabel.setLocation(0,0);
smallLabel.setSize(512,512);
smallLabel.setOpaque(true);
smallLabel.setBackground(Color.white);
small_obj_panel.add(smallLabel);
setVisible(true);
while(i!=5) // suppose to be while true, just checking
{
setVisible(true);
bigLabel.setIcon(new ImageIcon(imgRet));
smallLabel.setIcon(new ImageIcon(imgRetSmall));
try{
Thread.sleep(10);
}
catch(Exception e)
{}
i++;
}
}
#Override
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d=(Graphics2D)g;
g2d.translate(256,256);
g2d.rotate(Math.toRadians(20));
g2d.translate(-256,-256);
g2d.drawImage(imgRet,0,0,null);
g2d.dispose();
super.paint(g);
g2d=(Graphics2D)g;
g2d.translate(256,256);
g2d.rotate(Math.toRadians(30));
g2d.translate(-256,-256);
g2d.drawImage(imgRetSmall,0,0,null);
g2d.dispose();
}
public static BufferedImage drawBigCircle()
{
BufferedImage img=new BufferedImage(512,512,BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d=img.createGraphics();
g2d.setColor(Color.black);
g2d.drawOval(0,0,511,511);
Line2D l2d;
while(angle <= 2*Math.PI)
{
l2d=new Line2D.Double(256,256,256+256*Math.cos(angle),256+256*Math.sin(angle));
g2d.draw(l2d);
angle=angle+radians;
}
return img;
}
}
First rule of Swing. Don't block the Event Dispatching Thread. Doing so will make you application look like it's hung and prevent the EDT from processing any repaint requests.
This means, you need some way to schedule updates that doesn't block the EDT
Second rule of Swing. Don't create or modify any UI component from any thread other then the EDT.
Generally, you should avoid overriding the paint method of top level containers like JFrame, apart from everything else, they're not double buffered, meaning your painting will flicker as it's updated. Instead, you should use one of the Swing containers, like JPanel
There are lots of different ways to achieve this. Basically, here I've used three lists, but if I was serious, I would create an object that could maintain all the required information (image, angle an delta)
In order to achieve the actual animation, I've used a javax.swing.Timer. This will trigger an event at least every n periods, but more importantly, it does it within the context of the Event Dispatching Thread. This ensures that all the changes made to the angles are done in way that will prevent any possibility of painting occurring while we're updating the values...
This example rotates the three images at different (random) speeds...
public class TestRotation {
public static void main(String[] args) {
new TestRotation();
}
public TestRotation() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new AnimationPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class AnimationPane extends JPanel {
private List<BufferedImage> images;
private List<Double> angles;
private List<Double> speed;
public AnimationPane() {
images = new ArrayList<>(5);
images.add(createWheel(50, 4));
images.add(createWheel(50, 3));
images.add(createWheel(50, 6));
angles = new ArrayList<>();
speed = new ArrayList<>();
for (int index = 0; index < images.size(); index++) {
angles.add(0d);
speed.add(Math.random() * 5d);
}
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int index = 0; index < angles.size(); index++) {
double angle = angles.get(index);
double delta = speed.get(index);
angle += delta;
angles.set(index, angle);
}
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 0;
int y = 0;
for (int index = 0; index < images.size(); index++) {
BufferedImage image = images.get(index);
double angle = angles.get(index);
// This is important. Basically we going to grab a isolated snap shot
// of the current graphics context. This means any changes we make
// will not affect the original graphics context (other then painting)
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
AffineTransform at = new AffineTransform();
at.translate(x, y);
at.rotate(Math.toRadians(angle), image.getWidth() / 2, image.getHeight() / 2);
g2d.setTransform(at);
g2d.drawImage(image, 0, 0, this);
g2d.dispose();
x += image.getWidth();
}
}
}
protected Point2D calculateOutterPoint(int radius, double angel) {
int x = Math.round(radius / 2);
int y = Math.round(radius / 2);
double rads = Math.toRadians((angel + 90));
// This determins the length of tick as calculate from the center of
// the circle. The original code from which this derived allowed
// for a varible length line from the center of the cirlce, we
// actually want the opposite, so we calculate the outter limit first
double fullLength = (radius / 2d);
// Calculate the outter point of the line
double xPosy = (x + Math.cos(rads) * fullLength);
double yPosy = (y - Math.sin(rads) * fullLength);
return new Point2D.Double(xPosy, yPosy);
}
public BufferedImage createWheel(int radius, int spokes) {
BufferedImage img = new BufferedImage(radius, radius, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.black);
g2d.drawOval(0, 0, radius - 1, radius - 1);
Point2D center = new Point2D.Double(radius / 2d, radius / 2d);
double angle = 360d / spokes;
for (int index = 0; index < spokes; index++) {
Point2D p = calculateOutterPoint(radius, index * angle);
g2d.draw(new Line2D.Double(center, p));
}
g2d.dispose();
return img;
}
}
I am using a paintComponent Class in a project of mine, and I am currently wondering how I can decrease the size of the rectangle from the top making it's way downwards.
This is the part of the code:
public Battery(){
super();
firstTime = true;
f = new Font("Helvetica", Font.BOLD, 14);
m = Toolkit.getDefaultToolkit().getFontMetrics(f);
}
public void paintComponent(Graphics g){
if(firstTime){
firstTime = false;
batteryLevel = 1 + this.getHeight();
decr = batteryLevel / 20;
}else{
g.setColor(Color.RED);
g.fillRect(1, 0, this.getWidth(), this.getHeight());
g.setColor(Color.GREEN);
g.fillRect(1, 0, this.getWidth(), batteryLevel);
g.setColor(Color.BLACK);
g.setFont(f);
g.drawString("TEST", (getWidth() - m.stringWidth("TEST")) / 2 , this.getHeight() / 2);
}
}
public void decreaseBatteryLevel(){
batteryLevel -= decr;
this.repaint();
}
PS. Sorry if I did something wrong, I'm new to this forum.
As you want the visible battery level to descend you will want to increase your Y co-ordinate in relation to the value of batteryLevel. You could use:
g.fillRect(1, getHeight() - batteryLevel, getWidth(), batteryLevel);
Instead
g.fillRect(1, 0, this.getWidth(), batteryLevel);
Do
g.fillRect(1, batteryLevel, this.getWidth(), getHeight() - batteryLevel);
Also maybe repaint(50L) instead of repaint().
If your question meant: how to animate a change in the battery level.
Use a javax.swing.Timer:
int toPaintBatteryLevel = batteryLevel;
// In the paintComponent paint upto toPaintBatteryLevel.
Timer timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (toPaintBatteryLevl == batteryLevel) {
return;
}
if (toPaintBatteryLevl > batteryLevel) {
--toPaintBatteryLevel; // Animate slowly
} else {
toPaintBatteryLevel = batteryLevel; // Change immediately
}
repaint(50L);
};
});
timer.start();
For ease of coding, there is a permanent timer. And externally one changes the batteryLevel,
and the time determines the toPaintBatteryLevel, which paintComponent uses to paint.
I am writing a java application using swing in which I need to draw a grid above a square. In order to do so, I am using the drawLine(...) method provided by the Graphics class.
Everything works fine except that it takes a lot of time to draw each line (more than 20 sec for 50 lines...). I can even see the lines being drawn in real time. One weird thing is that the horizontal lines are drawn way faster than the vertical lines (almost instantly).
I might be doing something wrong. Here is the code for the grid.
public void drawGrid(Graphics g){
g.setColor(new Color(255, 255, 255, 20));
int width = getWidth();
int height = (int) (width * Utils.PLATE_RATIO);
int step = pixelSize*gridSpacing;
Color bright = new Color(255, 255, 255, 100);
Color transparent = new Color(255, 255, 255, 20);
for(int ix = insets.left + step;
ix < width; ix += step){
if(((ix - insets.left) / step) % 10 == 0){
g.setColor(bright);
}
else{
g.setColor(transparent);
}
g.drawLine(ix, insets.top, ix, height+insets.top);
}
for(int iy = insets.top+step;
iy < (insets.top + height); iy += step){
if(((iy - insets.top) / step) % 10 == 0){
g.setColor(bright);
}
else{
g.setColor(transparent);
}
g.drawLine(insets.left, iy, width + insets.left, iy);
}
}
The code you have posted is fine, there is no problems in it.
Here is a working example of a component using your method (a bit simplified):
public static class MyGrid extends JComponent
{
private int step = 10;
public MyGrid ()
{
super ();
}
public Dimension getPreferredSize ()
{
return new Dimension ( 500, 500 );
}
protected void paintComponent ( Graphics g )
{
super.paintComponent ( g );
drawGrid ( g );
}
public void drawGrid ( Graphics g )
{
int width = getWidth ();
int height = getHeight ();
Color bright = new Color ( 255, 255, 255, 200 );
Color transparent = new Color ( 255, 255, 255, 100 );
for ( int ix = step; ix < width; ix += step )
{
if ( ( ix / step ) % 10 == 0 )
{
g.setColor ( bright );
}
else
{
g.setColor ( transparent );
}
g.drawLine ( ix, 0, ix, height );
}
for ( int iy = step; iy < height; iy += step )
{
if ( ( iy / step ) % 10 == 0 )
{
g.setColor ( bright );
}
else
{
g.setColor ( transparent );
}
g.drawLine ( 0, iy, width, iy );
}
}
}
I guess there is some problem outside that piece of code.
P.S. A bit an offtopic but...
I suggest you to calculate the visible part of the painting area (using either JComponent's getVisibleRect () method or Graphics g.getClip ().getBounds () method) and limit your paintings with only that area.
That small optimization could speedup component's painting in times if it is really large (for example with 10000x10000 pixels component's area).
Here is how I solved the problem using Double-Buffering, as advised by #sureshKumar. I am simply drawing on an offscreen image and simply calling drawImage() when the drawing is over. This seems to do the trick.
Edit: this seems to be useful only if you want to call your painting methods (in my case drawGrid()) from outside of the paintComponent(...) method.
Here is the code:
private Graphics bufferGraphics;
private Image offScreen;
private Dimension dim;
//other attributes not shown...
public CentralPanel(){
//Some initialization... (not shown)
//I added this listener so that the size of my rectangle
//and of my grid changes with the frame size
this.addComponentListener(new ComponentListener() {
#Override
public void componentResized(ComponentEvent e) {
dim = getVisibleRect().getSize();
offScreen = createImage(dim.width, dim.height);
bufferGraphics = offScreen.getGraphics();
repaint();
revalidate();
}
//other methods of ComponentListener not shown
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(offScreen, 0, 0, null);
}
public void drawGrid(){
int width = dim.width - insets.left - insets.right;
width -= (width % plateSize.getXSize());
int height = (int) (width*Utils.PLATE_RATIO);
height -= (height % plateSize.getYSize());
int step = pixelSize*gridSpacing;
Color bright = new Color(255, 255, 255, 100);
Color transparent = new Color(255, 255, 255, 20);
for(int ix = insets.left + step;
ix < (width+insets.left); ix += step){
if(((ix - insets.left) / step) % 10 == 0){
bufferGraphics.setColor(bright);
}
else{
bufferGraphics.setColor(transparent);
}
//I am now drawing on bufferGraphics instead
//of the component Graphics
bufferGraphics.drawLine(ix, insets.top, ix, height+insets.top);
}
step *= Utils.PLATE_RATIO;
for(int iy = insets.top+step;
iy < (insets.top + height); iy += step){
if(((iy - insets.top) / step) % 10 == 0){
bufferGraphics.setColor(bright);
}
else{
bufferGraphics.setColor(transparent);
}
bufferGraphics.drawLine(insets.left, iy, width + insets.left, iy);
}
}
P.S.: If this should be added as an edit to my question, please tell me and I'll do it.
I've got a JPanel I'm drawing onto and I'm trying to get it so that you can use the mouse wheel to "zoom" in and out by modifying the variable scale. Right now what happens is you can zoom in or out but all of the drawing shifts to the right and downwards when you zoom in and then back up and left when zooming out.
I want to make it so that it adjusts as if you were zooming in on the point at the center of the JPanel but I can't figure out how to calculate the right offset to translate by…
Anybody got an idea of how to do this, or even better a cleaner way of achieving this whole pan and zoom ability?
I am basically plotting a bunch of coordinates that came from a system where 0,0 is in the lower left corner and fall between the bounds:
xMin = 661208
xMax = 662618
yMin = 4291657
yMax = 4293285
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
double scale = details.getScale();
double xOffset = details.getxOffset();
double yOffset = details.getyOffset();
g2.scale(scale, -scale);
// Dividing offset by scale makes panning 1:1 with the cursor still. yMax to account for the
// fact we needed to flip around the y axis to make it right-side up.
g2.translate((-xMin + xOffset / scale), (-yMax + yOffset / scale));
// Code to draw stuff goes here. It uses coordinates between xMin-xMax and yMin-yMax to draw.
.
.
.
}
Here is an example with the wheel:
public class GraphicsOnly extends JPanel implements MouseWheelListener {
Shape[] shapes;
Dimension size;
double scale = 1.0;
private static int source = 100;
public GraphicsOnly() {
addMouseWheelListener(this);
size = new Dimension(10,10);
setBackground(new Color(240,200,200));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if(shapes == null) initShapes();
// Keep shapes centered on panel.
double x = (getWidth() - scale*size.width)/2;
double y = (getHeight() - scale*size.height)/2;
AffineTransform at = AffineTransform.getTranslateInstance(x, y);
at.scale(scale, scale);
g2.setPaint(Color.blue);
g2.draw(at.createTransformedShape(shapes[0]));
g2.setPaint(Color.green.darker());
g2.draw(at.createTransformedShape(shapes[1]));
g2.setPaint(new Color(240,240,200));
g2.fill(at.createTransformedShape(shapes[2]));
g2.setPaint(Color.red);
g2.draw(at.createTransformedShape(shapes[2]));
}
public Dimension getPreferredSize() {
int w = (int)(scale*size.width);
int h = (int)(scale*size.height);
return new Dimension(w, h);
}
private void initShapes() {
shapes = new Shape[3];
int w = getWidth();
int h = getHeight();
shapes[0] = new Rectangle2D.Double(w/16, h/16, w*7/8, h*7/8);
shapes[1] = new Line2D.Double(w/16, h*15/16, w*15/16, h/16);
shapes[2] = new Ellipse2D.Double(w/4, h/4, w/2, h/2);
size.width = w;
size.height = h;
}
public static void main(String[] args) {
GraphicsOnly app = new GraphicsOnly();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(app));
f.setSize(400, 400);
f.setLocation(200,200);
f.setVisible(true);
}
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
// TODO Auto-generated method stub
if(e.getWheelRotation() >0){
source = source-e.getScrollAmount();
}else{
source = source+e.getScrollAmount();
}
scale = source/100.0;
System.out.println(scale);
repaint();
revalidate();
}
}