How to draw an image at the center of a JscrollPane

I have an image that I want to be centered in my JScrollPane. When I zoom-in, I want the image to fill the entire jscrollpane. When I zoom out it returns to the original scale. My problem is, when I open the image, it appears at the upper left corner of the JScrollPane. I want it centered. Also, when I zoom-in, it gets larger than the scrollpane. That is it goes beyond the boundaries of the JScrollpane. The function I am using to draw the image is:
Image img = imp.getImage();
               if (img!=null)
                    g.drawImage(img,0,0, (int)(srcRect.width*magnification), (int)(srcRect.height*magnification),
                    srcRect.x, srcRect.y, srcRect.x+srcRect.width, srcRect.y+srcRect.height, null);If I change the initial x,y values from (0,0) to any other value, it grays the upper left corner. So forinstance, if I did the following, the upper left corner of the scrollpane would become gray.
g.drawImage(img,100,200, (int)(srcRect.width*magnification), (int)(srcRect.height*magnification),
                    srcRect.x, srcRect.y, srcRect.x+srcRect.width, srcRect.y+srcRect.height,null);How can I center my image in the scrollpane?

When I zoom-in, I want the image to fill the entire jscrollpane. When I zoom out it returns to the original scaleSo why are you using a scroll pane? A scroll pane is used when its contents can potentially be larger than the scrollpane.
Although it wasn't originally designed for this purpose you can probably use my [Background Panel|http://www.camick.com/java/blog.html?name=background-panel]. It supports displaying an image at its actual size as well as scaled to fit the panel. So you should just be able to toggle the style as required.

