Positioning a JFrame on the center!!

how do i posiiton a JFrame on the center of a screen???

this is a method for centering the frame in the middle. Have a look at it
  private void centerFrame () {
    //Center the window
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize = this.getSize();
    if (frameSize.height > screenSize.height) {
      frameSize.height = screenSize.height;
    if (frameSize.width > screenSize.width) {
      frameSize.width = screenSize.width;
    this.setLocation( (screenSize.width - frameSize.width) / 2,
                     (screenSize.height - frameSize.height) / 2);
    this.setVisible(true);
  }

Similar Messages

  • 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

  • Positioning a symbol at the center AND bottom of stage

    hi there,
    maybe this is a simple question, i hope so...
    i need to place a symbol at the center AND the bottom of a responsive site (stage height/width = 100%). the size of the symbol is fixed and should NOT change when resizing the browser window.
    for better understanding i created this fantastic visual:
    thanks for your help!

    ok, i found out how to do it, it's quite simple... so anyone who needs a sticky footer may need this...
    project files:
    https://www.dropbox.com/s/f53kpr808ofmsr6/footer.zip
    best wishes to all of you

  • How to display a region in the center of the page

    Hi,
    I am trying to position a region in the center of the page and I am using the following in the region attributes field
    style="width:70%; region = "center";"
    but the region is positioned to the left only. Is there any other method to do this work.
    Please help me out.
    Thanks,
    Rik
    Edited by: Rik281 on Nov 17, 2010 7:31 AM

    Before posting, please TRY and do a search on the forum, you MIGHT find your question already asked and ANSWERED..: place a reports region on center of the page
    Thank you,
    Tony Miller
    Webster, TX
    On the road of life...There are 'windshields', and there are 'bugs'
    (splat!)
    "Squeegees Wanted"

  • ParallelCamera - how to position the origin at the center?

    When defining a ParallelCamera, I would like the ability to position the origin at the center of the scene, the way PerspectiveCamera does it, instead of the upper-left corner of the scene.
    Also, when I have a ParallelCamera and I call setScaleX, setScaleY, and setScaleZ (or their property-binding equivalents) with scale factors greater than 1, it seems to make the 3D elements smaller, instead of larger as I would expect.  Is there a reason for this?
    Thanks.

    Murugesh,
    I believe that you have mis-read Gabriel's problem.
    Gabriel,
    The cursor is not positioning at the base of the editor as you have cited.
    In order to get this functionality to work, you must set the LINE_EDITOR import paramter to 'X'.
    data: hdr like THEAD.
    data: l_itced like itced.
      hdr-tdobject = 'VBBP'.
      hdr-tdname = '4000029521000030'.
      hdr-tdid = 'Z005'.
      hdr-tdspras = 'E'.
      hdr-TDLINESIZE = '100'.
      hdr-TDTXTLINES = '3'.
      l_itced-SCROLLEND = 'X'.
      CALL FUNCTION 'EDIT_TEXT'
        EXPORTING
        DISPLAY             = ' '
        EDITOR_TITLE        = ' '
          HEADER              = hdr
        PAGE                = ' '
        WINDOW              = ' '
        SAVE                = 'X'
          LINE_EDITOR         = 'X'   " here !!!
          CONTROL             = l_itced
        PROGRAM             = ' '
        LOCAL_CAT           = ' '
      IMPORTING
        FUNCTION            =
        NEWHEADER           =
        RESULT              =
        TABLES
          LINES               = lines
      EXCEPTIONS
        ID                  = 1
        LANGUAGE            = 2
        LINESIZE            = 3
        NAME                = 4
        OBJECT              = 5
        TEXTFORMAT          = 6
        COMMUNICATION       = 7
        OTHERS              = 8
    Don't forget those points !!

  • How do you position text in a div tag to be in the center vertically?

    Can someone help?  I am struggling to convert from being dependent on tables to design sites to using all css and divs.  Anyway, in my practice file, i made a header that is styled to be 50 pixels tall.  The type in the header goes to the top.  I am used to having type default to to the left and positioned vertically in the center they way type "works" when placed in a <td>. What am I not "getting?" I would like to know that if I change the css for the header region from 50 to another value that the type will always be positioned where I want it. 
    thanks in advance for any suggestions.  Maybe the picture I've attached will better explain what I'm talking about. Oh, and I've also attached the html file

    HudsonSwimmer wrote:
    Can someone help?  I am struggling to convert from being dependent on tables to design sites to using all css and divs.  Anyway, in my practice file, i made a header that is styled to be 50 pixels tall.  The type in the header goes to the top.  I am used to having type default to to the left and positioned vertically in the center they way type "works" when placed in a <td>. What am I not "getting?" I would like to know that if I change the css for the header region from 50 to another value that the type will always be positioned where I want it. 
    thanks in advance for any suggestions.  Maybe the picture I've attached will better explain what I'm talking about. Oh, and I've also attached the html file
    I'm afraid you'll have to starting looking at things differently. Css cannot yet vertically centre anything in a <div> container reliably.
    About as good as it gets is one line of text (see code below) using the line-height attribute AND you need to give the <div> a height too which is also likely to lead to other problems. So forget it. You can use padding and margin to push it into a 'visual position vertically centered' in your browser but there is no guarantee that others with different browser set ups will be seeing it the same.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Untitled Document</title>
    <style type="text/css">
    #vertCentre {
    height: 300px;
    background-color:#FF0;
    line-height: 300px;
    text-align: center;
    p {
    font-family: verdana, helvetica, arial, sans-serif;
    font-size: 12px;
    margin: 0;
    padding: 0;
    </style>
    </head>
    <body>
    <div id="vertCentre"><p>This is some vertically centered text</p></div>
    </body>
    </html>

  • Align TransparentContainer  to the center position of the browser

    Hi there,
    i would like to align my TransparentContainer to the center position of the horizontal point of view and to the the middle poition of the vertical point of view. I tried everything but nothing really worked. Maybe anybody of you has a good advice for me.
    Thanks,
    Albert

    Albert,
    There is a button on the toolbar using which you can center the entire BPM config.
    I don't remeber the icon and I am not infront of the system. But you should be able figure that out.
    I think its the 5th one from the left hand side, the one on the left hand side of 1:1 icon.
    Regards,
    Ravi
    Message was edited by: Ravikumar Allampallam

  • 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

  • The center button on my 5th generation ipod is stuck in the down position - How can I fix this?

    The center button on my 5th generation ipod is stuck in the down position - How can I fix this?

    I'm not sure if there really is a way to "fix" it without diassembling the iPod in some manner.  Perhaps you find or use some sort of tool that can attach itself to the center botton and allow you to pull up to try and pop it out.  Kind of like the way a plunger works, but I don't know if you'll be able to find anything that small. :S
    Perhaps it would be worth it to send the iPod to a third party service company who would be able to fix it at a pretty reasonable cost. A simple Google search for "iPod repair" should give you a number of results to work with.
    B-rock

  • How do I position my layer/table for my header in the center and up top?

    I have designed a site before on my dreamweaver 4 site and
    decided to design a new one. I just tried to insert my header into
    the website and it worked fine. However, how to I align it directly
    in the center and all the way to the top so their is no space from
    the top of my site and header? My header is about 960 pixels wide
    and was hoping to have it centered when viewed with a few inches of
    background on each side. My last sight it just worked out when I
    did but not this time.
    Just so you know, I set a header layer down first, then put
    in a single row and column table, then inserted my Gif header.
    Header looks great but placement is wrong. Thanks

    Good grief - DW3? It's not there. You will have to do it in
    code view.
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    ==================
    "dontsettle22" <[email protected]> wrote in
    message
    news:fm1p83$pql$[email protected]..
    > Darn it, this is what I was looking for, however, I am
    on dreamweaver 3.
    > I can't find an insert ....layout....div. Any other
    ideas where I find
    > div?

  • How to align the JLabel to the center

    Hi,
    I made a JFrame and a JLabel, I want to put the JLabel to the center of the North position. But it doesn't work, it's just placed in the upper left corner. I tried to use html code, such as:
    JLabel l = new JLabel("<html><h1><center>Hello</h1></html>");
    And then put it in the JFrame's north position, but it doesn't work either. What should I do?
    Thx
    Adrian

    Oh, sorry,
    I just found out the function on how to align it to the center, it's
    JLable.setHorizontalAlignment(JLabel.CENTER);
    Please forget about this question.

  • Initial vertical positioning in JFrame

    In my frame(using GridBagLayout) I have several components, out of which some are not visible in the beginning. The problem is that the components that are visible in the beginning are positioned in the center of the screen, and when the rest of the components become visible, those components change position according to the space taken by the "new" components. So I would like the components' position to be initially static.
    Hope this is clear enough...
    There is a short piece of code, which demonstrates the prob...
    j
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    public class PositionTest extends JFrame{
         JButton buttShow = new JButton("Show the other button...");
         JButton buttTheOtherButton = new JButton("This is the other button");
         public PositionTest() throws Exception {
                   initFrame();
         private void initFrame() throws Exception {
              this.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent event) {
                        System.exit(0);
              buttShow.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent event) {
                        buttShow_actionPerformed(event);
              buttTheOtherButton.setVisible(false);
              this.getContentPane().setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.gridx=1;
              c.gridy=1;
              this.getContentPane().add(buttShow,c);
              c.gridy++;
              this.getContentPane().add(buttTheOtherButton,c);
              this.setTitle("TestFrame");
              this.setResizable(false);       
              this.setSize(200, 90);
              this.setLocation(100, 100);
              this.setVisible(true);
         public void buttShow_actionPerformed(ActionEvent event) {
              buttTheOtherButton.setVisible(true);
         public static void main(String[] args) throws Exception {
              PositionTest pt = new PositionTest();
    }

    I changed your code a little bit. I added an empty JLabel which holds all extra space.
    regards
    Stas
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame{
            JButton buttShow = new JButton("Show the other button...");
            JButton buttTheOtherButton = new JButton("This is the other button");
            public Test() throws Exception {
                            initFrame();
            private void initFrame() throws Exception {
                    this.addWindowListener(new WindowAdapter() {
                            public void windowClosing(WindowEvent event) {
                                    System.exit(0);
                    buttShow.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent event) {
                                    buttShow_actionPerformed(event);
                    buttTheOtherButton.setVisible(false);
                    this.getContentPane().setLayout(new GridBagLayout());
                    GridBagConstraints c = new GridBagConstraints();
                    c.gridx=1;
                    c.gridy=1;
                    this.getContentPane().add(buttShow,c);
                    c.gridy++;
                    this.getContentPane().add(buttTheOtherButton,c);
                    c = new GridBagConstraints();
                    c.gridx=1;
                    c.gridy=100;
                    c.fill=GridBagConstraints.VERTICAL;
                    c.weighty=1;
                    this.getContentPane().add(new JLabel(""),c);
                    this.setTitle("TestFrame");
                    this.setResizable(false);
                    this.setSize(300, 290);
                    this.setLocation(100, 100);
                    this.setVisible(true);
            public void buttShow_actionPerformed(ActionEvent event) {
                    buttTheOtherButton.setVisible(true);
            public static void main(String[] args) throws Exception {
                    Test pt = new Test();

  • 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 do i Pate frames from one movie to the center of another? please help?!

    what i am trying to do is, put a flash frame by frame movie into my flash web site. So i go to the frame by frame movie and hit Edit- Time line - Select all frames. i then hit Edit- Time line - Copy frames. i switch over to my web site, Create a new layer select the layer and hit Edit - Time line - Paste Frames. and the frames i copied are pasted into order and all my symbols are brought into my library. The problem is than when it is pasted its pasted in the upper left hand corner of the page on top of all my other stuff when i select the the frames of the frame by frame movie and move them to the center of the stage. It seems to work fine but when i test my movie the first frame will be fine and than some stuff goes back to the original pasted spot and some stuff will stay where i moved it to. my question is. How do you paste the frame by frame movie to the center of the stage so it does not have to be moved at all?
    or else how do i move all frames and objects to where i want them and not just the first frame?

    when you copy and paste frames, object positions will be maintained from the copied to the pasted frames.
    if you want to edit multiple frames simultaneously, click edit multiple frames (an icon in the timeline panel just below frame 22, if you're using normal sized frames).

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

Maybe you are looking for