Unable to set JPanel size in BorderLayout.CENTER

I have a class that defines a GUI for a paint-type program. This class extends JPanel. Within the class, I add a JMenu, a vertical JToolbar to the WEST, a JPanel to the SOUTH and lastly, I add the JPanel that the user draws on in the CENTER.
From my understanding of the BorderLayout, the CENTER object will take up the remaining available space. The program is run from an applet (which has a setPreferredSize() but it does not seem to affect anything - I think b/c the size specified for the applet in the HTML override it). Anyway, when I set the size of the applet in the HTML, the JPanel in the SOUTH gets cut off. In order to fit it, I have to make the size of the applet bigger - but that makes my CENTER JPanel too big. I need the CENTER JPanel to be a certain size b/c I'm saving the image - which needs to be a certain size.
I do not understand why the JPanel SOUTH is getting cut off. The JToolBar on the WEST is not that big that it should be governing the size, rather it seems like that JPanel in the CENTER is. I've tried setPreferredSize() and setSize() for that CENTER JPanel, but neither of them seem to help.
I'll appreciate any thoughts/suggestions - I can elaborate or send code if needed. Thank you all in advance.

Try using setMinimumSize() and setPreferredSize() for all the other components in the frame other than the CENTER Jpanel. For example, if you want you applet to be 300 pixel high by 500 pixels wide, and you want the centre panel to be 200 x 400 pixels, set the other components as follows:
Dimension westPanelSize = new Dimension(100, 300)); // width x height
westPanel.setMinimumSize(westPanelSize);
westPanel.setPreferredSize(westPanelSize);

Dimension southPanelSize = new Dimension(500, 100)); // width x height
southPanel.setMinimumSize(southPanelSize);
southPanel.setPreferredSize(southPanelSize);Good Luck!
- David

