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);
     }

Similar Messages

  • How to place a JPanel at the center of another JPanel?

    Can anyone tell me how to place a JPanel inside another JPanel? The first JPanel consists of three JPanels each consisting of a label&textfield and are placed using BoxLayout. The second JPanel is a big blank screen. So, i would like to put the first JPanel at the center of second JPanel(horizontally & vertically). The problem is that i don't have any other component. So,if i try to use FlowLayout, i am able to put it at the center(horizontally, not vertically) only on the top edge. I tried to use BoxLayout. But, i couldn't(as i don't have any other elements). I tried to create some blank elements. But, they are messing up the elements of my JPanel. Any cluesssssssss??????????

    import java.awt.*;
    import javax.swing.*;
    public class CenteredLayout
        private JPanel getPanel()
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            JPanel p = new JPanel(gridbag);
            addComponents(new JLabel("label 1"), new JTextField(8), p, gbc);
            addComponents(new JLabel("label 2"), new JTextField(8), p, gbc);
            addComponents(new JLabel("label 3"), new JTextField(8), p, gbc);
            JPanel panel = new JPanel(gridbag);
            panel.setBackground(Color.pink);
            gbc.anchor = GridBagConstraints.CENTER;
            gbc.insets = new Insets(0,0,0,0);
            panel.add(p, gbc);
            return panel;
        private void addComponents(Component c1, Component c2, Container c,
                                   GridBagConstraints gbc)
            gbc.anchor = GridBagConstraints.EAST;
            gbc.gridwidth = GridBagConstraints.RELATIVE;
            c.add(c1, gbc);
            gbc.anchor = GridBagConstraints.WEST;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            c.add(c2, gbc);
        public static void main(String[] args)
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new CenteredLayout().getPanel());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • 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.

  • Drawing 2D graphics with no frame or no panel ?

    Hi,
    I would like to know if it is possible to draw 2D graphics directly over the OS(windows2002) ? like drawing a rectangle over the desktop without any JPanel or JFrame.
    cheers,
    sletourne

    It is possible, I've done it ;-)
    import java.awt.*;
    import java.awt.event.*;
    public class JustSomething implements WindowListener
         public static void main(String args[])
              new JustSomething();
         public JustSomething()
              Frame winf = new Frame();
              winf.setLocation(2000,2000);
              winf.add(new java.awt.Label("If you see this you have a mighty big screen"));
              Window win = new Window(winf);          
              win.setSize(width,height);
              winf.addWindowListener(this);
         public void windowOpened(WindowEvent windowevent){}
         public void windowClosing(WindowEvent windowevent){}
         public void windowClosed(WindowEvent windowevent){}
         public void windowIconified(WindowEvent windowevent){}
         public void windowDeiconified(WindowEvent windowevent){}
         public void windowActivated(WindowEvent windowevent){}
         public void windowDeactivated(WindowEvent windowevent){}

  • Need help on drawing multiple squares on the screen

    I am working on a project for aircraft seating and what i have to do is create square on the screen as seat. I got to draw 180 squares on the screen and it sounds easy but i have been stuck at it for about 10 days now my superviser doesn't know java so he can't help me on what i should do next and java superviser's told me they have no time to see me so if anyone here can help to guide me where i am goin wrong or how i should do it would be very helpful. Here is the code i have so far i think i am maybe close to gettin it working but then again i could be far off.
    import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Seating extends JFrame {
        private JPanel boardPanel;
        private JPanel panel2;
        private Square board[][];
        public Seating() {
            boardPanel = new JPanel();
            boardPanel.setLayout(new GridLayout(6,30,0,0));
            //create board
            board = new Square[6][30];
            //rows in the board
           for(int row = 0; row < board.length; row++)
               //column on the board
                for(int column = 0; column < board[row].length; column++)
                    //create square
                    board[row][column] = new Square(' ', 3 * row + column);
                    //add square
                    boardPanel.add(board[row][column]);
                panel2 = new JPanel();
                panel2.add(boardPanel, BorderLayout.CENTER);
                add(panel2, BorderLayout.CENTER);
                setSize(2000,1500);
                setVisible(true);
                 private class Square extends JPanel
                    public Dimension getPreferedSize()
                      return new Dimension(20,20);
                    public Dimension getMinimumSize()
                        return getPreferedSize();
                    public void paintComponent(Graphics g)
                        super.paintComponents(g);
                        g.drawRect(0, 0, 19, 19);
    }

    Yeah I'd make a Seat class, subclassing JLabel, and then add some business logic to them to reflect that. For example, if they're already booked, given them a different color and disable clicks on them. If they're bookable, add a mouse click listener. Maybe I'd make different subclasses of Seat for those different roles. I'd add them all to the grid, but also add them to a Map indexed by seat name or something so I could find them and update them as needed.

  • Loading Images/Having images load at the center of a JFrame with random col

    Hey Guys,
    I was wondering how could i go about loading images two at a time for instance have two circle images load at the center of a J Frame connected to each other and also each time the J Frame is executed the circles are different colors. Ive posted this question before and have posted it on another forum but i have not gotten any help. I looked into using media tracker and the Random command but i am still not if these are the proper solution to my problem. Id appreciate any help if this post doesn't make sense let me know i will try and clarify better. Thanks in advance

    Ah alright then so what i have to far is i have an image load to my J Frame/J Panel and after it loads it starts to fall like a tetris block and i am able to move it left and right. When the image loads it loads to the default coordinates of 0,0 the left hand top corner. What i want to do it when i run my application the image loads at the center of the J Frame/J Panel but also have another block connected to it when it loads. So basically i have loaded four separate different images and want them to load to my J Frame/ J Panel two at a time side by side like tetris and puyo puyo smashed together here is my code sorry its hard for me to explain it for some reason hope this makes more sense.
    import javax.swing.*;
    import java.awt.*;
    public class DemoTest extends JPanel {
         public DemoTest() {
            add(new BlockPanel());
        public static void main(String[] args) { {
        JFrame frame = new JFrame("Tetris");
        frame.setContentPane(new BlockPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200,500);
        frame.setResizable(false);
        frame.setVisible(true);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class BlockAnimation extends JPanel {
      public static final int numDroppingBlocks=2;
      private static final int MAX_X = 200;
      private static final int MAX_Y = 430;
      private static final int DELTA_Y = 2;
      private static final int TIMER_DELAY = 20;
       // Declare name's for the Image object.
       Image image[];
       Timer pptimer;
       boolean right,left;
       int X = 0;
       int x = 32;
       int y;
    public BlockAnimation() {
          super();
          //Load an image file into the Image object. This file has to be in the same folder
          image = new Image[4];
          image[0] = Toolkit.getDefaultToolkit().getImage("block_yellow.png");
          image[1] = Toolkit.getDefaultToolkit().getImage("block_blue.png");
          image[2] = Toolkit.getDefaultToolkit().getImage("block_green.png");
          image[3] = Toolkit.getDefaultToolkit().getImage("block_red.png");
        //image5 = Toolkit.getDefaultToolkit().getImage("DeathNote1.jpg");
          setFocusable(true);
          BlockMove block_move = new BlockMove(); // Make a new video game KeyListener
          addKeyListener(block_move);
          //setBackground(Color.BLACK);
          pptimer = new Timer(TIMER_DELAY, new TimerAction());
          pptimer.start();
            public void setAnimation(boolean OnandOff) {
            if (OnandOff) {
                pptimer.start(); 
            } else {
                pptimer.stop(); 
            public void paintComponent(Graphics g) {
             super.paintComponent(g); 
             // draw the "stop" line for the animation
             g.setColor(Color.black);
             g.drawLine(0, MAX_Y, getWidth(), MAX_Y);
                // Draw our Image object.
           g.drawImage(image[0],X,y,this);
             if(right) // Move the block to the right
                   X++;
                   if(left) // Move the block to the left
                  X--;
                 repaint();
         private class BlockMove implements KeyListener {
         public void keyTyped(KeyEvent e){}
          public void keyReleased(KeyEvent e)
           if(e.getKeyCode() == e.VK_RIGHT)
            right = false;
            if(e.getKeyCode() == e.VK_LEFT)
              left = false;
                   public void  keyPressed(KeyEvent e)
                  if(e.getKeyCode() == e.VK_RIGHT)
                             right = true;
                        if(e.getKeyCode() == e.VK_LEFT)
                             left = true;
            class TimerAction implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                 y += DELTA_Y;
                if (y + x  >= MAX_Y) {
                setAnimation(false);
    }//end class
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class BlockPanel extends JPanel {
       BlockAnimation pa;  
        BlockPanel() {
            pa = new BlockAnimation();       
            JButton startButton = new JButton("Start");       
            JButton stopButton  = new JButton("Stop");
            startButton.addActionListener(new Start());
            stopButton.addActionListener(new Stop());
            JPanel button = new JPanel();
            button.setLayout(new FlowLayout());
            button.add(startButton);
            button.add(stopButton);
            this.setLayout(new BorderLayout());
            this.add(button, BorderLayout.SOUTH);
            this.add(pa,BorderLayout.CENTER);
        class Start implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                pa.setAnimation(true);
        class Stop implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                pa.setAnimation(false);
    }//endclass Edited by: Riz01 on Sep 14, 2009 2:34 PM

  • How to print the JFrame In The Center Of The Page?

    hi there in the following code iam trying to print a JFrame
    but the frame appear in the printed page at the top left
    and i want it to appear in the top center of the page
    how to do that?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.print.*;
    class PrintUIWindow implements Printable, ActionListener {
        JFrame frameToPrint;
        public int print(Graphics g, PageFormat pf, int page) throws
                                                            PrinterException {
            if (page > 0) {
                return NO_SUCH_PAGE;
            Graphics2D g2d = (Graphics2D)g;
            g2d.translate(pf.getImageableX(), pf.getImageableY()-55);
            frameToPrint.print(g);
            return PAGE_EXISTS;
        public void actionPerformed(ActionEvent e) {
             PrinterJob job = PrinterJob.getPrinterJob();
             job.setPrintable(this);
             boolean ok = job.printDialog();
             if (ok) {
                 try {
                      job.print();
                 } catch (PrinterException ex) {
        public PrintUIWindow(JFrame f) {
            frameToPrint = f;
        public static void main(String args[]) {
            UIManager.put("swing.boldMetal", Boolean.FALSE);
            JFrame f = new JFrame("Print UI Example");
            f.addWindowListener(new WindowAdapter() {
               public void windowClosing(WindowEvent e) {System.exit(0);}
            JLabel label1=new JLabel("Selling Bill",JLabel.CENTER);
            JLabel label2=new JLabel("Customer Name :Mahmoud Saleh       ",JLabel.LEFT);
            JLabel label3=new JLabel("Buying Date :29/8/2008             ",JLabel.LEFT);
            JLabel label4=new JLabel("Book Buyed :Java Printing          ",JLabel.LEFT);
            JLabel label5=new JLabel("Number : 6 Copies                  ",JLabel.LEFT);
            JLabel label6=new JLabel("Total Price :600 $                 ",JLabel.LEFT);
            label1.setFont(new Font("Courier New", Font.BOLD, 13));
            label2.setFont(new Font("Courier New", Font.BOLD, 13));
            label3.setFont(new Font("Courier New", Font.BOLD, 13));
            label4.setFont(new Font("Courier New", Font.BOLD, 13));
            label5.setFont(new Font("Courier New", Font.BOLD, 13));
            label6.setFont(new Font("Courier New", Font.BOLD, 13));
            JButton printButton = new JButton("Print This Window");
            printButton.addActionListener(new PrintUIWindow(f));               
            JPanel panel=new JPanel();
            panel.setLayout(new GridLayout(6,1));
            panel.add(label1);
            panel.add(label2);
            panel.add(label3);
            panel.add(label4);
            panel.add(label5);
            panel.add(label6);
            f.setSize(300,300);       
            f.setLocationRelativeTo(null);       
            f.add(panel,BorderLayout.CENTER);
            f.add(printButton,BorderLayout.SOUTH);
            panel.setBackground(Color.WHITE);
            f.setResizable(false);
            f.setVisible(true);
    }

    First_knight wrote:
    please tell me am i thinking right
    about this method: setImageableArea(.....)
    public void setImageableArea(double x, double y,  double width, double height);
    like I said, I've tried this method and it doesn't seem to do anything.
    the width=the JFrame Width,the height=the JFrame Height right?actually, when printing, 72 points (printing version of pixels) = 1 inch, so to do WYSIWYG, you need width = JFrameWidth * 72.0 / Toolkit.getToolkit().getScreenResolution. Ditto with height
    upper left beginningx(0)---------------------------200--------------------------------600-----------------------------------y(1000)upper right beginningyou need to do something like PageSetup.getImageableX and do Graphics.translate(x,y);
    also, if your page width = 720, that = 10 inches - that's a wide page (unless its in landscape)
    so if i want the JFrame To Be In The Center Of The Page I Would Choose From x=200 ,y=600 depending that frame width is 400Actually, it would be 300 - 700 in your example
    Because when i tried to use:setImageableArea(200, 600,  400, 200);like the above code
    no changes occurs in the printed paperYes. You need to offset the Graphics object

  • Zooming into the center of an image

    Hi, I have this code that allows the user to zoom into an image that they have selected. However, when the image is zoomed into using the slider, it goes towards the top left corner of the image rather than the center. How can I modify my code to zoom into the center of the image instead?
    import java.awt.*;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.event.*;
    public class MapScale extends JPanel
         BufferedImage image;
         double scale = 1.0;
         public MapScale(BufferedImage image)
              this.image = image;
         protected void paintComponent(Graphics g)
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D)g;
              g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
              double x = (getWidth() - scale*image.getWidth())/2;
              double y = (getHeight() - scale*image.getHeight())/2;
              AffineTransform at = AffineTransform.getTranslateInstance(x,y);
              at.scale(scale, scale);
              g2.drawRenderedImage(image, at);
         public Dimension getPreferredSize()
              int w = (int)(scale*image.getWidth());
              int h = (int)(scale*image.getHeight());
              return new Dimension(w, h);
         private JSlider getSlider()
              int min = 1, max = 36;
              final JSlider slider = new JSlider(min, max, 16);
              slider.setMajorTickSpacing(5);
              slider.setMinorTickSpacing(1);
              slider.setPaintTicks(true);
              slider.setSnapToTicks(true);
              slider.setPaintLabels(true);
              slider.addChangeListener(new ChangeListener()
                   public void stateChanged(ChangeEvent e)
                        int value = slider.getValue();
                        scale = (value+4)/20.0;
                        revalidate();
                        repaint();
              return slider;
         public static void main(String[] args) throws IOException
              JFileChooser selectImage = new JFileChooser();
              if (selectImage.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
                   String path = selectImage.getSelectedFile().getAbsolutePath();
                   BufferedImage image = ImageIO.read(new File(path));
                   MapScale test = new MapScale(image);
                   JFrame f = new JFrame();
                   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   f.getContentPane().add(new JScrollPane(test));
                   f.getContentPane().add(test.getSlider(), "Last");
                   f.setSize(400,400);
                   f.setLocation(200,200);
                   f.setVisible(true);
    }

    KGCeltsGev wrote:
    Hi, I have this code that allows the user to zoom into an image that they have selected. However, when the image is zoomed into using the slider, it goes towards the top left corner of the image rather than the center. How can I modify my code to zoom into the center of the image instead?Since you use a JScrollPane and change the client size when you zoom in/out you need to scroll to the center every time you zoom in/out.
    This is done by using scrollRectToVisible.
    slider.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            int value = slider.getValue();
            scale = (value+4)/20.0;
            revalidate();     
            Dimension d = getPreferredSize();
            Dimension extentSize = ((JViewport) getParent()).getExtentSize();
            scrollRectToVisible(new Rectangle((d.width-extentSize.width)/2, (d.height-extentSize.height)/2, extentSize.width, extentSize.height));
    });

  • Appleworks6 (drawing - text & graphics) to be converted - how?

    I have a lot of mathematics worksheets, produced on Appleworks6 (on the drawing package with text and graphics) over the years. The new OS will not support Rosetta, I understand, and so I need to transfer (translate?) all the worksheets into a more modern format, available to both Mac and PC users. How do I do this and what applications are now available which will be suitable? If I try Word:mac (11.6.3) it tells me the Appleworks6 drawing document is not the right file type.

    If it were an AW6 text document with inserted graphics, then Pages would probably open it.
    However, as a drawing document with text added that may not work. It is possible that Keynote might be able to open it.
    Edit - - nope - just tried it with Keyboate, won't do it.
    Just played with AW6 a bit. If these documents are static docs, meaning ones which do not need to be changed or otherwise addressed except viewed, there's other choices. One I tried just now in AW6, ws to do a Save As and change the format to JPEG.
    This resulted in a document that should be openable by most anyone. In OS X, it opens in Preview automatically, but should be able to be opened in any app that can open JPEG files.
    In Pages it got a bit trickier - Pages would not open it directly, not even via Open in File menu. But, when I treated it as a regular JPEG it worked: I opened a blank text doc in Pages, then drag-and-dropped the JPEG file into it. That worked - gave me a Pages doc with an inserted image of the original AW6 graphics file.

  • How do I disable being able to select the center of shapes (no fill)?

    I have "Object Selection By Path Only" option enabled. Yet, I am still able to select the center of a hollow shape. This is very frustrating when attempting to marquee select objects over/inside hollow shapes and having selected larger shapes by accident. This is new behavior compared to older versions of Ai and is jarringly unexpected. If anyone could please enlighten me, it would be a huge help. Thanks!

    Beautiful! Thank you! So glad that the center still appears when attempting to draw and snap to it. Works perfect .

  • Listing Graphics in the TOC...?

    Hello-
    I am very new to FrameMaker and have only been working with it for a few weeks now.
    My company is using FrameMaker 10 to create a User Manual for one of our products.  This is a large PDF document with multiple chapters.  We are creating each chapter as a separate FrameMaker document and then compiling the entire group of chapter documents into a book with a table of contents (TOC) when creating the final version of the PDF.  We are, however, having a problem with the creation of the TOC which can be better explained via the figure below.
    The first page of each chapter has a banner graphic (portable network graphic) across the top of it which has the chapter number and the subject of the chapter as text within the graphic itself.  Since this information is part of the graphic itself, it is not being detected by FrameMaker when the TOC is being generated and is therefore not being included in the TOC of the User Manual PDF.
    The Paragraph and Sub-Paragraph text IS detected and listed in the TOC.  However, since the chapter title is only represented in the PDF with a graphic, the TOC will skip from listing the last Sub-Paragraph title of the previous chapter and then jump directly to the first Paragraph title of the next chapter.
    Question:
    How can we continue to represent our chapter titles with graphics (preferred by management) but somehow have the beginning of a new chapter and its title represented in the TOC when the PDF is generated?

    Remember, there are two types of text frames. If you ctrl+click to
    select the small frame you are using on the master page, then
    right-click and choose Object Properties, you can tell that the frame
    you are using is a background frame by looking in the "Tag" field (which
    will be empty). When the Tag field is empty, the text frame is a
    background text frame. Any content put in such a frame WILL show up on
    the body page, but if I remember right, it will NOT show up in TOCs.
    If you ctrl+click to select the large text frame on the master page, and
    then right-click and select Object Properties, you will see that there
    is probably a Tag setting of "A." This means that this frame is in flow
    A on the body page. Type text in that frame and you will see that it
    does NOT show up on the body page. Text frames with a flow tag are
    merely placeholder frames for the body page. And content placed into the
    text frame on a body page CAN be picked up by the TOC.
    Since it appears that your goal is to make that graphic wider than the
    main text frame, it looks like you want to do something a little
    different than what you first showed as an example and what I described.
    Try this:
    1. Create a new master page (Special> Add Master Page). A dialog box
    will pop up. Since this is going to be the first page in a chapter and
    is unique in style from typical right and left pages, name it First and
    choose an "Initial Page Layout" of "Empty." (Don't use the Left or Right
    master pages for custom master pages as they are the pages FM
    automatically inserts when you type enough text to require
    autogeneration of a new page. You can, of course, alter the design of
    Left and Right master pages if you want.)
    2. Using the graphics toolbar (View> Toolbars> Graphics Toolbar ), click on the Text Frame Tool and then draw a text
    box on your new "First" master page. Make it big enough to hold your
    chapter graphic. A dialog will pop up. Choose "Template for Body Page
    Text Frame" with a Flow Tag of A. Click the Add button. You now have one
    text frame on your page. (You probably noticed that the other choice was
    to set the frame for "Background Text," which is not what we want this
    time.)
    3.  Since you want the text frame for your main text to be narrower, we
    will now draw a second, narrower text frame on the same page. So click
    on the Text Frame Tool again, and draw a second text frame on the page
    at the size you want. A dialog box will pop up. Again, choose the
    "Template for Body Page Text Frame" with a Flow Tag of A. Click the Add
    button. A notification should pop up that "The new text frame has been
    connected to the end of flow A." This means that, though there are now
    two boxes on your screen, they flow as one. There should be a section
    sign in the upper left corner of the first frame, but nothing in the
    second frame.* When you type enough text into the first frame, it will
    flow into the second frame automatically. (Remember, though, we are
    working on a master page. You will insert your actual content on a BODY
    page. So don't put anything in the text frames now.)
    If there is a section marker in both frames, something went a little
    wrong, but can be fixed. Ctrl-click the first frame, then ctrl-click the
    second frame. Both should be selected. Then choose Format> Customize
    Layout> Connect Text Frames and the second section marker should disappear.
    4. View> Body Pages to move back to the body page. Since this is the
    first page in the book and content has not been added, you should be
    seeing a Right page. So use Format> Page Layout> Master Page Usage and
    choose Custom and First to assign your new master page format to this
    page. Click Apply.
    5. Now you can type your chapter title into the first text frame and
    assign your ChapterTitle paragraph format to it. Make sure the "Space
    Below" setting for the format in the Paragraph Designer is large enough
    that, when you press a carriage return at the end of the line, it moves
    that section marker down into the second text frame.
    6. Now you can import your graphic. Click OUTSIDE** the text frames and
    choose File> Import> File, then locate your graphic and click the Import
    button. The graphic will appear in the middle of the page. Click and
    drag it to where you want, to where it will cover the chapter title that
    you typed. You may be done, but if you can still see the chapter title
    that you typed, there is one more step. (Because the graphic ended up
    behind the type instead of on top of it.) With the graphic still
    selected, choose Graphics> Bring to Front. Done!
    **When importing the graphic for this step, it is important not to click
    within the text frame before you import the graphic because that will
    place the graphic in an anchored frame and it will be harder to get it
    to hide the typed text. The method I described makes the graphic float
    on the page as a separate entity, a bit like stuff put in a background
    text frame on the master page. Note also that this technique doesn't
    usually work elsewhere in a document, since you usually want a graphic
    to move along with associated text, when more text is added. The method
    I described above does not allow the graphic to shift.
    7. Any further text you type should appear in the second text frame, and
    should autoconnect with additional pages as they are created.
    8. Now, you can assign (Format> Page Layout> Master Page Usage) this
    "First" master page design to the first page in each new chapter you
    write. (You can use File> Import> Formats to pull master page formats
    from one document to another.)
    You know, when I first started out with FrameMaker, I banged my head for
    a few days-- especially before I found this group. Then I started
    getting aha! moments all over the place and it became clear that FM has
    a very logical design and is a wonderful program. It is not, however, as
    flexible at positioning graphics as InDesign.
    Anyway, I hope those steps will get you started.

  • Drawing a Graphics object on a Graphics object

    Is there anyway to draw a Graphics object on another Graphics object? I'm trying to show 2 screens, side by side, on a Canvas and I'm trying to cheat a little :-P Basically, I want to take half of one screen and half of another and put them on top of each other to form one screen.
    OR is there a way to turn a Graphics object into an Image object?

    I'm not sure if this is what you're after, but you can
    - create an offscreen image using "createImage(int width, int height)" method of a Component , then
    - obtain the graphics context of the offscreen image using "getGraphics()",
    - you can then draw onto the offscreen image using the graphics context.
    hope that helps. =)

  • Can somebody help me out? I need a Corel Draw (.cdr) graphic converted to Illustrator

    I'm trying to get a logo from brandsoftheworld.com but the one I want is in .CDR. I don't have Corel Draw (who does anymore) but I see that Illustrator 6 can open it. Unfortunately, I'm still on CS5.5. Can somebody help me out?

    Send it to me. I'll save it as an EPS file for you.
    Bob AT theindesignguy DOT com
    TwitchOSX <mailto:[email protected]>
    Thursday, January 24, 2013 7:11 PM
    >
          Can somebody help me out? I need a Corel Draw (.cdr) graphic
          converted to Illustrator
    created by TwitchOSX <http://forums.adobe.com/people/TwitchOSX> in
    /InDesign/ - View the full discussion
    <http://forums.adobe.com/message/5020999#5020999

  • Draw a square with the cursor

    i would like to draw a square with the movement of the coursor, while its left button is clicked and the cursor is over an image.
    when i leave of pushing the right button the square have to dissapear.
    if you don't understand, it's the same in windows when you click the left button and square appears.
    My question is how can i do this?
    thanks

    Not sure I completely understand the question, but maybe this will give you an idea:
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class DrawSquare extends JPanel
         Point startPoint = null;
         Point endPoint = null;
         public DrawSquare()
              setPreferredSize(new Dimension(500,500));
              MyMouseListener ml = new MyMouseListener();
              addMouseListener(ml);
              addMouseMotionListener(ml);
              setBackground(Color.white);
         public void paintComponent(Graphics g)
              // automatically called when repaint
              super.paintComponent(g);
              g.setColor(Color.black);
              if (startPoint != null && endPoint != null)
                   // draw the current dragged line
                   int x = Math.min(startPoint.x, endPoint.x);
                   int y = Math.min(startPoint.y, endPoint.y);
                   int width = Math.abs(endPoint.x - startPoint.x);
                   int height = Math.abs(endPoint.y - startPoint.y);
                   g.drawRect(x, y, width, height);
         class MyMouseListener extends MouseInputAdapter
              public void mousePressed(MouseEvent e)
                   if (SwingUtilities.isLeftMouseButton(e))
                        startPoint = e.getPoint();
                        repaint();
              public void mouseReleased(MouseEvent e)
                   if (SwingUtilities.isLeftMouseButton(e))
                        startPoint = null;
                        endPoint = null;
    //                    repaint();
              public void mouseDragged(MouseEvent e)
                   if (SwingUtilities.isLeftMouseButton(e))
                        endPoint = e.getPoint();
                        repaint();
         public static void main(String[] args)
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              DrawSquare d = new DrawSquare();
              frame.getContentPane().add( d );
              frame.pack();
              frame.setVisible(true);
    }

  • 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;
        }

Maybe you are looking for