Resize of Drawing in JPanel

Hi,
I am looking for some ideas on how to resize a drawing in JPanel.
I wanted to increase its width and height at run time by dragging its end points (any direction).
One more thing is how do I add text to the drawing at run time? Is this possible?
My idea is to develop an application similar to MS-Word where we can add few drawings and add text to them.
Any help would be great.
Mathew

The drawing code has to be written in ratios. Don't draw from x1, y1, to x2, y2 -- draw from (left + .3*width, top + .3 * height) to . . . Then the drag gesture should give you new width and height values, and you can just repaint().

Similar Messages

  • Please help with a drawing on JPanel in a background.

    Hello everybody,
    I have already post this question in the main java forum and was adviced to place the question here. Since then, I have refactored the code. I need your opinion and advice.
    My task is to draw some objects on the JPanel or some other components and to place the names to the objects, for example squares, but later, from the thread. Because it can take some time, untill the names will be avaliable.
    So, I refactored the code I post before http://forum.java.sun.com/thread.jspa?threadID=5192586&tstart=15
    And now, it draws on layers and from thread on resize, with some imitating interval.
    Is it a good approach I use, is there a better way, to draw on JPanel, after some objects were already painted.
    Here is my sample, try to resize window:
    package test;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JFrame;
    import javax.swing.JLayeredPane;
    import javax.swing.JPanel;
    public class Painter extends JFrame implements ComponentListener{
         private static final long serialVersionUID = 1L;
         private ThreadPainter threadPainter;
         JPanel panel = new JPanel() {
              private static final long serialVersionUID = 1L;
              @Override
              protected void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   System.out.println("repaint");
                   Graphics2D g2d = (Graphics2D) g;
                   g2d.setColor(Color.gray);
                   g2d.fillRect(0, 0, 800, 600);
                   g2d.setColor(Color.white);
                   for (int i = 0; i < 6; i++) {
                        Rectangle2D rec2d = new Rectangle2D.Double(10 + i * 100,
                                  10 + i * 100, 10, 10);
                        g2d.fill(rec2d);
                        g2d.drawString("Square " + i, 10 + i * 100 + 20, 10 + i * 100);
                   // start thread to paint some changes later
                   if (threadPainter == null) {
                        threadPainter = new ThreadPainter();
                        threadPainter.start();
         JPanelTest panel1 = new JPanelTest();
         public class JPanelTest extends JPanel {
              private static final long serialVersionUID = 1L;
              private int times = 0;
              @Override
              protected void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   Graphics2D g2d = (Graphics2D) g;
                   g2d.setColor(Color.red);
                   System.out.println("repaint panel test");
                        System.out.println("repaitn times");
                        g2d.drawString("Square " + times, 10 + times * 100 + 20, 10 + times * 100);
              public void repaintMethod(int times) {
                   this.times = times;
                   this.repaint(times * 100 + 20, times * 100, 300,300);
         public class ThreadPainter extends Thread {
              private boolean stop = false;
              @Override
              public void run() {
                   while (!stop) {
                        int cnt = 0;
                        for (int i = 0; i < 6; i++) {
                             System.out.println("do task");
                             panel1.repaintMethod(i);
                             // load data, do calculations
                             try {
                                  // emulate calcilation
                                  Thread.sleep(1000);
                             } catch (InterruptedException e) {
                                  e.printStackTrace();
                             if (stop) {
                                  break;
                             cnt++;
                        if (cnt == 6) {
                             stopThread();
              public void stopThread() {
                   this.stop = true;
         public Painter() {
              this.setLayout(new BorderLayout());
              JLayeredPane pane = new JLayeredPane();
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setLocation(new Point(100, 100));
              this.setPreferredSize(new Dimension(800, 600));
              this.panel.setOpaque(false);
              this.panel1.setOpaque(false);
              pane.setOpaque(false);
              pane.add(panel, JLayeredPane.DEFAULT_LAYER);
              pane.add(panel1, new Integer(
                        JLayeredPane.DEFAULT_LAYER.intValue() + 1));
              this.add(pane, BorderLayout.CENTER);
              panel.setBounds(new Rectangle(0, 0, 800, 600));
              panel1.setBounds(new Rectangle(0, 0, 800, 600));
              this.addComponentListener(this);
         public static void main(String[] args) {
              Painter painter = new Painter();
              painter.pack();
              painter.setVisible(true);
         @Override
         public void componentHidden(ComponentEvent e) {
              // TODO Auto-generated method stub
         @Override
         public void componentMoved(ComponentEvent e) {
              // TODO Auto-generated method stub
         @Override
         public void componentResized(ComponentEvent e) {
              if (threadPainter != null) {
                   threadPainter.stopThread();
                   threadPainter = new ThreadPainter();
                   threadPainter.start();
         @Override
         public void componentShown(ComponentEvent e) {
              // TODO Auto-generated method stub
    }

    Hello camickr,
    thanks for your answers.
    It sounds like you are trying to add a component and
    descriptive text of this component to a panel. So the
    question is why are you overriding paintComponent()
    method on your main panel and why are you using a
    Thread.JLabel is not a good way I think, because of the performance. Think about 1000 labels on the panel. And the text can have different style, so drawString method is better here.
    Create a component that draws your "shape" and then
    add that component to the main panel that uses a null
    layout. That means you need to specify the bounds of
    the component. Then you can add a JLabel containing
    the releated text of the component. If you don't know
    the text then it can always be updated with the
    setText() method in the future. Also, the foreground
    can be updated as well.If it would be lable, I could update Text as us say and JLabels would be perfect. In this case, JLabels are not what I need.
    You said the names will not be available right away.
    Well then you don't start a thread to schedule the
    repainting of the names since you don't know exactly
    when the name will be available. You wait until you
    have the names and then simple use the setText()
    method.I have decided this way.
    Draw all objects on the panel in different layers, for different type of objects.
    Get names and make some calculations, for example, optimal position of the text on the panel (in Thread) and after it repaint();
    Repaint draw all objects, but now it have the names, which will be added too.
    The requirement is: thousand of objects on the panel
    Different type of ojbects should be drawn in different layers
    Names should be added to the objects and maybe some other drawings (showing state). Name and drawing can be done later, but should be added dynamically, after all calculation are done.

  • Drawing in JPanel within JApplet

    Hi, having problems drawing in jpanel that is within japplet.
    My code follows:
    * TestApplet.java
    * @author WhooHoo
    //<applet code="TestApplet.class" width="400" height="250"></applet>
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.Graphics;
    import javax.swing.JButton;
    public class TestApplet extends javax.swing.JApplet implements ActionListener {
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel1;
    private Graphics g;
    private javax.swing.JButton btnTest;
    /** Creates new form Cafe */
    public TestApplet() {
    public void init() {
    jPanel1 = new javax.swing.JPanel();
    btnTest = new javax.swing.JButton();
    jPanel2 = new javax.swing.JPanel();
    btnTest.setText("test");
    jPanel1.add(btnTest);
    getContentPane().add(jPanel1, java.awt.BorderLayout.NORTH);
    jPanel2.setBorder(new javax.swing.border.TitledBorder("Draw"));
    getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);
    btnTest.addActionListener(this);
    jPanel2.setOpaque(false);
    g=jPanel2.getGraphics();
    /** Invoked when an action occurs.
    public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equalsIgnoreCase("test"))
    System.out.println("test");
    g.setColor(java.awt.Color.BLACK);
         g.drawString("testing",50,50);
         g.drawString("testing",50,100);
         g.drawString("testing",50,150);
         g.drawString("testing",50,200);
         g.drawString("testing",50,250);
    public void destroy()
    g.dispose();
    When this code is run the applet seems to run fine but when the button is pressed, nothing is drawn in jpanel. Can anyone see what the problem is and suggest a fix. I need to be able to pass graphics obj around to other methods to draw in the other methods also. Testing will not dispaly anywhere in applet or frame.
    plz email or post any suggestions.

    but if I can get this to workYou can get this to work, here is the working code:
    import java.awt.event.*;
    import java.awt.Graphics;
    import javax.swing.*;
    import java.awt.*;
    public class TestApplet extends JApplet implements ActionListener {
         private JPanel jPanel2,jPanel1;
         private javax.swing.JButton btnTest;
         String string1 = "";
         public TestApplet() {
         public void init() {
              jPanel1 = new JPanel();
              btnTest = new JButton();
              jPanel2 = new JPanel(){
                   public void paintComponent(Graphics g) {
                        g.setColor(java.awt.Color.BLACK);
                        g.drawString(string1,50,50);
                        g.drawString(string1,50,100);
                        g.drawString(string1,50,150);
                        g.drawString(string1,50,200);
                        g.drawString(string1,50,250);
              btnTest.setText("test");
              jPanel1.add(btnTest);     
              getContentPane().add(jPanel1, BorderLayout.NORTH);
              jPanel2.setBorder(new javax.swing.border.TitledBorder("Draw"));
              getContentPane().add(jPanel2, BorderLayout.CENTER);
              btnTest.addActionListener(this);
              jPanel2.setOpaque(false);
         public void actionPerformed(ActionEvent e) {
              if (e.getActionCommand().equalsIgnoreCase("test"))
                   System.out.println("test");
                   string1 = "testing";
                   jPanel2.repaint();
         public void destroy(){}
    }Unfortunately all painting to a component must happen inside the paint method. I don't know if what you ask is possible. I try to figure it out. Maybe someone else has an answer.
    Pandava

  • Photoshop CC is dramatically slow when resizing or drawing.

    Hello everyone.
    Please assist me in finding out a bottleneck:
    OS: Windows 7 x64 Professional
    Photoshop CC, not 2014.
    Hardware configuration:
    MotherBoard- Asus P8Z77-V LX LGA
    CPU - Intel Core i7 2700K + Zalman CNPS10X EXTREME
    Video Card- Asus GTX660-DC2OCPH-2GD5, 2GB, GDDR5
    RAM: 2x8Gb HYNIX Original DDR3 1600, DIMM + 2x8Gb Kingston KVR16N11/8 DDR3 1600, DIMM
    HDD:
    4xSeagate Barracuda ST2000DM001 - 2Tb - RAID 5 - for Data storage, OS TEMP directory.
    1xWestern Digital 500Gb - for Photoshop scratch file, 300Gb free.
    1xWestern Digital 2Tb for other stuff + OS page file. 1.2Tb free.
    SSD: OCZ Agility 3, 90Gb - OS + Photoshop installed. 30Gb free
    PSU: HIPRO HPP600W-80Plus
    Tablet: Wacom Intuos Pro M.
    Photoshop preferences:
    History levels - 15
    Cache levels - 8
    Cache tile size - 1024Kb
    Photoshop can use up to 70% memory.
    GPU Acceleration - tried both "off" and "basic"
    Previews for layers are set to "Minimum".
    My main photoshop usage is in editing photos - 5760x3840 pixels.
    When I create a document with 5760x3840 pixels and add several layers with editing, curves, masks and so on I try to resize the image. Photoshop starts lagging. Same effect happens when I create a mask with a simple brush. As example - I draw a 1cm line on my tablet, and then PS does the same with an about 10 seconds delay.
    Any help would be appreciated. I had no same issues with CS6.

    1.  You probably have a specific problem with drivers that's causing your tablet operations to be very inefficient.  I would look into getting new Wacom drivers to start with.  Focus first on why your powerful system is running poorly with the tablet.  Determine whether a mouse works better than the tablet, to ensure you've isolated where the problem is.
    Then, after working that out, if performance is still troublesome to you...
    2.  I would suggest that, assuming you have the budget, you relegate ALL your spinning hard drives to be backup or low access storage drives.  Do NOTHING with them for normal, everyday use.  See item 3 below for that.
    3.  Get 2 TB of SSD storage in the form of four 512 GB SSDs, put them in a RAID 0 array - not RAID 5.  Make that drive C: and install Windows, all apps, your working data, scratch, swap, etc.  Don't worry about reliability - get good ones, pro models.  They have high MTBF, and even with 4 SSDs you will not be taking nearly as big a chance of failure as with a single HDD.  Re-evaluate whether the RAID controller you're using is a good match for high throughput SSD storage and get a good one if not.
    4.  Institute a thorough backup regimen.  That sounds a bit scary, but it really boils down to setting your system up to do system regular system image backups to your HDD storage (or an offline USB drive).  RAID 5 wastes resources in an ongoing way in anticipation of failure.  Backup prepares you for any eventuality, and RAID 0 uses the resources efficiently - especially SSDs.
    5.  You have 32 GB of RAM, which is sufficient, but make sure you've done whatever is needed to ensure your system maximizes its efficiency in accessing that RAM.  I'm not familiar with that ASUS motherboard, so I don't know what it can do, but sometimes you can dig and find info on optimum configurations where when the right things match, the system switches into a higher mode with more channels, etc.  I know my workstation does special things when the RAM all matches.
    I've personally done all the above, save for the tablet diagnosis as I don't have a tablet.  There is NOTHING that will wake up a system - every aspect - like having a high throughput I/O subsystem.  You'll wonder how you ever could stand using HDDs.
    -Noel

  • Draw a JPanel in a Image

    Hi,
    I'd like to draw what is in my JPanel into a image to export it. But When I try to do that , I have problems. I put my code to be more clear:
    // comp is the JPanel
    comp.setDoubleBuffered(false);
    JFrame frame = new JFrame();
    frame.setContentPane(comp);
    frame.pack();
    Dimension size = comp.getSize();
    Image image = comp.createImage(size.width,size.height);
    final Graphics g = image.getGraphics();
    g.setClip(0,0,size.width,size.height);
    try
    // Paint the Swing component into the image
    SwingUtilities.invokeAndWait(new Runnable()
    public void run()
    comp.paint(g);
    catch (Exception x) { x.printStackTrace(); }
    finally
    g.dispose();
    frame.dispose();
    The problem is that I export into GIF this image, but if I don't show the frame:
    frame.show(); at least one time, the image is bad: it has a black background. I tried to set the background, but nothing works execpt showing the frame.
    If you could help me, I would be great.
    Vincent

    to diesel22
    http://onesearch.sun.com/search/developers/index.jsp?col=devforums&qp=&qt=%2Bprint+%2Bshow

  • How do i draw on JPanel?

    Hi all,
    Is it possible to draw inside swing JPanel? If so, how to draw, say, a rectangle inside a JPanel? Thanks a bunch!
    mp

    JPanel, is a generic light weight component. By Default, they dont paint any thing except for the background, you can easily add borders and customise their painting.

  • Ridiculously dumb question about drawing in JPanel

    Howdy everyone,
    I gotta really stupid question that I cant figure out the answer to. How do I draw an image to a JPanel, when my class inherits from JFrame?
    Thanks,
    Rick

    Ok,
    Problem. The image isnt showing up in the Frame I set up for it. Heres my code. Im trying to get this image to show up in a scollable window. Can anyone tell what the problem with this code is??
    JPanel imgPanel= new JPanel(){
    protected void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawImage(getToolkit().createImage(imstr),imgw,imgh,this);
    imgPanel.setVisible(true);
    this.getContentPane().setLayout(new BorderLayout());
    this.getContentPane().add(new JScrollPane(imgPanel));
    this.setVisible(true);
    Any ideas?
    Thanks
    Rick

  • How to draw a JPanel in an offscreen image

    I am still working on painting a JPanel on an offline image
    I found the following rules :
    - JPanel.setBounds shall be called
    - the JPanel does not redraw an offline image, on should explicitly override paint()
    to paint the children components
    - the Children components do not pain, except if setBounds is called for each of them
    Still with these rules I do not master component placement on the screen. Something important is missing. Does somebody know what is the reason for using setBounds ?
    sample code :
    private static final int width=512;
    private static final int height=512;
    offScreenJPanel p;
    FlowLayout l=new FlowLayout();
    JButton b=new JButton("Click");
    JLabel t=new JLabel("Hello");
    p=new offScreenJPanel();
    p.setLayout(l);
    p.setPreferredSize(new Dimension(width,height));
    p.setMinimumSize(new Dimension(width,height));
    p.setMaximumSize(new Dimension(width,height));
    p.setBounds(0,0,width,height);
    b.setPreferredSize(new Dimension(40,20));
    t.setPreferredSize(new Dimension(60,20));
    p.add(t);
    p.add(b);
    image = new java.awt.image.BufferedImage(width, height,
    java.awt.image.BufferedImage.
    TYPE_INT_RGB);
    Graphics2D g= image.createGraphics();
    // later on
    p.paint(g);
    paint method of offScreenPanel :
    public class offScreenJPanel extends JPanel {
    public void paint(Graphics g) {
    super.paint(g);
    Component[] components = getComponents();
    for (int i = 0; i < components.length; i++) {
    JComponent comp=(JComponent) components;
    comp.setBounds(0,0,512,512);
    components[i].paint(g);

    Unfortunately using pack doesn't work, or I didn't use it the right way.
    I made a test case, eliminated anything not related to the problem (Java3D, applet ...). In the
    test case if you go to the line marked "// CHANGE HERE" and uncomment the jf.show(), you have
    an image generated in c:\tmp under the name image1.png with the window contents okay.
    If you replace show by pack you get a black image. It seems there still something.
    simplified sample code :[b]
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import com.sun.j3d.utils.applet.*;
    import com.sun.j3d.utils.image.*;
    import com.sun.j3d.utils.universe.*;
    import java.io.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class test {
    private static final int width=512;
    private static final int height=512;
    public test() {
    JPanel p;
    BorderLayout lay=new BorderLayout();
    java.awt.image.BufferedImage image;
    // add a JPanel with a label and a button
    p=new JPanel(lay);
    p.setPreferredSize(new Dimension(width,height));
    JLabel t=new JLabel("Hello");
    t.setPreferredSize(new Dimension(60,20));
    p.add(t,BorderLayout.NORTH);
    p.setDebugGraphicsOptions(DebugGraphics.LOG_OPTION );
    // show the panel for debug
    JFrame jf=new JFrame();
    jf.setSize(new Dimension(width,height));
    jf.getContentPane().add(p);
    [b]
    // CHANGE HERE->
    jf.pack();
    //jf.show();
    // create an off screen image
    image = new java.awt.image.BufferedImage(width, height,
    java.awt.image.BufferedImage.TYPE_INT_RGB);
    // paint JPanel on off screen image
    Graphics2D g= image.createGraphics();
    g.setClip(jf.getBounds());
    System.err.println("BEFORE PAINT");
    jf.paint(g);
    System.err.println("AFTER PAINT");
    // write the offscreen image on disk for debug purposes
    File outputFile = new File("c:\\tmp\\image1.png");
    try {
    ImageIO.write(image, "PNG", outputFile);
    } catch (Exception e) {
    System.err.println(e.getMessage());
    g.dispose();
    jf.dispose();
    public static void main(String[] args) {
    test t=new test();
    }

  • Resizing drawing objects defies pixel snapping

    This happens mostly with drawing objects, and to a lesser degree with shapes. When resizing drawing objects in Flash CS6 with pixel snapping turned on, one would expect the dimensions of the shape to snap to even pixel numbers. For the most part it does, but too frequently the position and size values begin to drift into fractions of pixels.
    If you create a rectangle as a drawing object, no stroke, it will snap to pixels properly. Drag it around and it always lands on whole pixel values. Now try resizing it using the free transform tool, or even by clicking and dragging the position and size values in the properties panel. Width and height values will mostly stick to whole pixels, but too often it will slip into fractions of pixels, bizarrely offsetting the x and y values as well. If you resize a drawing object and this error occurs, it does not help to try and move it to snap it back onto whole pixels, because it will snap to whatever fraction of a pixel it's currently stuck in, thereby forcing the user to manually edit the object's x and y coordinates.
    This is a problem in my workflow as I'm constantly having to keep an eye on the properties panel and manually editing the numbers when shapes stray into 2.85 pixels or some such when I want it at 3. I find myself frequently just entering the numbers I want, which defeats the purpose of pixel snapping in the first place.

    This happens mostly with drawing objects, and to a lesser degree with shapes. When resizing drawing objects in Flash CS6 with pixel snapping turned on, one would expect the dimensions of the shape to snap to even pixel numbers. For the most part it does, but too frequently the position and size values begin to drift into fractions of pixels.
    If you create a rectangle as a drawing object, no stroke, it will snap to pixels properly. Drag it around and it always lands on whole pixel values. Now try resizing it using the free transform tool, or even by clicking and dragging the position and size values in the properties panel. Width and height values will mostly stick to whole pixels, but too often it will slip into fractions of pixels, bizarrely offsetting the x and y values as well. If you resize a drawing object and this error occurs, it does not help to try and move it to snap it back onto whole pixels, because it will snap to whatever fraction of a pixel it's currently stuck in, thereby forcing the user to manually edit the object's x and y coordinates.
    This is a problem in my workflow as I'm constantly having to keep an eye on the properties panel and manually editing the numbers when shapes stray into 2.85 pixels or some such when I want it at 3. I find myself frequently just entering the numbers I want, which defeats the purpose of pixel snapping in the first place.

  • Problem with JPanel inside JScrollPane

    I want to make a simple graphic editor (like MS-Paint) with Java.
    I create the frame using JFrame, and use many Swing component. But I found
    some difficult when I tried to create the drawing area (the area where user
    performs drawing). I use JPanel as drawing area and I put it in JScrollPane.
    I use JScrollPane in case if user want to create a big drawing area.
    What I want to do with drawing area is, to put it in JScrollPane with size smaller than JScrollPane but I can't get it because the size of drawing area (JPanel) is always be the same as JScrollPane size. In MS-Paint you can see that the canvas (drawing area) size is able to be resize. And the canvas default color is white, and the Scroll Box around it has darkgray color. How can I make it like that (MS-Paint)? Please help. Thanks...
    Irfin

    I haven't actually tested this, but I think it should work...
    Add a JPanel to the scrollpane setting it's background to grey (i think the dark grey in MSPaint is something easy like 128,128,128). Set the layout on that panel to null, then add a second panel to that panel, at freeze it's size (ie. setMaximumSize). Doing it this way will allow you to set like a (10,10) position or something like that, giving the second panel a position away from the edge of the scrollpane.
    Seeing as you will be using mouse listeners anyways, you might even be able to allow for the second panel to be resized by checking the mouse position to see if the mouse is over the edge of the panel. I won't go into detail, that'll ruin the fun for you.
    Good luck, hope this helps.
    Grant.

  • Component resize, paint and AffineTransform

    Hello,
    I am resizing a JInternalFrame that contains a JPanel.
    When I call:
    MyJPanel.repaint();The paint function gets the dimensions of the JPanel
    using getWidth() and getHeight(), once, at the start of the
    paint function. The function then proceeds to plot some lines and
    points on a graph. Everything appears to work fine for lines and points (ie: drawOval).
    The function then goes on to draw some text for the axes of the graph. The Y axis
    text plots fine. The X axis text is rotated using AffineTransform and plots intermittently
    with the correct and incorrect position.
    Calling repaint() for the JPanel, without resizing,
    everything renders in the proper place
    via the overridden paint() procedure for that panel.
    When I resize the JInternalFrame, thus causing the
    JPanel to also automatically resize and repaint, the JPanel
    paints all lines and points in the correct locations
    with respect to the bounds of the JPanel. The
    Y axis text, drawn using drawText() plots in the correct place.
    The X axis text then plots in the wrong place after AffineTransform
    positioning in a location that would indicate it is transforming based on the
    coordinate system of the JInternalFrame rather than the JPanel (??).
    To create the text transform I am calling the following function:
    public void drawRotatedText(Graphics g, String text, int xoff, int yoff, double angle_degrees){
                        Graphics2D g2d=(Graphics2D)g;
                        AffineTransform old_at=((Graphics2D)g).getTransform();
                        AffineTransform at = new AffineTransform(old_at);
                        at.setToTranslation(xoff, yoff);
                        at.rotate((angle_degrees/360.0)*Math.PI*2.0);
                        g2d.setTransform(at);
                        g2d.drawString(text, 0, 0);
                        g2d.setTransform(old_at);
                    }The parameter Graphics g is the Graphics passed from public void MyJPanel.paint(Graphics g) .
    Why would AffineTransform get confused regarding which component the Graphics is coming from?
    More importantly, how can I avoid the problem?
    Thanks,
    P

    >
    To create the text transform I am calling the following function:
    public void drawRotatedText(Graphics g, String text, int xoff, int yoff, double angle_degrees){
    Graphics2D g2d=(Graphics2D)g;
    AffineTransform old_at=((Graphics2D)g).getTransform();
    AffineTransform at = new AffineTransform(old_at);
    at.setToTranslation(xoff, yoff);
    at.rotate((angle_degrees/360.0)*Math.PI*2.0);
    g2d.setTransform(at);
    g2d.drawString(text, 0, 0);
    g2d.setTransform(old_at);
    The problem is with the use of at.setToTranslation(xoff, yoff); instead of at.translate(xoff, yoff).
    After changing that the problem cleared up.
    P

  • How can I Print a JPanel including all added Components?

    Hello dear saviours,
    I have a JPanel object which is responsible for displaying a Graph.
    I need to Print the Components of this JPanel as close to what they look like to the user as possible.
    I thought about casting the JPanel into an Image of some kind, but couldn't find anything but how to add am Image to a JPanel (God damned search engines :-).
    But wait, this gets more interesting!
    I need to have control over the scale of the Printed matterial.
    I want the option to choose between a single page and dividing the drawing the JPanel displays into Multiple-Pages.
    In both cases I need full details of all the data (Nodes, Arcs, Text describing the various Nodes and Arcs names or type, etc.).Keeping the sizes of all these components is also important (that means, I don't want the nodes to be tinny-winny and the Fonts to be twice as large as the nodes and so on...).
    Attached is the code of the PrintUtillity class I created as an API for printing the JPanel data:
    package ild;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    /** A simple utility class that lets you very simply print
    * an arbitrary component. Just pass the component to the
    * PrintUtilities.printComponent. The component you want to
    * print doesn't need a print method and doesn't have to
    * implement any interface or do anything special at all.
    * <P>
    * If you are going to be printing many times, it is marginally more
    * efficient to first do the following:
    * <PRE>
    * PrintUtilities printHelper = new PrintUtilities(theComponent);
    * </PRE>
    * then later do printHelper.print(). But this is a very tiny
    * difference, so in most cases just do the simpler
    * PrintUtilities.printComponent(componentToBePrinted).
    * 7/99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
    * May be freely used or adapted.
    public class PrintUtilities implements Printable {
    private Component componentToBePrinted;
    public PrintUtilities(Component componentToBePrinted) {
    this.componentToBePrinted = componentToBePrinted;
    public static void printComponent(Component c) {
    new PrintUtilities(c).print();
    public void print() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if (printJob.printDialog())
    try {
    printJob.print();
    } catch(PrinterException pe) {
    System.out.println("Error printing: " + pe);
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0) {
    return(NO_SUCH_PAGE);
    } else {
    Graphics2D g2d = (Graphics2D)g;
    // double scale = 2;
    // g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    double scaleFactor = java.lang.Math.min((double)this.componentToBePrinted.getSize().width/(double)(pageFormat.getImageableWidth()),
    (double)this.componentToBePrinted.getSize().height/(double)(pageFormat.getImageableHeight()));
    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    g2d.scale(1.0/scaleFactor,1.0/scaleFactor);
    // disableDoubleBuffering(componentToBePrinted);
    componentToBePrinted.paint(g2d);
    enableDoubleBuffering(componentToBePrinted);
    return(PAGE_EXISTS);
    /** The speed and quality of printing suffers dramatically if
    * any of the containers have double buffering turned on.
    * So this turns if off globally.
    * @see enableDoubleBuffering
    public static void disableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
    /** Re-enables double buffering globally. */
    public static void enableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);

    That's a nice utility, but my JPanel gets truncated when printed. Is there a way to print a JPanel in full.

  • JLayeredPane Resize

    I have two JPanels which I want to add to my JLayeredPane. The JLayeredPane has to show one of the JPanels, dependant on the state of a combobox. When the user resizes the window the JPanel inside the JLayeredPane also needs to resize. I can't get JLayeredPane to work correctly without setting the size of the JPanels (which is something I don't want to do because the size of the JPanels will be determined by the size of the window).
    I've looked a great deal to find the answer to my problem, but no luck so far. This is what I have.
              layered = new JLayeredPane();
              layered.setLayout(new BorderLayout());
              layered.setLayer(treepanel, new Integer(0));
              layered.add(treepanel,BorderLayout.CENTER);
              layered.setLayer(searchpanel, new Integer(1));
              layered.add(searchpanel,BorderLayout.CENTER);
              layered.moveToFront(treepanel); This code only shows the last added panel (searchpanel). The last line apperantly does nothing (moveToFront(treepanel)).
    How can I fix this?

    Sounds like you should be using a CardLayout, not a Layered Pane.
    "How to Use Card Layout"
    http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html
    Otherwise you will need to add a ComponentListener to the layered pane and resize the panels manually whenever the layered pane is resized.

  • Overlapping two JPanels on a JLayeredPane

    I am having some problems overlapping two JPanels on a JLayeredPane for some reason only one of them shows when I compile the program! Any help would be greatly appreciated
    The code is the following:
    import java.lang.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class SpaceBall
    //To do the background just draw a JPanel inside another //JPanel just set the opacity of the outside one
    //to false and let
    //it hold all the components of the game
    public static void main(String[] args)
    //declaring the buttons
    JButton test=new JButton("test");
    JButton test1=new JButton("test1");
    JButton test2=new JButton("test2");
    //declaring and setting the properties of the frame
    JFrame SpaceBall= new JFrame("Space Ball");
    SpaceBall.setSize(700,650);
    //declaring the Panels
    JLayeredPane bgPanel= new JLayeredPane();
    JPanel fgPanel= new JPanel();
    JPanel topPanel= new JPanel();
    JPanel sidePanel= new JPanel();
    JPanel lowPanel= new JPanel();
    JPanel masterPanel= new JPanel();
    //adding the buttons to the corresponding panels
    fgPanel.add(test1);
    sidePanel.add(test2);
    topPanel.add(test);
    ImageIcon background= new ImageIcon("images/background.jpg");
    JLabel backlabel = new JLabel(background);
    backlabel.setBounds(0,0,background.getIconWidth(),background.getIconHeight());
    backlabel.add(test1);
    bgPanel.add(backlabel, new Integer(0));
    fgPanel.setOpaque(false);
    bgPanel.add(fgPanel, new Integer(100));
    bgPanel.moveToFront(fgPanel);
    //adding bgPanel and sidePanel to lowPanel
    lowPanel.setLayout(new GridLayout(1,2));
    lowPanel.add(bgPanel);
    lowPanel.add(sidePanel);
    //adding the Panels to the masterPanel
    masterPanel.setLayout(new GridLayout(2,1));
    masterPanel.add(topPanel);
    masterPanel.add(lowPanel);
    //getting the container of SpaceBall and adding the Panels to it
    Container cp=SpaceBall.getContentPane();
    cp.add(masterPanel);
    //displaying everything
    SpaceBall.show();
    WindowListener ClosingTheWindow=new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    SpaceBall.addWindowListener(ClosingTheWindow);

    Take a look at the section from the Swing tutorial titled "How to Use Layered Panes". It has a sample program:
    http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html

  • Why does my login panel resize?

    Hi,
    This is probably a basic problem. So please bear with me.
    I'm making an application and Applet, where the user needs to log in. I created a Frame, that scales to cover the whole screen.
         dimension = Toolkit.getDefaultToolkit().getScreenSize();
         setBounds (0, 0, dimension.width, dimension.height);After the Frame is created, I create a JPanel in it, where the user needs to enter username and password. And as users go, they will make errors, so I have to add functionality to check on
    1. Are username and password filled in
    2. Can username and password be used to authenticate
    So I need to draw that JPanel a few times. And there it goes wrong. So my question is, can you help me with my JPanel.
       // Constructor
       public LogInPanel () {
          width = 450;
          height = 350;
          // Create error label and set its colour
          errorLabel = new JLabel ("Fill in both fields", SwingConstants.LEFT);
          errorLabel.setForeground(Color.RED);
          setLayout(new GridLayout (4, 2)); // 4 rows, 2 columns
          setUp();
       public void actionPerformed(ActionEvent event) {
              command = event.getActionCommand();
              if (OK.equals(command)) {
                   //Process the user name and password.
                   userName = userNameField.getText();
                   password = passwordField.getPassword();
                   isError = ((userName.length() == 0) || (password.length ==0));
              if (!isError) {
                   // TODO: Authenticate with system
              else {
                   // Error condition, either user name or error not filled in. Do setUp() again.
                   setUp();
        private void setUp () {
            // Set the size and location of this panel
            setBounds (width, height, width, height);
             // User name label and text field
             add (unameLabel);
             add (userNameField);
             // Password label and text field
             add(passLabel);
             add(passwordField);
             // Create okButton and add it to the layout
             JComponent okButton = createButtonPanel();
             add(okButton);
             // An empty panel to fill up the empty spot after the button
             JPanel emptyPanel = new JPanel();
             emptyPanel.setBackground(Color.WHITE);
            if (isError) {
                add(errorLabel);
            setSize(dimension.width/3, dimension.height/3);
            setVisible (true);
        private JComponent createButtonPanel() {
            JPanel panel = new JPanel(new GridLayout(0,1));
            JButton okButton = new JButton("OK");
            okButton.setActionCommand(OK);
            okButton.addActionListener(this);
            panel.add(okButton);
            return panel;
        }When I run the code I get the following LoginPanel displayed
    |Username: | "userNameField"       |
    |Password: | "add(passwordField)"  |
    |OKbutton  |emptyPanel             |
    |Nothing yet                       |
    ------------------------------------And as I emulate a stupid user, I directly press the OK button. What happens now is that my LoginPanel moves up a few lines, and increases four times (2x in width, 2x in height), to something like:
    |Username: | "userNameField"                                           |
    |Password: | "add(passwordField)"                                      |
    |OKbutton  |emptyPanel                                                 |
    |No error message!                                                     |
    |                                                                      |
    |                                                                      |
    |                                                                      |
    |                                                                      |
    |                                                                      |
    ------------------------------------------------------------------------And I can't find the reason for that behaviour. So hopefully you see it. And if so, do tell.
    TIA,
    Abel

    without your code, I can't tell why you are having this behavior, however I can tell you that when I've done something like this, I've done it differently. For one, I don't recreate the JPanel but rather I show a JOptionPane.showMessage(....) error message over the panel, the erase the JPanel's fields and set focus where I want it after the JOptionPane has been dealt with. This is simpler than your current plan and thus less likely to blow-up.

Maybe you are looking for

  • HT3529 iMessage appearing in 2 different iPhones with distinct phone numbers but using same apple ID

    I and my friend both use same apple ID. When someone sends me an iMessage to my iPhone, it goes to his iPhone with separate phone number also. When I send someone an iMessage from my iPhone, the message will appear as sent from his iPhone also. But t

  • No "action" attribute found

    I am getting the following error messages.  I have checked through the SDN and found many notes on the subject, but I am still unable to figure out why I am getting the following errors.  Can anyone help please? 2007-06-14 13:51:52 Error No "action"

  • Illustrator CS5 Windows 7 64-bit Support

    I was unable to find a direct anwser to the following questions so figured it would be best to ask here: Is Illustrator CS5 supported on Windows 7 64-bit?  If so does it run as a 64-bit application or is it running in 32-bit mode?

  • VF02 Prevent changes to an invoice

    Hi, I'm looking for a way to prevent some invoices, identified through a group of attributes, to be changed once created. Any change through VF02, release to accounting and anything else should be blocked or readdressed to display only. Is there a wa

  • Form scheduling

    Hi - I want to build two simple forms for my site - one to display during office hours - one outside of office hours. I know how to build the forms - but how do I schedule them? I'm looking at trying to do some kind of date/time based layer visibilit