Similar Messages

  • How can I draw an image in the browser using mouse

    I have to draw an image in the browser and have to store a file in the server and I don't know how can I do it. Is there anybody who konw it.

    Components other than applets cannot be downloaded into client machines
    unleess There is a Java Web Start kind of Mechanism present on client and the server also supports
    this .Hence your application is between Applet ---Xdownloadable ApplicationXX ---- traditinal Application

  • How do I get images to automatically center in a picture box?

    How do I get images to automatically center in a picture box (e.g. place a picture box on a master page and set it so that any image placed inside will automatically center, but not scale)? This was a simple procedure in CS5 (set "Fitting Options" to 'center' by clicking on the center box in the 9-box centering tool) but seems to have disappeared in CS6/CC. Am I missing something?

    Hi and thanks. Actually, my problem is with setting the properties of the image frame to 'align center' before an image is placed, allowing me to place large numbers of images and having them automatically center instead of me centering each one manually. Even when I create an object style the frame will not hold any alignment settings and apply them to the image being placed (unless some manner of scaling has been chosen, which is not something I want). There are work-arounds I have used but it would be nice to be able to just put a picture box on a master page, set it to align it's contents to the center and just be done with it . Thanks though.

  • How to draw an image on transparent JPanel?

    I want to draw an image on the transparent JPanel. How to do it?
    I do like this:
    ( In constructor )
    setOpaque(false);
    String imageName = "coral.jpg";
    iimage_Bg = Toolkit.getDefaultToolkit().getImage(imageName);
    ( In paintComponent( Graphics g ) )
    Graphics2D g2D = (Graphics2D) g;
    g2D.drawImage( iimage_Bg, 0, 0, getWidth() , getHeight() , Color.white, null );
    But it doesn't work. Please help me!
    Thank you very much.
    coral9527

    Check the values that are returned from getWidth() and getHeight(). If they either are zero, then paintComponent(Graphics g) never gets called by the components paint(Graphics g) method. I cannot see the how this component has been added or displayed so can give no advice on how you can guarantee getting a valid size. If you have simply added it to a JFrame and called pack(), the size will be zero, as the panel does not contain any components (you would not have this problem if you were adding a JLabel with an ImageIcon for example). Try not packing the frame, and giving it a valid size.

  • Drawing 2D Graphics in the center of a JPanel

    Hi,
    Below is my GUI. The basic idea is, I want this to create a neat UI on any machine with any monitor resolution settings. Because I dont really know what will be the resolution of the target machine, I do not perform a setPreferred size on any component. I have several problems here.
    1. My DiagramPanel.paintComponent method relies on the Panel's preferred size to draw a rectangle in the center of the panel. When a panel is layed out using BorderLayout, it expands it to fit the space. So is there some method I can use to know, what space the component panel is occupying (its dimension) ?
    2. Also, when the frame is maximized or resized, the DiagramPanel's dimension changes. So I want to be able to redraw the diagram in the new center position. How can I do this ?
    4. I am using the Frame size to be the screen dimension and set it to be maximized. So when I try to restore the window, it takes up the whole screen even the space including the windows taskbar. Is there someway to get the screen dimension leaving out the space for the taskbar ?
    3. I dont set the DividerLocation of the contentPane because, I want it to be set automatically based on the contents of the leftPanel. But when i print out the dividerLocation after creating the UI, it prints -1. How can I get the current divider location then ?
    import java.awt.BorderLayout;
    import java.awt.Button;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.LayoutManager;
    import java.awt.Toolkit;
    import java.awt.Graphics;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextArea;
    @SuppressWarnings("serial")
    public class MainFrame extends JFrame {
    public MainFrame() {
    createAndShowGUI();
    private void createAndShowGUI() {
    initMainFrame();
    initMenus();
    initPanels();
    initContentPane();
    setVisible(true);
    System.out.println("Divider location "+ contentPane.getDividerLocation());
    private void initMainFrame() {
    setTitle("Main Frame");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setState(JFrame.NORMAL);
    //GETS SCREEN SIZE
    Dimension screen_Dimension = Toolkit.getDefaultToolkit().getScreenSize();
    setSize(screen_Dimension.width, screen_Dimension.height);
    setExtendedState(MAXIMIZED_BOTH);
    private void initContentPane() {
    getContentPane().add(contentPane);
    contentPane.setEnabled(false); / *prevent the divider location from being moved* /
    contentPane.setLeftComponent(leftpanel);
    contentPane.setRightComponent(rightpanel);
    contentPane.setOpaque(true);
    private void initMenus() {
    exitMenu.setActionCommand(EXIT_COMMAND);
    file.add(exitMenu);
    menub.add(file);
    setJMenuBar(menub);
    private void initPanels() {
    initLeftPanel();
    initRightPanel();
    private void initLeftPanel() {
    leftpanel.setLayout(new FlowLayout(FlowLayout.CENTER));
    leftpanel.add(new Button("Click"));
    private void initRightPanel() {
    LayoutManager border = new BorderLayout();
    rightTab.setLayout(border);
    scrollingDiagram = new JScrollPane(diagramPanel);
    diagramDescriptionPanel.setLayout(new BorderLayout());
    diagramDescriptionPanel.add(diagDescTextArea, BorderLayout.CENTER);
    rightTab.add(scrollingDiagram, BorderLayout.CENTER);
    rightTab.add(diagramDescriptionPanel, BorderLayout.SOUTH);
    rightpanel.addTab("Right Tab", rightTab);
    public static void main(String args[]) {
    try {
    new MainFrame();
    } catch (Exception e) {
    e.printStackTrace();
    System.exit(0);
    private JSplitPane contentPane = new JSplitPane();
    private JMenuBar menub = new JMenuBar();
    private JMenu file = new JMenu("File");
    private JMenuItem exitMenu = new JMenuItem("Exit");
    private JPanel leftpanel = new JPanel();
    private JTabbedPane rightpanel = new JTabbedPane();
    private JPanel rightTab = new JPanel();
    private JScrollPane scrollingDiagram;
    private DiagramPanel diagramPanel = new DiagramPanel();
    private JPanel diagramDescriptionPanel = new JPanel();
    private JTextArea diagDescTextArea = new JTextArea(18, 45);
    public static final String EXIT_COMMAND = "Exit";
    @SuppressWarnings("serial")
    class DiagramPanel extends JPanel{
    public static int RECT_WIDTH = 100;
    public static int RECT_HEIGHT = 75;
    public void paintComponent(Graphics g) {
    super.paintComponents(g);
    Coordinates centerOfPanel = getCenterCoordinates();
    g.drawRoundRect(centerOfPanel.x, centerOfPanel.y, RECT_WIDTH, RECT_HEIGHT, 10, 10);
    public Coordinates getCenterCoordinates() {
    Dimension panelDimension = getPreferredSize();
    int x = (panelDimension.width - RECT_WIDTH) / 2;
    int y = (panelDimension.width - RECT_HEIGHT) / 2;
    return new Coordinates(x,y);
    class Coordinates {
    int x;
    int y;
    Coordinates(int x, int y) {
    this.x = x;
    this.y = y;

    Hi,
    The getSize worked perfectly for me. But what I tried doing now is that, instead of just the simple centering of the rectangle, i did this
    1. When the dimension of the rectangle is smaller than the Panel.getSize(), do centering as usual
    2. else when the rectangle is bigger, say because its width was longer than Panel.getSize().getWidth(), I center the rectangle only on its Height, and set the preferred size of the Panel to (rectangle.getWidth(), panel.getSize().getHeight()). And I call revalidate, so that the scrollbars appear.
    Problem im running into now is that, once I do a setPreferredSize, everytime I use a getSize later on, i always get the same size. But what I want to see is that, when the rectangle can fit in the panel, i want it centered without any scrollbars, but when it cannot fit on the width, i want it to appear centered on height, but have a horizontal scroll bar.
    I'd be really grateful, if you could help me with this.
    Here is the code
    public void paintComponent(Graphics g) {
              super.paintComponents(g);
              Coordinates centerOfPanel = getCenterCoordinates();
              g.drawRoundRect(centerOfPanel.x, centerOfPanel.y, RECT_WIDTH, RECT_HEIGHT, 10, 10);
              //preferredSize might have changed, call revalidate
              revalidate();
    public static final int PANEL_MARGIN = 50;
    public Coordinates getCenterCoordinates() {
              setPreferredSize(null);
              Dimension panelDimension = getSize();
              Dimension myPreferredSize = new Dimension();
              if (panelDimension.width > RECT_WIDTH)
                   myPreferredSize.width = panelDimension.width;
              else
                   myPreferredSize.width = RECT_WIDTH + 2 * PANEL_MARGIN; // MARGIN on left end and right end
              if (panelDimension.height > RECT_HEIGHT)
                   myPreferredSize.height = panelDimension.height;
              else
                   myPreferredSize.height = RECT_HEIGHT + 2 * PANEL_MARGIN; // MARGIN on top and bottom
              System.out.println("Panel size is " + getSize());
              setPreferredSize(myPreferredSize);
              System.out.println("Preferred size is " + myPreferredSize);
              //center of the panel.
              int x = (myPreferredSize.width - RECT_WIDTH) / 2;
              int y = (myPreferredSize.height - RECT_HEIGHT) / 2;
              return new Coordinates(x,y);
         }

  • How to have multiple images on the same screen? like in the movies where you see several actions at

    how to have multiple images on the same screen? like in the movies where you see several actions at the same time ....
    i don't find  a tutorial in adobe tv....
    thanks !!

    The short answer is that you'll put the source clip(s) for each inset on a different video track, all stacked up. Then use the Scale and Position effects (under "Motion" on the Effect Controls panel) to reduce their size and place them where you want.
    If the content of an inset will involve edited content (where you're cutting among various clips or just trimming out unwanted content from a single clip), then you'll probably find it easier to do all those edits in one sequence, then nest that sequence in the master sequence, where you apply the Scale and Positioning effects. That will save the step of applying the scale and position effects to each edited track item.

  • How to attach a text in the center of the Ellipse using JXML ?

    How to attach a text in the center of the Ellipse using JXML ? Can we use labelFor="$topEllipse" ?
    <StackPane fx:controller="myfxml.ArchiveLogsController" id="Login" xmlns:fx="http://javafx.com/fxml">
    <children>
    <AnchorPane>
    <!-- Prevent AnchorPane so that it's max = pref. This causes it to center in StackPane -->
    <maxWidth><Double fx:value="-Infinity"/></maxWidth>
    <maxHeight><Double fx:value="-Infinity"/></maxHeight>
    <children>
    <Ellipse fx:id="topEllipse" centerX="100" centerY="100" radiusX="50" radiusY="10" strokeWidth="2" stroke="#FF0000" style="-fx-fill: linear-gradient(to right, white 0%, red 100%);"/>
    *<Label fx:id="ArchLogs_lb" text="My Ellipse Label" />*
    </children>
    <properties>
    <backgroundColor>
    <Color blue="1.0" green="1.0" red="1.0" />
    </backgroundColor>
    <elementLockSel>
    <Boolean fx:value="true" />
    </elementLockSel>
    </properties>
    </AnchorPane>
    </children>
    </StackPane>

    I'd suggest putting the Ellipse and the Label in a StackPane.
    I wonder why so many people call it JXML?
    It is so strange - I guess the JXML name just seems more natural to some people, though I don't know why.
    I think Greg is right and that labelFor is not what you want:
    http://docs.oracle.com/javafx/2.0/api/javafx/scene/control/Label.html
    "Labels also are useful in that they can have mnemonics which, if used, will send focus to the Control listed as the target of the labelFor property . . . A Label can act as a label for a different Control or Node. This is used for Mnemonics and Accelerator parsing. This allows setting of the target Node."

  • How to draw horizontal line at the end of table for multiple line items

    Dear Experts,
                       Pls can anyone help me how to draw horizontal line at the end of table for multiple line items . kindly help me regarding this
    Thanks
    Ramesh Manoharan

    Hi
       I tried as per your logic but it is not solving my problem .  when i am gone to table painter it is showing line type 1 and line type 2
      is below format.. if u see here line type 1 bottom line and line type 2 top line both are same..  so how to avoid this ?
                              line type 1
                             line type 2

  • How to add a image in the DocSign example

    Hi,
    I am struggling to add a image to the DocSign example instead of text. If somebody could give me a few hints it would be much appretiated.
    I am currently modifying the CreateN2XObject function.
    My situation is as follows:
    I am drawing a image using the wxWidget library. From this a save the raw pixel data to a file. The pixel data is an array of unsigned chars where the first RGB triplet corresponds to the pixel first pixel of the first row, the second one to the second pixel of the first row and so on until the end of the first row; and so on...
    In the CreateN2XObject I create an ASStm to read this file.
    I create an attribute dictionary for this image
    And then a new cos stream from the ASStm and dictionary
    When I return from the function the plugin says that it is successfully signed, but I see nothing on the screen.
    When I open the 'signed' document in a text editor I see:
    <</Subtype/Form/Length 16038/Name/PROS/BitsPerComponent 8/Matrix[1.00011 0.0 0.0 1.00011 0.0000305176 0.0000305176]/ColorSpace/DeviceRGB/Width 54/Height 99/Type/XObject/BBox[0 76 238 0]/FormType 1>>stream
    the data in the file
    endstream
    Below is the code I use to make the image i.e. CreateN2XObject:
         DSAPXObjEntryRec signRec;
         memset(&signRec, 0, sizeof(DSAPXObjEntryRec));
         signRec.rect = *pBBoxRec;
         signRec.bDestroy = true;
         AVDevRect rcDev = { (int)ASFixedToFloat(pBBoxRec->left), (int)ASFixedToFloat(pBBoxRec->top), (int)ASFixedToFloat(pBBoxRec->right), (int)ASFixedToFloat(pBBoxRec->bottom) };
         const char* baseDirectory = "C:/temp/data";
         ASPathName exampleFilePathName = ASPathFromPlatformPath ((char*)baseDirectory);
         ASFile theFile;
         ASInt32 retVal = ASFileSysOpenFile(NULL,exampleFilePathName, ASFILE_READ, &theFile);
         int len = 16038;
         ASStm inStm = ASFileStmRdOpen(theFile,len);
         char tmpsize[255];
         sprintf(tmpsize,"%d",len);
         AVAlertNote("tmpsize");
         AVAlertNote(tmpsize);
         //sprintf_s(buf, 125, "1 0 0 RG %i %i m %i %i l S", rcDev.left, rcDev.top, rcDev.right, rcDev.bottom);
         //ASArraySize len = strlen(buf);
         //int len = 19758;
         //ASStm inStm = ASMemStmRdOpen(buf, len);
         CosObj attrDict = CosNewDict(cosDoc, false, 1);
         CosDictPutKeyString(attrDict, "Type", CosNewNameFromString(cosDoc, false, "XObject"));
         CosDictPutKeyString(attrDict, "Subtype", CosNewNameFromString(cosDoc, false, "Image"));
         CosDictPutKeyString(attrDict, "Width", CosNewInteger(cosDoc, false, 54));
         CosDictPutKeyString(attrDict, "Height", CosNewInteger(cosDoc, false, 99));
         CosDictPutKeyString(attrDict, "ColorSpace", CosNewNameFromString(cosDoc, false, "DeviceRGB"));
         CosDictPutKeyString(attrDict, "BitsPerComponent", CosNewInteger(cosDoc, false, 8));
         CosDictPutKeyString(attrDict, "Name", CosNewNameFromString(cosDoc, false, "PROS"));
         CosDictPutKeyString(attrDict, "Length", CosNewInteger(cosDoc, false, len));
         CosObj cBBoxObj = CosNewArray(cosDoc, false, 4);
         CosArrayInsert(cBBoxObj, 0, CosNewInteger(cosDoc, false, rcDev.left));
         CosArrayInsert(cBBoxObj, 1, CosNewInteger(cosDoc, false, rcDev.top));
         CosArrayInsert(cBBoxObj, 2, CosNewInteger(cosDoc, false, rcDev.right));
         CosArrayInsert(cBBoxObj, 3, CosNewInteger(cosDoc, false, rcDev.bottom));
         CosDictPutKeyString(attrDict, "BBox", cBBoxObj);
         AVAlertNote("Creating cos stream");
         CosObj cStmObj = CosNewStream(cosDoc, true, inStm, 0, true, attrDict, CosNewNull(), len);
         AVAlertNote("Finished creating cos stream");
         ASStmClose(inStm);
         signRec.xobj = cStmObj;
         AFPDWidgetBorderRec border;
         AFPDWidgetGetBorder(PDAnnotFromCosObj(sigAnnot), &border);
         AVAlertNote("Returning DigSigAPXObjectFromXObjList");
         return DigSigAPXObjectFromXObjList(cosDoc, pBBoxRec, &signRec, 0, 0, &border, kDSMerge);
    Regards,
    Magda

    Thanks!
    So, even though I am spesifically telling it to create an Image type with CosDictPutKeyString(attrDict, "Subtype", CosNewNameFromString(cosDoc, false, "Image"));
    I must still create a Form object around it?

  • In iPhoto, how can I export images with the metadata - including the title and caption information - intact as part of the image?

    In iPhoto, how can I export images with the metadata — including the title and caption information — intact as part of the image?

    Check those boxes in the export dialogue - Exporting From iPhoto
    LN

  • How see if material exist in the center?

    Hi gurus.
    Iam a abaper and I hene a problem.
    I am using  BAPI_SALESORDER_CREATEFROMDAT2 and ocurrs log error in txt file :
    The material 40000221 does not exist in the center CE52 / country BR
    How see if material exist in the center?(transaction ?table? )
    Thanks

    Being an ABAPer, you should be knowing in which tables a material would be stored than a functional guy.  Moreover, being an old member of the forum, you should be knowing forum rules where it has been clearly spelled out to post queries here after ensuring that you made efforts to search the forum.  So according to that, had you searched with that text ( material 40000221 does not exist in the center), you would have found lot of discussions happened on this topic.
    Coming to your query, you need to check first in MARA table whether the material is created or not.  Next in MVKE where the material has to be extended to Sales Area for which, the sale order is being created.
    G. Lakshmipathi

  • How do i copy images from the web?

    How do I copy images on the web for use in a powerpoint presentation?

    Drag them to the desktop or control-click them and choose to copy them to the clipboard.
    (61484)

  • How can i get rid of the cents in my account ?

    how can i get rid of the cents in my account ?

    If you want to change countries and can't spend it then you can try contacting iTunes support and ask them if they can remove the balance so that you can do so : http://www.apple.com/support/itunes/contact/- click on Contact iTunes Store Support on the right-hand side of the page, then Purchases, Billing & Redemption

  • Can't show image in the center of the jscrollpane ,any one can help

    i write a program to show image in the jscrollpane
    i create a class called ImageLabel (it extends jlabel) then i use
    ImageLabel im=new ImageLabel(imageicon)
    jscrollpane.setViewportView(im);
    validate();
    repaint();
    but it show the image in the left and top corner of the jscrollpane ,not in the center of the jscrollpane
    then i change the ImageLabel to JLabel ,:
    JLabel im=new JLabel(imageicon);
    jscrollpane.setViewportView(im);
    validate();
    repaint();
    it shows the image in the center of the jscrollpane,
    but i want to use ImageLabel not jlabel
    whats the problem ,any one can help me ,thank you:)

    the ZoomLabel is the imagelabel ,and my complete code as follows:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    class ZoomLabel extends JLabel
        private ImageIcon icImage;   
        private int ph,pw,picW,picH;    
        ZoomLabel(ImageIcon ic)   
            super(ic, JLabel.CENTER); 
            icImage = ic;
            pw = picW = ic.getIconWidth(); 
            ph = picH = ic.getIconHeight();
           setSize(pw,ph);
           setPreferredSize(new Dimension(pw,ph));
           repaint();
          validate();
           public void zoom(float scale)    
               ph = Math.round(picH * scale);         
               pw = Math.round(picW * scale);          
               setPreferredSize(new Dimension(pw,ph)); 
               repaint();
             public void paint(Graphics g)     
                     update(g);     
                public synchronized void update(Graphics g)     
                {             g.drawImage(icImage.getImage(),0,0,pw,ph,this); 
      public class ImageShow extends JFrame
                  ImageShow()
                 ImageIcon ii=new ImageIcon("e:/download/pic/me1.JPG");
                   JScrollPane js=new JScrollPane();
                   zl=new ZoomLabel(ii);
                  js.setViewportView(zl);
                  getContentPane().add(js,"Center");
                     js.repaint();
                                  js.validate();
                  pack();
                  setVisible(true);     
             public  static void main(String[] args)
                   new ImageShow();
             ZoomLabel zl;
        }

  • How to apply an image to the back face of another?

    I am only fairly new to motion but am, learning fast. I'm wondering if someone can tell me how to apply an image to the back face of another image?
    I'm trying to animate a brochure opening and want to apply the front cover as the back face to the page I'm opening to (each page is a separate .pdf file). I know this can be done easily rather than animating them as 2 separate objects, i just can't remember how to do it.

    Thanks Mark. That is how I will do it if there isn't a simpler way. I could have sworn i have seen the option to allocate an image as the back face to another image. So when it animates, you automatically see the other image on the reverse side?

Maybe you are looking for