Similar Messages

  • JPanel not resizing BorderLayout.CENTER component

    I have a JPanel (panel_1) with a BorderLayout. In response to a mous event, I want to replace the component at BorderLayout.CENTER. I'm tracking which component is currently there, so when i get the event, I remove the component currently there, and then add a different one using add(component, BorderLayout.CENTER), and then for good measure I call getLayout().layoutContainer(this) (where "this" is panel_1). At this point, I've got another JPanel, panel_2, in the CENTER position of PANEL_1, and I can see that it's been resized correctly. However, panel_2 also has a BorderLayout, and has a JScrollPane in it's CENTER position. adding panel_2 to panel_1 at center, and redoing the layout, doesn't resize the ScrollPane inside panel_2, even though panel_2 itself is resized.
    Furthermore, in panel_2, I tried overloading setSize(int, int), setSize(Dimension), resize(int, int), resize(Dimension), and even reshape(int, int, int, int), and none of them got called during the layout, but it's size still comes out different on the other side of the layout.
    Can anyone suggest a good way to automatically resize the JScrollPane when the parent container (panel_2) is resized? Is this normal behvior? I thought that BorderLayout was supposed to do this automatically?
    Message was edited by:
    B.Mearns

    LayoutManagers uses the preferredSize to help layout components. The size means nothing, so using setSize() will not help. You should be using setPreferredSize(...).
    You may also want to look at using a [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]Card Layout which is designed to flip back and forth between multiple panels in the same container.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Get size of BorderLayout.CENTER

    I have a gif that's set to the center of a Panel using BorderLayout.
            pic = new ImageIcon(gifName);
            image = pic.getImage();
            imageWidth = image.getWidth(null);
            imageHeight = image.getHeight(null);
            label = new JLabel(){
                        public void paintComponent(Graphics g){
                            super.paintComponent(g);
                            double width = getWidth();
                            double height = getHeight();
                            Insets insets = getInsets();
                            int hInsets = insets.left + insets.right;
                            int vInsets = insets.top + insets.bottom;
                            // scale up to full image size
                            double wScale = width/(imageWidth + hInsets);
                            double hScale = height/(imageHeight + vInsets);
                            double scale = (wScale > hScale ? wScale < 1 ? wScale : 1 : hScale < 1 ? hScale : 1);
                            g.drawImage(image, 0, 0, (int)(imageWidth * scale), (int)(imageHeight * scale), this);
            };the gif scales dynamically with the size of the frame, the problem is that the gif would be fully visible if it were just added to the contentPane of the frame, but it's added to the CENTER. to the SOUTH i have a 3 x 2 GridLayout of TextFields, and this "covers up" the bottom of the gif. how do i set the gif to only extend to the bottom of the CENTER portion of the panel, instead of the bottom of the frame it is in?

    Ok, i got everything displaying now, but i still have the residual problem that when i open an internal frame with a circle in it, and then open an internal frame with a rectangle in it--the circle becomes stretched horizontally. to explain via an example:
    -- i open a circle image that is inscribed within a 10 x 10 internal frame. the circle fills up the frame.
    -- i then open a rectangle image that is inscribed in a 20 x 10 internal frame. the image of the circle now takes on the width:height ratio of the rectangle. furthermore, when i initially open these images, they are displayed at 1/2 the dimensions of the actual .GIF file, but after opening this second frame, the first one (after i resize a little to update the image) takes on the max size of the most recently opened one (rectangle in this case).
    So my circle image is 600 x 600. i open it--it displays as 300 x 300. my rectangle image is 487 x 265. i open it and it displays at ~244 x 133 simultaneously my circle image now looks like an oval. i try to resize it and it jumps to 487 x 265. the reverse occurs if i open the rectangle first, then open the circlei.e. the rectangle assumes the size of the circle, and becomes a square. How do I fix this?
            toolPanel.setSize(new Dimension((int)(imageWidth*.5), (int)(imageHeight*.5)));    
            System.out.println("tool size--w x h: "+toolPanel.getWidth() + " "+toolPanel.getHeight());
            label = new JLabel(){
                        public void paintComponent(Graphics g){
                            super.paintComponent(g);
                            double panelWidth = toolPanel.getWidth();
                            double panelHeight = toolPanel.getHeight() - myPanel.getHeight(); //may need to stick myPanel above this code
                            double labelWidth = label.getWidth();
                            double labelHeight = label.getHeight();
                            System.out.println("pw: "+panelWidth+" ph: "+panelHeight+" lw: "+labelWidth+" lh: "+labelHeight);
                            double wScale = (panelWidth/imageWidth > 1 ? 1 : panelWidth/imageWidth);
                            double vScale = (panelHeight/imageHeight > 1 ? 1 : panelHeight/imageHeight);
                            double scale = (wScale < vScale ? wScale : vScale);
                            int x = (int)(labelWidth - (int)(imageWidth * scale))/2;
                            int y = (int)(labelHeight - (int)(imageHeight * scale))/2;
                            g.drawImage(image, x, y, (int)(imageWidth * scale), (int)(imageHeight * scale), this);                       
            setSize((int)((imageWidth*.5)), (int)(imageHeight*.5));//initial frame size, before any resizing is done              
            ComponentListener l = new ComponentAdapter() {
                double scale = ((imageWidth)/(double)(imageHeight)); //the -90 kind of works with circle
                public void componentResized(ComponentEvent e) {
                    Dimension size = getSize();
                    Insets insets = getInsets();
                    int hInsets = insets.left + insets.right;
                    int vInsets = insets.top + insets.bottom;
                    // height being resized
                    if(size.width/(double)size.height < scale && size.width < imageWidth + hInsets)
                        setSize((int)(size.height * scale), size.height);
                    // width being resized
                    if(size.width/(double)size.height > scale && size.height < imageHeight + vInsets)
                    //if(size.height < imageHeight + vInsets)
                        setSize(size.width, (int)(size.width / scale));
                    // max frame size constrained to imageSize
                    if(size.width > imageWidth + hInsets || size.height > imageHeight + vInsets)
                        setSize(imageWidth + hInsets, imageHeight + vInsets);
            addComponentListener(l);       
            setOpaque(false);
            //Set the window's location.
            setLocation(xOffset*openFrameCount, yOffset*openFrameCount); //changes location for each new JIF
            //scroll.setViewportView(label);
            toolPanel.add(label, BorderLayout.CENTER);
            toolPanel.add(myPanel, BorderLayout.SOUTH);       
            toolPanel.setOpaque(false); //works
            contentPane.add(toolPanel);

  • Unable to set paper size in SSRS (it always remain Letter)

    I am making a report in SSRS (SQL Server 2012). The main report has many sub reports under it. All main and sub reports have the following properties:
    Orientation: Landscape
    Margins: Custom
    Paper Size: A4
    When I export the report in Word, it always shows Paper Size as "Letter" and I have to change it to "A4" in it. Orientation and Margins are correctly exported. What's the problem with Paper Size? Why doesn't it export correct Paper Size
    as defined in SSRS which is "A4" and always resort to "Letter"?
    I see another use has same problem but no solution was identified.
    http://social.msdn.microsoft.com/Forums/sqlserver/en-US/fce60903-3d0a-4727-abcf-b2e3370bf7d8/ssrs-2008-and-page-size-issue
    EDIT
    I just created a new basic test report with one Tablix in it. It is also showing same behavior i.e. even though I have set Paper Size to A4 when I export the report in Word, it changes to "Letter".

    Hi Frank,
    I viewed XML file for a report. The xml file doesn't store paper size name.
    <PageHeight>8.5in</PageHeight>
    <PageWidth>11in</PageWidth>
    <LeftMargin>0.25in</LeftMargin>
    <RightMargin>0.25in</RightMargin>
    <TopMargin>0.5in</TopMargin>
    <BottomMargin>0.5in</BottomMargin>
    Thanks.
    Remember to mark as an answer if this post has helped you.
    This is my master report file and looks like it has correct values. Because orientation is landscape hence height is smaller than width in my case.
    <PageHeight>8.27in</PageHeight>
    <PageWidth>11.69in</PageWidth>
    <LeftMargin>1in</LeftMargin>
    <RightMargin>0.25in</RightMargin>
    <TopMargin>0.25in</TopMargin>
    <BottomMargin>0.25in</BottomMargin>

  • Unable to set heap size to 4gb in sun java application server pe 8.2

    i have sun v890 machine with 32gb ram and solaris 10
    i am running sun java system application server platform edition 8.2
    when i am setting max heap size to 4GB
    it is giving an error
    Invalid maximum heap size -Xmx4096m
    the specified size exceeds the maximum representable size
    i want to know what i should do to increase this heap size.
    also tell me if the JVM running is 64bit. if not how can i change it
    to 64bit VM.

    The maximum size for a 32-bit process on Solaris (any 32-bit process, not just Java) is 4GB, which includes the program text, thread stacks, and various other things in addition to the JVM heap. So the maximum heap you can expect to allocate for the appserver is about 3500MB.
    SJSAS 8.2 does not support a 64-bit JVM; SJSAS 9.1 is needed for that. However, it's very rare that a Java EE application actually needs that much memory, and the 64-bit JVM has a performance penalty vs. the standard JVM. So more heap is probably not going to make your app run any better.

  • Data Visualization: Unable to set Marker Size

    JDeveloper Version: 11g Preview 3
    I have an advanced graph component (dvt:graph) with GraphType set to COMBINATION_VERT_ABS_2Y. I am using this to display two numeric values one each on Y1 and Y2. Y1 values are displayed as a bar graph and Y2 as a line graph. I have associated this graph with a managed bean. The graph component code is as follows -
    <dvt:graph id="graph1"
    value="#{bindings.SalaryHistoryRate.graphModel}"
    imageWidth="850" graphType="COMBINATION_VERT_ABS_2Y"
    barShape="CYLINDER" stylePath="Regatta"
    markerDisplayed="true" imageFormat="FLASH"
    binding="#{EmploymentDetailsGraphBean.salaryHistoryGraph}">
    <dvt:o1Title text="Change Date">
    <dvt:graphFont size="14"/>
    </dvt:o1Title>
    <dvt:y2Title text="Salary">
    <dvt:graphFont size="14"/>
    </dvt:y2Title>
    <dvt:y1Title text="Comparatio">
    <dvt:graphFont size="14"/>
    </dvt:y1Title>
    <dvt:seriesSet>
    <dvt:series/>
    <dvt:series markerShape="MS_CIRCLE"/>
    </dvt:seriesSet>
    <dvt:legendText>
    <dvt:graphFont size="14"/>
    </dvt:legendText>
    </dvt:graph>
    I am trying to change the size of the data markers for the line graphs (series 2). For this, I have the following code in the bean -
    public void setSalaryHistoryGraph(UIGraph salHistGraph) {
    this.salaryHistoryGraph = salHistGraph;
    if (salaryHistoryGraph != null) {
    CommonGraph graph = (CommonGraph)salaryHistoryGraph.getImageView();
    graph.getDataMarker().setMarkerSize(100);
    While this code executes (confirmed through debug) it does not seem to change the size of the data markers. Please can someone guide me on what I have done wrong here and what I should have done instead?

    Hi,
    You can specify multiple file names in the data export command. It will automatically extract the data in multiple files as you want.
    Thanks,
    Sourabh

  • Set specific size for JTextfield/Jbutton in BorderLayout?

    can some one tell me how to set a specific size for JTextfield/JButton in Border/BoxLayout please?
    I stried setSize, setPrefersize, setMAxsize, setMinsize, setBounds... but it won't work?
    For example. If I add a jbutton to a jpanel, which has borderlayout, it will take up ALL the space in that jpanel.
    Thanks

    Typically you use a BorderLayout for the high level layout and then add panels using other layouts to the BorderLayout. So for example on a simple dialog that is using a form that asks your for your first name and last name you would build a panel with those fields and add that panel to the center of the BorderLayout. Then you would create another panel for the "Ok" and "Cancel" buttons which would typically use a FlowLayout. Then you add that panel to the South of the BorderLayout.
    The Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use LayoutManagers has all the information you need to know on using layout managers.

  • How can I know the size of a JViewport laid out in BorderLayout.CENTER?

    I have a JPanel inside a JScrollPane. The scroll pane is laid out inside of BorderLayout.CENTER. I need to know the size of the JViewport to do stuff like centering and zooming.
    Where can I find the size? All these methods return 0 values for X and Y:
    myScrollPane.getViewport().getSize()
    myScrollPane().getSize()
    myScrollPane.getHorizontalScrollbar().getValue()
    Yes, even the scrollbars won't give me any values! It's all because of the BorderLayout!
    Any ideas? Thanks.

    Sounds like you are accessing the sizes before the views are realized (that is before a call to frame.pack()/show()) They are available only after the layoutManager had a go on it. What is available earlier are preferred/min/max, though.
    Greetings
    Jeanette

  • Unable to set Oracle driver statement cache size to 300

    Hi Friends,
    when i am starting thread pool worker using threadpoolworker using threadpoolworker.cmd i am getting the error as follows
    The root LoggedException was: Unable to set Oracle driver statement cache size to 300
    at com.splwg.shared.common.LoggedException.raised(LoggedException.java:65)
    at com.splwg.base.support.sql.OracleFunctionReplacer.setOracleCacheSize(OracleFunctionReplacer.java:232)
    at com.splwg.base.support.sql.OracleFunctionReplacer.initializeConnectionForNewSession(OracleFunctionReplacer.java:207)
    at com.splwg.base.support.context.FrameworkSession.initialize(FrameworkSession.java:225)
    at com.splwg.base.support.context.FrameworkSession.<init>(FrameworkSession.java:194)
    at com.splwg.base.support.context.ApplicationContext.createSession(ApplicationContext.java:417)
    at com.splwg.base.support.context.ApplicationContext.createThreadBoundSession(ApplicationContext.java:461)
    at com.splwg.base.support.context.SessionExecutable.doInReadOnlySession(SessionExecutable.java:96)
    at com.splwg.base.support.context.SessionExecutable.doInReadOnlySession(SessionExecutable.java:79)
    at com.splwg.base.support.context.ApplicationContext.initialize(ApplicationContext.java:211)
    at com.splwg.base.support.context.ContextFactory.buildContext(ContextFactory.java:114)
    at com.splwg.base.support.context.ContextFactory.buildContext(ContextFactory.java:90)
    at com.splwg.base.support.context.ContextFactory.createDefaultContext(ContextFactory.java:498)
    at com.splwg.base.api.batch.StandaloneExecuter.setupContext(StandaloneExecuter.java:258)
    at com.splwg.base.api.batch.StandaloneExecuter.run(StandaloneExecuter.java:129)
    at com.splwg.base.api.batch.StandaloneExecuter.main(StandaloneExecuter.java:357)
    at com.splwg.base.api.batch.AbstractStandaloneRunner.invokeStandaloneExecuter(AbstractStandaloneRunner.java:403)
    at com.splwg.base.api.batch.AbstractStandaloneRunner.run(AbstractStandaloneRunner.java:134)
    at com.splwg.base.api.batch.ThreadPoolWorker.run(ThreadPoolWorker.java:24)
    at com.splwg.base.api.batch.ThreadPoolWorker.main(ThreadPoolWorker.java:17)
    can any one tell me the exact error
    shyam.

    Hi Friends,
    when i am starting thread pool worker using threadpoolworker using threadpoolworker.cmd i am getting the error as follows
    The root LoggedException was: Unable to set Oracle driver statement cache size to 300
    at com.splwg.shared.common.LoggedException.raised(LoggedException.java:65)
    at com.splwg.base.support.sql.OracleFunctionReplacer.setOracleCacheSize(OracleFunctionReplacer.java:232)
    at com.splwg.base.support.sql.OracleFunctionReplacer.initializeConnectionForNewSession(OracleFunctionReplacer.java:207)
    at com.splwg.base.support.context.FrameworkSession.initialize(FrameworkSession.java:225)
    at com.splwg.base.support.context.FrameworkSession.<init>(FrameworkSession.java:194)
    at com.splwg.base.support.context.ApplicationContext.createSession(ApplicationContext.java:417)
    at com.splwg.base.support.context.ApplicationContext.createThreadBoundSession(ApplicationContext.java:461)
    at com.splwg.base.support.context.SessionExecutable.doInReadOnlySession(SessionExecutable.java:96)
    at com.splwg.base.support.context.SessionExecutable.doInReadOnlySession(SessionExecutable.java:79)
    at com.splwg.base.support.context.ApplicationContext.initialize(ApplicationContext.java:211)
    at com.splwg.base.support.context.ContextFactory.buildContext(ContextFactory.java:114)
    at com.splwg.base.support.context.ContextFactory.buildContext(ContextFactory.java:90)
    at com.splwg.base.support.context.ContextFactory.createDefaultContext(ContextFactory.java:498)
    at com.splwg.base.api.batch.StandaloneExecuter.setupContext(StandaloneExecuter.java:258)
    at com.splwg.base.api.batch.StandaloneExecuter.run(StandaloneExecuter.java:129)
    at com.splwg.base.api.batch.StandaloneExecuter.main(StandaloneExecuter.java:357)
    at com.splwg.base.api.batch.AbstractStandaloneRunner.invokeStandaloneExecuter(AbstractStandaloneRunner.java:403)
    at com.splwg.base.api.batch.AbstractStandaloneRunner.run(AbstractStandaloneRunner.java:134)
    at com.splwg.base.api.batch.ThreadPoolWorker.run(ThreadPoolWorker.java:24)
    at com.splwg.base.api.batch.ThreadPoolWorker.main(ThreadPoolWorker.java:17)
    can any one tell me the exact error
    shyam.

  • Unable to set profit center

    Hi Friends,
    Pls help in this issue
    "Using transaction FB50, post to GL account 4500610 with Profit Center MT5000V48C. However, upon saving of document, profit center was set to DUMMY. User is unable to set the profit center"
    Thanks,
    Santi

    Hi Santi,
    This one is a duplicate issue. Please close this thread.
    Regards,
    Abhisek

  • Set minimum size for GridBagLayout

    Hi all,
    I have a dialog which using GridBagLayout. I spent quite a lot of time to test, but still got the following problems. Could anyone give me some solutions?
    1. How do I set the dialog to have a minimum size ?
    Since the dialog is sizeable, so I have to make this limitation to prevent the dialog being too small .
    I tried the following code:
            this.getContentPane().setMinimumSize(new Dimension(686,520));
            this.setMinimumSize(new Dimension(686,520));but it's still not work... , I can still resize it too small.. any other way ?
    2. How do I set its default size when dialog pop up?
    I don't know why the dialog always auto popup in maximum size.
    I have tried to use this.setSize(new Dimension(686, 536)); inside jbInit() function, but still not work...
    Please help ... Thanks a lot.

    Why dont you try this.setResizable(false);?
    Anyway I have given a sample program here using Gridbag layout and this dialog cannot be resized.
    import java.awt.BorderLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class SunExample28 extends JDialog {
         public SunExample28() {
              setTitle("JDialog with Fixed size");
              JLabel nameLbl = new JLabel("Name:");
              JLabel ageLbl = new JLabel("Age:");
              JTextField nameFld = new JTextField(10);
              JTextField ageFld = new JTextField(10);
              GridBagConstraints gbc = new GridBagConstraints();
              Insets in = new Insets(5,5,5,5);
              JPanel compPanel = new JPanel(new GridBagLayout());
              gbc.gridx = 0;
              gbc.gridy = 0;
              compPanel.add(nameLbl,gbc);
              gbc.insets = in;
              gbc.gridx = 1;
              gbc.gridy = 0;
              compPanel.add(nameFld, gbc);
              gbc.insets = in;
              gbc.gridx = 0;
              gbc.gridy = 1;
              compPanel.add(ageLbl, gbc);
              gbc.insets = in;
              gbc.gridx = 1;
              gbc.gridy = 1;
              compPanel.add(ageFld, gbc);
              JButton okBtn = new JButton("OK");
              JButton cancelBtn = new JButton("Cancel");
              JPanel btnPanel = new JPanel();
              btnPanel.add(okBtn);
              btnPanel.add(cancelBtn);
              getContentPane().add(compPanel, BorderLayout.CENTER);
              getContentPane().add(btnPanel, BorderLayout.PAGE_END);
              setDefaultCloseOperation(DISPOSE_ON_CLOSE);
              setSize(500,300);
              setResizable(false);
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              new SunExample28().setVisible(true);
    }

  • How to set the size of a textPane

    I have the following text pane:
         private JTextPane objTPOutput = new JTextPane ();
    /* Output information to the Text Area */
                   objTPOutput.setText("Student Name = " + name +
                                            "\nClass Name = " + className +
                                            "\nCampus Name = " + campusName +
                                            "\nClass Start = " + start +
                                            "\nClass End = " + end +
                                            "\nNumber of Credits = " + numCredit +
                                            "\nCost Per Credit = " + cost +
                                            "\nCost of Class = " + (cost * numCredit));And I want to make it so that I can set it's size so that all the text fits in the panel. For instance, be able to set it's height to a static number.
    How would I go about doing this?

    It is actually in an applet, and JPanel. Let me show you my code so that you can see it:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
         Class: MetroClass
    public class MetroClass extends JApplet{
         /* Create Applet Controls used */
         private JTextField objTFName = new JTextField();
         private JComboBox objCBClass = new JComboBox();
         private JComboBox objCBCampus = new JComboBox();
         private JTextField objTFStart = new JTextField();
         private JTextField objTFEnd = new JTextField();
         private JTextField objTFCost = new JTextField();
         private JTextField objTFNumCredit = new JTextField();
         private JButton objBtnCalculate = new JButton("Calculate");
         private JTextPane objTPOutput = new JTextPane ();
              Method: init()
              Initializes all controls on the applet.
         public void init(){
              /* Create Panel to store all controls */
              JPanel objPanel = new JPanel(new GridLayout(10,2));
              /* Add Items to Drop Down List */
              objCBClass.addItem("ICS 140");
              objCBClass.addItem("ICS 141");
              objCBClass.addItem("ICS 240");
              objCBClass.addItem("ICS 340");
              /* Add Items to Drop Down List */
              objCBCampus.addItem("St. Paul");
              objCBCampus.addItem("Midway");
              objCBCampus.addItem("Minneapolis");
              /* Set the Text Alignment to Left*/
              objTFName.setHorizontalAlignment(JTextField.LEFT);
              objTFStart.setHorizontalAlignment(JTextField.LEFT);
              objTFEnd.setHorizontalAlignment(JTextField.LEFT);
              objTFCost.setHorizontalAlignment(JTextField.LEFT);
              objTFNumCredit.setHorizontalAlignment(JTextField.LEFT);
              /* Add all the controls to the panel*/
              objPanel.add(new JLabel("Enter your Name"));
              objPanel.add(objTFName);
              objPanel.add(new JLabel("Select the class"));
              objPanel.add(objCBClass);
              objPanel.add(new JLabel("Select the Campus"));
              objPanel.add(objCBCampus);
              objPanel.add(new JLabel("Class Start"));
              objPanel.add(objTFStart);
              objPanel.add(new JLabel("Class End"));
              objPanel.add(objTFEnd);
              objPanel.add(new JLabel("What is the cost per Credit"));
              objPanel.add(objTFCost);
              objPanel.add(new JLabel("How many credits"));
              objPanel.add(objTFNumCredit);
              objPanel.add(new JLabel(""));
              objPanel.add(objBtnCalculate);
              objPanel.add(new JLabel(""));
              objPanel.add(objTPOutput);
              /* Add the panel to the applet */
              add(objPanel,BorderLayout.CENTER);
              /* Add a event handler to listen for the button press*/
              objBtnCalculate.addActionListener(new ButtonListener());
              Class: ButtonListener
         private class ButtonListener implements ActionListener {
                   Method: actionPerformed()
                   This method listens for a button click.  Upon a button click
                   the values in the text boxes and drop down list are acquired,
                   and displayed in a text area.
              public void actionPerformed(ActionEvent e){
                   /* Method Variables*/
                   int numCredit = 0;
                   double cost = 0.0;
                   String name = "";
                   String start = "";
                   String end = "";
                   String className = "";
                   String campusName = "";
                   /* Get the control values */
                   numCredit = Integer.parseInt(objTFNumCredit.getText());
                   cost = Double.parseDouble(objTFCost.getText());
                   name = objTFName.getText();
                   start = objTFStart.getText();
                   end = objTFEnd.getText();
                   className = objCBClass.getSelectedItem().toString();
                   campusName = objCBCampus.getSelectedItem().toString();
                   objTPOutput.pane.setPreferredSize(new Dimension(40, 40));
                   /* Outut information to the Text Area */
                   objTPOutput.setText("Student Name = " + name +
                                            "\nClass Name = " + className +
                                            "\nCampus Name = " + campusName +
                                            "\nClass Start = " + start +
                                            "\nClass End = " + end +
                                            "\nNumber of Credits = " + numCredit +
                                            "\nCost Per Credit = " + cost +
                                            "\nCost of Class = " + (cost * numCredit));
    }

  • JLabel: how to set maximum size in layout?

    I have a BorderLayout that i want to show a JLabel in NORTH. I use HTML in the label message text with one line being centered with <center>. If the overall text of the label is long/big enough, i.e. subsequent text results in line breaks, the cenetered line is cenetered correctly.
    however, if the subsequent text is just small, all lines are left justified/adjusted. i guess, the JLabel dimension is not maximized to the maximum available spave in the NORTH area of BorderLayout.
    I tried adding the JLabel directly or within a JPanel (also with BorderLayout, then with add(label, BorderLayout.CENTER)), also first set the size of the dialog, added all components and just added the text to the label at the last position. doesn't help.

    Tip: putting a border on a JComponent like JLabel helps you see how its parent container is sizing it. I don't know what HTML mark-up you are using, but is the centering necessary?
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Ex {
        public static void main(String[] args) {
            JFrame f = new JFrame("Ex");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container cp = f.getContentPane();
            String text = "Example text";
            Border b = BorderFactory.createLineBorder(Color.BLUE);
            JLabel label0 = new JLabel(text, SwingConstants.CENTER);
            label0.setBorder(b);
            JLabel label1 = new JLabel(text);
            label1.setBorder(b);
            cp.add(label0, BorderLayout.NORTH);
            cp.add(label1, BorderLayout.SOUTH);
            f.setSize(400,100);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }

  • Setting the size of a JComponent which is not currently shown

    Hi,
    I got a problem to set the size of a maybe JButton, before the button is displayed on screen.
    Assume i got a button without any text.
    Then the button length and height is 0 before the button
    is displayed.
    But i don't want to set the width and height of the
    button dynamically in the paint method for performance
    reason.
    I got only the trick to set a JButton with like this
    JButton b = new JButton("                            ");But this is not nice.
    I found no method in a JComponent to set the
    size of a component static in the constructor.
    The usage of setPrefferedSize() etc. don't work
    until the component is not displayed.
    So is there a way to compute the size of a Component
    before displaying?
    regards
    Olek

    It seems that there is no way to calculate the size via legacy methods.as already mentioned, it has a preferredSize and all you need do is something like this
    import javax.swing.*;
    import java.awt.*;
    class Testing
      public void buildGUI()
        JFrame f = new JFrame();
        f.getContentPane().add(getPanel("Hello"),BorderLayout.NORTH);
        f.getContentPane().add(getPanel("Hello World"),BorderLayout.CENTER);
        f.getContentPane().add(getPanel("Goodbye"),BorderLayout.SOUTH);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public JPanel getPanel(String buttonText)
        JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JButton btn = new JButton(buttonText);
        Dimension d = btn.getPreferredSize();
        JLabel label = new JLabel("w = "+d.width+", h = "+d.height);
        p.add(label);
        p.add(btn);
        return p;
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }[EDIT]
    just reread your first post, you want to set (not get) the size (thwak!, uppercut)
    first reply amended
    import javax.swing.*;
    import java.awt.*;
    class Testing
      public void buildGUI()
        JFrame f = new JFrame();
        f.getContentPane().add(getPanel(62,26),BorderLayout.NORTH);
        f.getContentPane().add(getPanel(99,26),BorderLayout.CENTER);
        f.getContentPane().add(getPanel(83,26),BorderLayout.SOUTH);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public JPanel getPanel(int w, int h)
        JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JButton btn = new JButton();
        btn.setPreferredSize(new Dimension(w,h));
        Dimension d = btn.getPreferredSize();
        JLabel label = new JLabel("w = "+d.width+", h = "+d.height);
        p.add(label);
        p.add(btn);
        return p;
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }Edited by: Michael_Dunn on Nov 6, 2007 4:40 AM

  • HELP !!! How can I set the size of each component separately

    Please tell me, when adding components (a mix of
    labels , buttons etc.) on a container (swing), how can I set the size
    of each component separately.
    for example:
    the code here has a mix of button and a grid that is actually another JPanel. Its a part of a bigger
    program. When running the grid is cut (not seen in its full size).
    So, please try to anser also about the specific acse of frame contining another frame in it , and the interior should be right sized.
    The relevant part of the code:
    =========================================
    public class Reversi extends JFrame {
    public static void main(String[] args) {
    Reversi ourGame = new Reversi();
    public Reversi() {
    super("Grid Reversi");
    setSize(new Dimension(300, 300));
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Grid g = new Grid(); // the grid was built at another part..
    ReversiGame ourGame = new ReversiGame();
    JButton b;
    JFrame f = new JFrame("Hello Java");
    f.setSize(new Dimension(300, 300));
    f.setDefaultCloseOperation(EXIT_ON_CLOSE);
    Container c = f.getContentPane();
    c.add(g,BorderLayout.NORTH );
    c.add(b = new JButton("Hola"), BorderLayout.CENTER);
    //f.pack();
    f.show();

    BorderLayout chooses the sizes of each of the components added to it. Choose a different layout manager (or set the placement/size manually with a 'null' layout)
    http://java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr/shortcourse.html

Maybe you are looking for