GridBagLayout on top of other layout manager

Hi,
I am trying to put a GridBagLayout within a GridLayout and it is not showing up. What's wrong?
Thanks,
Steve
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class TestButton {
    public static void main(String[] arguments) {
        JFrame frame = new Interface();
        frame.show();
class Interface extends JFrame {
     private dataPanel screenvar;
     private JTextArea msgout;
     Interface () {
          super("This is a JFrame");
        setSize(600, 200);  // width, height
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          JPanel pane = new JPanel();
          // create empty space
          pane.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30)); //top, left, bottom, right
          // declare components
          msgout = new JTextArea( 8, 40 );
          dataPanel screenvar = new dataPanel();
          NamePass testGrid = new NamePass();
          // end declare components
          pane.setLayout(new GridLayout(1, 4, 5, 15));  
          pane.add(testGrid);
          pane.add(msgout);
             pane.add( new JScrollPane(msgout));
          pane.add(screenvar);
          msgout.append("Successful");
          setContentPane(pane);
          setVisible(true);
class updateDataFields implements ActionListener {     // 400
     private dataPanel abc;
     private JTextArea msg;
     public updateDataFields(dataPanel xyz, JTextArea msgout) {     // 100
          abc = xyz;
          msg = msgout;
     }     // 100
     public void actionPerformed(ActionEvent evt) {     // 200
          String command = evt.getActionCommand();
               if (command.equals("TestMe")){     // 300
                    msg.append("\nSuccessful");
                    abc.right01.setText("1000");
                    abc.left02.setText("Hi!");
                    abc.right03.setText("123456");
               }     // 300
     }     // 200
}     // 400
class dataPanel extends JPanel {
     JLabel left1, left2, left3, right1, right2, right3;
     JTextField left01, left02, left03, right01, right02, right03;
    public dataPanel () {     // 1
          GridLayout grid = new GridLayout(3, 2, 5, 15); // row, col, hgap, vgap
          setLayout(grid);
          left1 = new JLabel("Left1");
          add(left1);
          left01 = new JTextField(0);
          add(left01);
          right1 = new JLabel("Right1");
          add(right1);
          right01 = new JTextField(0);
          add(right01);
          left2 = new JLabel("Left2");
          add(left2);
          left02 = new JTextField(0);
          add(left02);
          right2 = new JLabel("Right2");
          add(right2);
          right02 = new JTextField(0);
          add(right02);
          left3 = new JLabel("Left3");
          add(left3);
          left03 = new JTextField(0);
          add(left03);
          right3 = new JLabel("Right3");
          add(right3);
          right03 = new JTextField(0);
          add(right03);
class buttonPanel extends JPanel {     // 200 
     public buttonPanel(dataPanel xyz, JTextArea msgout) {     // 100
          GridLayout actionGrid = new GridLayout(1, 1, 5, 15); // row, col, hgap, vgap
          setLayout(actionGrid);     
          JButton buttonTest = new JButton("TestMe");
          int width = 5;
          int height = 30;
          buttonTest.setPreferredSize(new Dimension(width, height));
          buttonTest.addActionListener( new updateDataFields( xyz, msgout ));
          add(buttonTest);
     }     // 100
}     // 200
class NamePass extends JPanel {
    void buildConstraints(GridBagConstraints gbc, int gx, int gy,
        int gw, int gh, int wx, int wy) {
        gbc.gridx = gx;
        gbc.gridy = gy;
        gbc.gridwidth = gw;
        gbc.gridheight = gh;
        gbc.weightx = wx;
        gbc.weighty = wy;
    public NamePass() {
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints constraints = new GridBagConstraints();
        JPanel pane1 = new JPanel();
        pane1.setLayout(gridbag);
        // Name label
        buildConstraints(constraints, 0, 0, 1, 1, 10, 40);
        constraints.fill = GridBagConstraints.NONE;
        constraints.anchor = GridBagConstraints.EAST;
        JLabel label1 = new JLabel("Name:", JLabel.LEFT);
        gridbag.setConstraints(label1, constraints);
        pane1.add(label1);
        // Name text field
        buildConstraints(constraints, 1, 0, 1, 1, 90, 0);
        constraints.fill = GridBagConstraints.HORIZONTAL;
        JTextField tfname = new JTextField();
        gridbag.setConstraints(tfname, constraints);
        pane1.add(tfname);
        // password label
        buildConstraints(constraints, 0, 1, 1, 1, 0, 40);
        constraints.fill = GridBagConstraints.NONE;
        constraints.anchor = GridBagConstraints.EAST;
        JLabel label2 = new JLabel("Password:", JLabel.LEFT);
        gridbag.setConstraints(label2, constraints);
        pane1.add(label2);
        // password text field
        buildConstraints(constraints, 1, 1, 1, 1, 0, 0);
        constraints.fill = GridBagConstraints.HORIZONTAL;
        JPasswordField tfpass = new JPasswordField();
        tfpass.setEchoChar('*');
        gridbag.setConstraints(tfpass, constraints);
        pane1.add(tfpass);
        // OK Button
        buildConstraints(constraints, 0, 2, 2, 1, 0, 20);
        constraints.fill = GridBagConstraints.NONE;
        constraints.anchor = GridBagConstraints.CENTER;
        JButton okb = new JButton("OK");
        gridbag.setConstraints(okb, constraints);
        pane1.add(okb);
        // Content Pane
//        setContentPane(pane);
        setVisible(true);
}

The problem is in your NamePass panel...you create another panel object called pane1 and add everything to it. Just remove the line that creates the pane1 object and everywhere you have pane1.add(...) just remove "pane1." - you will then be adding to your NamePass panel instead!

Similar Messages

  • Layout manager issue.

    I was hoping that someone could shed some light on why one layout manage will allow an applet to be inserted in a class that extends JFrame but not another.
    Here is the guts of the problem I have an class that extends applet to display a pie chart. I then have a seperate class that extends JFrame that display two input boxes and a button. When the user enters two fields and clicks draw the pie chart displays working with the two numbers. The JFrame class that works uses the border layout. I change the class to use gridbag, and now only the textboxes display. Can anyone help. Here is the code for the three classes.
    This is the applet class....
    * File: PieChart.java
    * PieChart class is an Swing applet that use a pie chart
    * to show the percentage. It is used by PieChartExample
    * to show what percetange of a payment actually goes to
    * pay interest. There is no error handling in the program.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class PieChart extends JApplet {
    final static Color bg = Color.white;
    final static Color fg = Color.black;
    private double percent;
    public void init() {
    //Initialize drawing colors
    setBackground(bg);
    setForeground(fg);
    percent = 1.0;
         public void setPercentage(double pct) {
              this.percent = pct;
    public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setPaint(fg);
    drawAnnotation(g2);
    drawArc(g2, percent);
    public void drawAnnotation(Graphics2D g2) {
              // draw a small green circle
              g2.setPaint(Color.green);
    g2.fill(new Ellipse2D.Double(200, 200, 10,10));
    // draw a small red circle
    g2.setPaint(Color.red);
    g2.fill(new Ellipse2D.Double(270, 200, 10, 10));
    g2.setPaint(Color.black);
    g2.drawString("Interest", 210, 210); // write "Interest" by green circle
    g2.drawString("Principal", 280, 210); // write "Principal" by red circle
         public void drawArc(Graphics2D g2, double percent) {
    // draw the interest portion
              g2.setPaint(Color.green);
              g2.fill(new Arc2D.Double(10,10,200,200, 0, percent * 360, Arc2D.PIE));
              // draw the rest (principal portion)
              g2.setPaint(Color.red);
              g2.fill(new Arc2D.Double(10,10,200,200, percent * 360, (1-percent)*360, Arc2D.PIE));
    This is the JFrame class using Boarderlayout that works.
    * File: PieChartExample.java
    * The program demonstrate a simple use of pie chart. It takes total
    * payment and interest paid from user input and draws a pie chart
    * to show the percentage of interert to total payment. There is no
    * error handling whatsoever in the example program, so you can see
    * that it can be broken easily.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class PieChartExample extends JFrame {
         final static int CHART_WIDTH = 800;
         final static int CHART_HEIGHT = 300;
         JPanel panel ;
         JLabel paymentLabel;
         JTextField paymentField;
         JLabel interestLabel;
         JTextField interestField;
         JButton show;
    PieChart applet;
    public PieChartExample() {
    super("Pie Chart Example");
    panel = new JPanel();
    paymentLabel = new JLabel("Payment: $");
    panel.add(paymentLabel);
    paymentField = new JTextField(10);
    panel.add(paymentField);
    interestLabel = new JLabel("Interest: $");
    panel.add(interestLabel);
    interestField = new JTextField(10);
    panel.add(interestField);
    show = new JButton("Draw");
    panel.add(show);
    this.getContentPane().add("North", panel);
    applet = new PieChart();
    this.getContentPane().add("Center", applet);
    show.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent evt) {
                        double interest = Double.parseDouble(interestField.getText());
                        double payment = Double.parseDouble(paymentField.getText());
                        double percent = interest / payment;
                        //System.out.println("In event handler, percent is " + percent);
                        applet.setPercentage(percent);
                        applet.repaint();
    private static void createAndShowGUI() {
    PieChartExample f = new PieChartExample();
    f.pack();
    f.setSize(new Dimension(CHART_WIDTH ,CHART_HEIGHT));
    f.show();
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    This is the modified class to use GridBag that fails.
    * File: PieChartExample2.java
    * The program demonstrate a simple use of pie chart. It takes total
    * payment and interest paid from user input and draws a pie chart
    * to show the percentage of interert to total payment. There is no
    * error handling whatsoever in the example program, so you can see
    * that it can be broken easily.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class PieChartExample2 extends JFrame {
         final static int CHART_WIDTH = 800;
         final static int CHART_HEIGHT = 300;
         JPanel panel ;
         JLabel paymentLabel;
         JTextField paymentField;
         JLabel interestLabel;
         JTextField interestField;
         JButton show;
    PieChart applet;
    public PieChartExample2() {
    super("Pie Chart Example");
    // Get container and set layout manager
    Container contentPane = getContentPane();
    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    contentPane.setLayout(gridbag);
    c.fill = GridBagConstraints.HORIZONTAL;
    panel = new JPanel();
    paymentLabel = new JLabel("Payment: $");
    panel.add(paymentLabel);
    paymentField = new JTextField(10);
    panel.add(paymentField);
    interestLabel = new JLabel("Interest: $");
    panel.add(interestLabel);
    interestField = new JTextField(10);
    panel.add(interestField);
    show = new JButton("Draw");
    panel.add(show);
    c.gridx = 0;
    c.gridy = 0;
    gridbag.setConstraints(panel, c);
    contentPane.add(panel);
    applet = new PieChart();
    c.gridx = 0;
    c.gridy = 1;
    gridbag.setConstraints(applet, c);
    contentPane.add(applet);
    show.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent evt) {
                        double interest = Double.parseDouble(interestField.getText());
                        double payment = Double.parseDouble(paymentField.getText());
                        double percent = interest / payment;
                        //System.out.println("In event handler, percent is " + percent);
                        applet.setPercentage(percent);
                        applet.repaint();
    private static void createAndShowGUI() {
    PieChartExample2 f = new PieChartExample2();
    f.pack();
    f.setSize(new Dimension(CHART_WIDTH ,CHART_HEIGHT));
    f.show();
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    }

    Ok. It seems I may be wrong and that this may not be a concurrent call issue. I overode the components setBounds and setLocation methods and it appears that an external class is updating the position of these components while layoutContainer is attempting to position them. I can see that the correct positions are being set in the setBounds method, but this is happening after layoutContainer has called getLocation on the components. To be a little more specific, I am using a JLayeredPane to display some overlapping JLabels with images. I have implemented drag and drop on these labels so that dropping one on another swaps the images. The label positions and sizes are not being changed during the drop (I don't want them to move or resize just change images). However, for some reason I have yet to discover, two calls to set bounds are being made on the labels. The first call is relocating the label to the second labels position, the second call is relocating the label back to it's original position. If anyone has any insight on why the label position are changing when I am not explicitly repositioning them please reply. I will post another reply when I have corrected the problem or found a work around for it. I am awarding the dukes to tjacobs1 since he was the only responses I've had so far.

  • Layout manager for a Windows type toolbar

    I have made a layout manager that when there is not enough room to put all the buttons it stores them inside a "subMenu" that appears at the end of the tool bar. Unfortunally the perfered size is not being calculated correctly so when the user makes the toolbar floatable it doesn't make the toolbar long enough.
    Here is my code:
    * ExpandLayout.java
    * Created on May 29, 2003, 3:17 PM
    package edu.cwu.virtualExpert.caseRecorder;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    * @author  subanark
    public class ExpandLayout implements java.awt.LayoutManager
        private JPopupMenu extenderPopup = new JPopupMenu();
        private JButton extenderButton = new JButton(new PopupAction());
        /** Creates a new instance of ExpandLayout */
        public ExpandLayout()
        protected class PopupAction extends AbstractAction
            public PopupAction()
                super(">");
            public void actionPerformed(ActionEvent e)
                JComponent component = (JComponent)e.getSource();
                extenderPopup.show(component,0,component.getHeight());
        /** If the layout manager uses a per-component string,
         * adds the component <code>comp</code> to the layout,
         * associating it
         * with the string specified by <code>name</code>.
         * @param name the string to be associated with the component
         * @param comp the component to be added
        public void addLayoutComponent(String name, Component comp)
         * Lays out the specified container.
         * @param parent the container to be laid out
        public void layoutContainer(Container parent)
            Dimension parentSize = parent.getSize();
            Dimension prefSize = preferredLayoutSize(parent);
            Insets insets = parent.getInsets();
            int x = insets.left;
            int y = insets.top;
            parentSize.width -= insets.right;
            int i;
            for(int j = 0; j < extenderPopup.getComponentCount();)
                Component aComponent = extenderPopup.getComponent(j);
                parent.add(aComponent);
            parent.remove(extenderButton);
            //System.out.println("Component count:"+parent.getComponentCount());
            for(i = 0; i < parent.getComponentCount() &&
                       parent.getComponent(i).getPreferredSize().width +(i==parent.getComponentCount()-1?0:extenderButton.getPreferredSize().width) + x < parentSize.width;i++)
                //System.out.println("exSize"+(parent.getComponent(i).getPreferredSize().width +extenderButton.getPreferredSize().width + x));
                Component aComponent = parent.getComponent(i);
                if(aComponent != extenderButton)
                    aComponent.setSize(aComponent.getPreferredSize());
                    aComponent.setLocation(x,y);
                    x += aComponent.getPreferredSize().width;
                    //System.out.println(aComponent.getX());
            if(i < parent.getComponentCount())
                while(i < parent.getComponentCount())
                    //System.out.println("Need Room");
                    extenderPopup.add(parent.getComponent(i));
                //System.out.println("extenderButton added");
                parent.add(extenderButton);
                extenderButton.setSize(extenderButton.getPreferredSize());
                extenderButton.setLocation(x,y);
                x += extenderButton.getPreferredSize().width;
                //System.out.println(extenderButton);
            else
                //System.out.println("extenderButton removed");
                parent.remove(extenderButton);
                //System.out.println("Component count:"+extenderButton.getComponentCount());
         * Calculates the minimum size dimensions for the specified
         * container, given the components it contains.
         * @param parent the component to be laid out
         * @see #preferredLayoutSize
        public Dimension minimumLayoutSize(Container parent)
            return extenderButton.getMinimumSize();
        /** Calculates the preferred size dimensions for the specified
         * container, given the components it contains.
         * @param parent the container to be laid out
         * @see #minimumLayoutSize
        public Dimension preferredLayoutSize(Container parent)
            Dimension d = new Dimension();
            d.width += parent.getInsets().right+parent.getInsets().left;
            for(int i = 0; i < parent.getComponents().length;i++)
                if(parent.getComponent(i) != extenderButton)
                    d.width+=parent.getComponent(i).getPreferredSize().width;
                    d.height = Math.max(d.height,parent.getComponent(i).getPreferredSize().height);
            for(int i = 0; i < extenderPopup.getComponentCount();i++)
                d.width+=extenderPopup.getComponent(i).getPreferredSize().width;
                d.height = Math.max(d.height,extenderPopup.getComponent(i).getPreferredSize().height);
            d.height += parent.getInsets().top+parent.getInsets().bottom+5;
            return d;
        /** Removes the specified component from the layout.
         * @param comp the component to be removed
        public void removeLayoutComponent(Component comp)
        public static void main(String[] argv)
            JFrame f = new JFrame();
            JToolBar toolBar = new JToolBar();
            toolBar.setLayout(new ExpandLayout());
            toolBar.add(new JButton("hello"));
            toolBar.add(new JButton("Hello2"));
            toolBar.add(new JButton("Hello3"));
            toolBar.add(new JButton("Hi"));
            f.getContentPane().setLayout(new BorderLayout());
            f.getContentPane().add(toolBar,BorderLayout.NORTH);
            f.setBounds(0,0,300,300);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setVisible(true);
    }

    This is a wierd one. I noticed that the width of a button is 22 pixels larger in the popup menu that it is in the toolbar.I traced this down to the insets being changed when the button is added to the toolbar. The strange part is that the size of the component keeps changing as you move it from the toolbar to the popup menu and back.
    Anyway, I ended up changing most of you code. Here is my version:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    * @author subanark
    public class ExpandLayout implements java.awt.LayoutManager
         private JPopupMenu extenderPopup = new JPopupMenu();
         private JButton extenderButton = new JButton(new PopupAction());
         /** Creates a new instance of ExpandLayout */
         public ExpandLayout()
         /** If the layout manager uses a per-component string,
         * adds the component <code>comp</code> to the layout,
         * associating it
         * with the string specified by <code>name</code>.
         * @param name the string to be associated with the component
         * @param comp the component to be added
         public void addLayoutComponent(String name, Component comp)
         * Lays out the specified container.
         * @param parent the container to be laid out
         public void layoutContainer(Container parent)
              //  Position all buttons in the container
              Insets insets = parent.getInsets();
              int x = insets.left;
              int y = insets.top;
              int spaceUsed = insets.right + insets.left;
              for (int i = 0; i < parent.getComponentCount(); i++ )
                   Component aComponent = parent.getComponent(i);
                   aComponent.setSize(aComponent.getPreferredSize());
                   aComponent.setLocation(x,y);
                   int componentWidth = aComponent.getPreferredSize().width;
                   x += componentWidth;
                   spaceUsed += componentWidth;
              //  All the buttons won't fit, add extender button
              //  Note: the size of the extender button changes once it is added
              //  to the container. Add it here so correct width is used.
              int parentWidth = parent.getSize().width;
              if (spaceUsed > parentWidth)
                   parent.add(extenderButton);
                   extenderButton.setSize( extenderButton.getPreferredSize() );
                   spaceUsed += extenderButton.getSize().width;
              //  Remove buttons that don't fit and add to the popup menu
              while (spaceUsed > parentWidth)
                   int last = parent.getComponentCount() - 2;
                   Component aComponent = parent.getComponent( last );
                   parent.remove( last );
                   extenderPopup.insert(aComponent, 0);
                   extenderButton.setLocation( aComponent.getLocation() );
                   spaceUsed -= aComponent.getSize().width;
         * Calculates the minimum size dimensions for the specified
         * container, given the components it contains.
         * @param parent the component to be laid out
         * @see #preferredLayoutSize
         public Dimension minimumLayoutSize(Container parent)
              return extenderButton.getMinimumSize();
         /** Calculates the preferred size dimensions for the specified
         * container, given the components it contains.
         * @param parent the container to be laid out
         * @see #minimumLayoutSize
         public Dimension preferredLayoutSize(Container parent)
              //  Move all components to the container and remove the extender button
              parent.remove(extenderButton);
              while ( extenderPopup.getComponentCount() > 0 )
                   Component aComponent = extenderPopup.getComponent(0);
                   extenderPopup.remove(aComponent);
                   parent.add(aComponent);
              //  Calculate the width of all components in the container
              Dimension d = new Dimension();
              d.width += parent.getInsets().right + parent.getInsets().left;
              for (int i = 0; i < parent.getComponents().length; i++)
                   d.width += parent.getComponent(i).getPreferredSize().width;
                   d.height = Math.max(d.height,parent.getComponent(i).getPreferredSize().height);
              d.height += parent.getInsets().top + parent.getInsets().bottom + 5;
              return d;
         /** Removes the specified component from the layout.
         * @param comp the component to be removed
         public void removeLayoutComponent(Component comp)
         protected class PopupAction extends AbstractAction
              public PopupAction()
                   super(">");
              public void actionPerformed(ActionEvent e)
                   JComponent component = (JComponent)e.getSource();
                   extenderPopup.show(component,0,component.getHeight());
         public static void main(String[] argv)
              JFrame f = new JFrame();
              JToolBar toolBar = new JToolBar();
              toolBar.setLayout(new ExpandLayout());
              toolBar.add(new JButton("hello"));
              JButton button = new JButton("Hello2");
              System.out.println( button.getInsets() );
              toolBar.add(button);
              System.out.println( button.getInsets() );
              toolBar.add(new JButton("Hello3"));
              toolBar.add(new JButton("Hi"));
              f.getContentPane().setLayout(new BorderLayout());
              f.getContentPane().add(toolBar,BorderLayout.NORTH);
              f.setBounds(0,0,300,300);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.setVisible(true);
    }

  • Doing without layout manager

    Hi guys.
    I have a very complex problem.
    I've been writing a code that should be able to display a general tree. The tree has to look like an organigram, if you know what I mean. For example, the parent node is a the top and the child nodes are underneath it.
    It's clear that there is no layout manager that can handle this correctly. At least I assume.
    I used the Node Positioning of John Walker to compute the x- and y-coordinate of each node.
    I can display the nodes so far, but I don't know how to force a scrollpane to react to the size of the JPanel containing the nodes.
    In fact, the JPanel containing the nodes of the tree has a null layout manager. If it contains let say 10 nodes, it becomes big enough. However the scrollpane doesn't grow along with the panel.
    What should I do to let the scroll pane grow so that all nodes can be seen.
    Regards.
    Edmond

    It's clear that there is no layout manager that can handle this correctly. Correct. So you need to create a custom layout manager.
    I used the Node Positioning of John Walker to compute the x- and y-coordinate of each node. This is the code that should be added to your custom layout manager.
    but I don't know how to force a scrollpane to react to the size of the JPanel containing the nodes.This is the job of the layout manager. It will determine the preferred size of the panel based on the location/size of all the components added to the panel.
    Here is a simple example to get you started. This layout displays the components diagonally:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class NodeLayout implements LayoutManager, java.io.Serializable
         private int hgap = 20;
         private int vgap = 20;
         public NodeLayout()
          * Adds the specified component with the specified name to the layout.
          * @param name the name of the component
          * @param comp the component to be added
         @Override
         public void addLayoutComponent(String name, Component comp) {}
          * Removes the specified component from the layout.
          * @param comp the component to be removed
         @Override
         public void removeLayoutComponent(Component component)
          *     Determine the minimum size on the Container
          *  @param      target   the container in which to do the layout
          *  @return      the minimum dimensions needed to lay out the
          *                subcomponents of the specified container
         @Override
         public Dimension minimumLayoutSize(Container parent)
              synchronized (parent.getTreeLock())
                   return preferredLayoutSize(parent);
          *     Determine the preferred size on the Container
          *  @param      parent   the container in which to do the layout
          *  @return  the preferred dimensions to lay out the
          *              subcomponents of the specified container
         @Override
         public Dimension preferredLayoutSize(Container parent)
              synchronized (parent.getTreeLock())
                   return getLayoutSize(parent);
          *  The calculation for minimum/preferred size it the same. The only
          *  difference is the need to use the minimum or preferred size of the
          *  component in the calculation.
          *  @param      parent  the container in which to do the layout
         private Dimension getLayoutSize(Container parent)
              int components = parent.getComponentCount();
            int width = (components - 1) * hgap;
            int height = (components - 1) * vgap;
              Component last = parent.getComponent(components - 1);
              Dimension preferred = last.getPreferredSize();
              width += preferred.width;
              height += preferred.height;
              Insets parentInsets = parent.getInsets();
              width += parentInsets.top + parentInsets.right;
              height += parentInsets.top + parentInsets.bottom;
              Dimension d = new Dimension(width, height);
              return d;
          * Lays out the specified container using this layout.
          * @param       target   the container in which to do the layout
         @Override
         public void layoutContainer(Container parent)
         synchronized (parent.getTreeLock())
              Insets parentInsets = parent.getInsets();
              int x = parentInsets.left;
              int y = parentInsets.top;
              //  Set bounds of each component
              for (Component component: parent.getComponents())
                   if (component.isVisible())
                        Dimension d = component.getPreferredSize();
                        component.setBounds(x, y, d.width, d.height);
                        x += hgap;
                        y += vgap;
          * Returns the string representation of this column layout's values.
          * @return      a string representation of this layout
         public String toString()
              return "["
                   + getClass().getName()
                   + "]";
         public static void main( String[] args )
              final JPanel panel = new JPanel( new NodeLayout() );
              panel.setBorder( new MatteBorder(10, 10, 10, 10, Color.YELLOW) );
              createLabel(panel);
              createLabel(panel);
              createLabel(panel);
              createLabel(panel);
              createLabel(panel);
              JButton button = new JButton("Add Another Component");
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        NodeLayout.createLabel( panel );
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.add( new JScrollPane(panel) );
              frame.add(button, BorderLayout.SOUTH);
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
         public static void createLabel(JPanel panel)
              JLabel label = new JLabel( new Date().toString() );
              label.setOpaque(true);
              label.setBackground( Color.ORANGE );
              panel.add( label );
              panel.revalidate();
              panel.repaint();
    }You would need to customize the getLayoutSize() and layoutContainer() methods to meet your Node Layout requirements.

  • Which layout manager can do this?

    Heya folks.
    I've been developing a piece of software and laid out the UI by hand (not using any NetBeans or whatever).
    What i have issue with now is setting 3x JTextFields to 33% of the frame's width. Im using GridBagLayout with constraints and cannot achieve that effect.
    Here is the example of what im trying to achieve (and yes its photoshoped, well....actually "MSpaint"ed :P )
    http://i51.tinypic.com/2u7osvb.png
    I want to have a JLabel over each JTextField too.

    Kleopatra wrote:
    Darryl Burke wrote:
    I would nest panels with different layouts to achieve the same result more easily.nesting is for nerds <g> Or slaves, being bound to core LayoutManagers. Or people that post to these forums and expect answers that start with anything other than "Go ask the 3rd party developer..".
    As a side note. Not that I am doubting the power of the LMs you outlined. To read Karsten's* (JGoodies) posts on public forums indicates he has a far better grasp of easy & fluid layout management than is incorporated in many of the core layouts.
    * Disclaimer: I was granted a free license to use JGoodies PLAFs and layouts - though I have been very slack in not using it to full advantage.

  • Suitable layout manager for adding JToolbar?

    Hi there,
    I'm new to Java Swing. I'm looking to add a toolbar to the top of a JFrame. I've created a Grid layout with 3 rows and no columns. I've placed the JToolbar in the first row. Unfortunately, each row in the grid is of equal size so the toolbar is stretched to 1/3rd the size of the JFrame. I want to the toolbar to be standard size but I don't know how to resize the grid rows. I don't want to have to add more rows to reduce the size.
    Can anyone help me here? Or if you have a better layout manager suggestion.
    Thanks,
    Sean

    You can use the default BorderLayout of JFrame and add your JToolBar to the North.

  • Adding Custom Layout Manager

    I'm trying to add my own LayoutManager to JDeveloper following the instructions at http://otn.oracle.com/jdeveloper/help/
    This might help identify the exact page:
    javascript:top.footer.viewTopic('jar%253Afile%253A/u01/webapps/OHW/ohw-app/jdeveloper/helpsets/jdeveloper/developing_gui_clients.jar%2521/ui_paddcustom.html');
    Snip
    JDeveloper supports the integration of other layout managers with its UI Editor. To get a custom layout manager to appear in the Inspector's layout property list, make sure that the layout manager is on the IDEClasspath as defined in JDeveloper\bin\jdeveloper.ini, and add the following line to JDeveloper\bin\addins.properties:
    jdeveloper.uiassistant.<full class name>=oracle.jdeveloper.uidesigner.BasicLayoutAssistant
    End snip
    I don't have jdeveloper.ini anywhere in my hierarchy. At present, I'm setting JDEV_CLASSPATH before starting jdev.exe. Is their a method for providing my own libraries to JDeveloper?
    I have addins.properties, but it is in JDeveloper\jdev\bin and this is the one I'm editing.
    Adding the line above gives the following console message when the UI is started:
    Assistant for com.wb.wfc.FormLayout could not be found: oracle.jdeveloper.uidesigner.BasicLayoutAssistant
    Adding jdeveloper.uiassistant.com.wb.wfc.FormLayout=oracle.jdevimpl.uieditor.assistant.BasicLayoutAssistant (cribbed from other assistants in the addins.properties file) shows my manager in the PropertyInspector, but won't allow it to be selected.
    My manager takes a simple String as it's Constraint. Must I do something else?
    Tony.

    Hello,
    we would like to provide a Layout Manager Support for a custom layout manager in JDev 9.0.3. A short description of how this can be done is provided in den jdev online docs "Developing Java GUI Clients / Working with Layout Manager / Adding Custom Layout Manager". There the javadocs for the oracle.jdevimpl.uieditor package is referenced. We found the classes needed in jdev.jar, but the jdev-doc.jar does not include the javadocs for this package. Can anyone help us with this?
    Regards
    Stefan Unfortunately the uieditor package has not been included in the javadoc distribution. I do not know of a way for you to
    generate the javadoc yourself without the source files. I have logged a bug to have the javadoc included in future releases.
    bug #2697038

  • Does anyone know how to win a fight with layout manager?

    I am using the form designer in netBeans to design my page, which has a jPanel on the left and a number of controls on the right.
    My problem is that when I eventually get it to look half right at design time, it looks different at run time. The fonts are different, the combo boxes are a different height and some of my text boxes are 4 times as wide. http://RPSeaman.googlepages.com/layout.GIF shows both the design-time view and the run-time view. How can I win my fight with layout manager?

    I'd like to do an experiment where you take say 20 pairs of students of java, with each pair matched in terms of prior programming and java experience, general knowledge, etc... and set one of each pair to learn Swing using netbeans and its layout generator with the other pair learning to code Swing by hand. Then 6 months later compare their abilities. I'll bet that the code by hand group will blow the other group out of the water in terms of understanding and ability.
    Just my 2 Sheckel's worth.

  • Delete Crystal Report Design in Report and Layout Manager

    Hi All
    How to permanently delete a customised Crystal Report Design imported in Report and Layout Manager?
    There is no Delete button at all unlike Form Design?
    Kedalene Chong

    Hi Nagarajan
    Please see image attached, already login as superuser but there is no Delete button for imported Crystal Report Design in Report and Layout Manager.

  • Placing components without layout manager not working

    Hey there, I am working on a java game version of pong which I have begun to try and do using Java Swing. The problem I am currently having is reposition the components in the main window part of the game which is were the user can start a new game or close the program. I having tried using the absolute positioning by setting the layout manager to null but then everything goes blank. I can't figure out why this is not working. Here is the code so far...
    import javax.swing.*;
    import java.awt.*;
    public class SwingPractice extends JFrame
        private Container contents;
        private JLabel titleLabel;
        private JButton startGameButton;
        public SwingPractice()
            super("SwingPractice");       
            contents = getContentPane();
            contents.setLayout(null);
            this.getContentPane().setBackground(Color.BLUE);
            startGameButton = new JButton("Start Game");
            startGameButton.setFont(new Font("Visitor TT1 BRK", Font.PLAIN, 24));
            startGameButton.setForeground(Color.cyan);
            startGameButton.setBackground(Color.blue);       
            startGameButton.setBounds(350,350, 75, 75);
            titleLabel = new JLabel("The Amazing Ping Pong Game!!");
            titleLabel.setForeground(Color.cyan);
            titleLabel.setBackground(Color.blue);
            titleLabel.setOpaque(true);
            titleLabel.setFont(new Font("Visitor TT1 BRK", Font.PLAIN, 24));
            titleLabel.setBounds(0,350, 75, 75);
            contents.add(startGameButton);
            contents.add(titleLabel);
            setSize(700,350);
            setResizable(false);
            setVisible(true);
        /*private class SwingPracticeEvents implements ActionListener
        public static void main(String [] args)
            SwingPractice window = new SwingPractice();
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       Any other critiquing would be greatly appreciated. Thank you.
    Edited by: 804210 on Oct 21, 2010 1:30 PM

    804210 wrote:
    Hey there, I am working on a java game version of pong which I have begun to try and do using Java Swing. The problem I am currently having is reposition the components in the main window part of the game which is were the user can start a new game or close the program. I having tried using the absolute positioning by setting the layout manager to nullDon't. Ever. Never. Well, mostly.
    Read the tutorial chapter about [url http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html]Laying out components. It even features a section on absolute positioning - which you should skip reading, of course! :o)
    And read this old Sun topic: http://forums.sun.com/thread.jspa?threadID=5411066
    Edited by: jduprez on Oct 21, 2010 10:48 PM

  • Report & Layout Manager

    Hi,
    I have created User defined form. Now i have to display report when click on Preview button (Same as Standard document).
    Can we use report & layout manager to display report.
    Regards,
    Pravin

    Hello
    possible with development, and it is pending from the B1 version.
    Easy solutions are:
    - 8.81 you can use Crystal Reports and PLD
    - 2007 you can use PLD only or CR integration addon
    in Crystal:
    - You can create your layout and you can import into the system as report (not layout) into a specific folder
    - When you press the print or print preview button (eg menu action is indicated, menu id "520", "519"), then you can find the crystal report in the OCMN table with the following query
    select MenuUID from OCMN where Name = N'YOUR_REPORT_NAME'
    - next step is call the report with ActivateMenuItem and fill the parameters.
    Complete code for crystal
                Dim oRs As SAPbobsCOM.Recordset = oCompany.GetBusinessObject(BoObjectTypes.BoRecordset)
                Dim sQuery As String
                Dim sMenuID As String
                sQuery = "select MenuUID from OCMN where Name = N'YOUR_REPORT_NAME"
                oRs.DoQuery(sQuery)
                If oRs.Fields.Count > 0 Then
                    sMenuID = oRs.Fields.Item("MenuUID").Value.ToString
                    m_SBO_Application.ActivateMenuItem(sMenuID)
                    Dim oForm As SAPbouiCOM.Form = SBO_Application.Forms.ActiveForm
                    oForm.Items.Item("1000003").Specific.String = docentry
                    m_CrystalCriteriaFormID = oForm.UniqueID
                    oForm.Items.Item("1").Click(BoCellClickType.ct_Regular)
                Else : m_SBO_Application.MessageBox("NO PRINTING LAYOUT EXISTS!")
                End If
    In PLD, the logic is the same, but you must activate the User Queries print layout, and locate the report in the matrix.
    Regards
    János

  • Need suggestion regarding Layout Manager using Swing in Java

    I have developed a swing application where i am having problem with selecting the right layout manager.
    I am attaching the file where it contains the method for addingComponents to the Content Pane. But, the code that i have written
    contains lot of spaces between first panel and second panel and so forth.
    Please suggest.
    <<Code>>
    public void addComponentsToPane(Container contentPane) {
              this.contentPane = contentPane;
    //          File Panel
              JPanel jfile1panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              JPanel jfile2panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              JPanel jfile3panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              JLabel jfile1 = new JLabel("Select File:");
              jtfile1 = new JTextField(50);
              jbfile1 = new JButton("Button1");
              jfile1panel.add(jfile1);
              jfile1panel.add(jtfile1);
              jfile1panel.add(jbfile1);
              jbfile1.addActionListener(this);
              JLabel jfile2 = new JLabel("Select File:");
              jtfile2 = new JTextField(50);
              jbfile2 = new JButton("Button2");
              jfile2panel.add(jfile2);
              jfile2panel.add(jtfile2);
              jfile2panel.add(jbfile2);
              jbfile2.addActionListener(this);
              JLabel jfile3 = new JLabel("Select File:");
              jtfile3 = new JTextField(50);
              jbfile3 = new JButton("Button3");
              jfile3panel.add(jfile3);
              jfile3panel.add(jtfile3);
              jfile3panel.add(jbfile3);
              jbfile3.addActionListener(this);
              //Button Panel
              JPanel jbuttonpanel = new JPanel();
              jbuttonpanel.setLayout(new FlowLayout(FlowLayout.CENTER));
              JButton jbcmd1 = new JButton("Submit");
              JButton jbcmd2 = new JButton("Cancel");
              jbuttonpanel.add(jbcmd1);
              jbuttonpanel.add(jbcmd2);
              jbcmd1.addActionListener(this);
              jbcmd2.addActionListener(this);
              //Content Pane               
              contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
              contentPane.add(jfile1panel);
              contentPane.add(jfile2panel);
              contentPane.add(jfile3panel);
              contentPane.add(jbuttonpanel);
    }

    But, the code that i have written contains lot of spaces between first panel and second panel and so forth.use pack(), see if it makes a difference
    as you're using FlowLayout, make the frame not resizable

  • Layout Management in Table Control

    Hi Dialog Programming Experts,
    I have a new requirement - adding Layout Management options in Table Control. This is dialog/module programming, not ALV Report. Is there a function module for this?
    Thanks so much in advance for your help.
    Regards,
    Joyreen

    Hi
    For filter use the following function modules,
    l_rightx-id = l_index.
      l_rightx-fieldname = 'DESCR'.
      l_rightx-text = text-054.
      APPEND l_rightx TO i_rightx.
      l_index = l_index + 1.
      CLEAR l_rightx.
      l_rightx-id = l_index.
      l_rightx-fieldname = 'DEL_CM'.
      l_rightx-text = text-055.
      APPEND l_rightx TO i_rightx.
    CALL FUNCTION 'CEP_DOUBLE_ALV'
           EXPORTING
                i_title_left  = text-034
                i_title_right = text-035
                i_popup_title = text-036
           IMPORTING
                e_cancelled   = l_cancelled
           TABLES
                t_leftx       = i_leftx[]
                t_rightx      = i_rightx[].
    Firstly populate the right table with all fields which you want in the filtering condition. The left table will be populated once the use selects some fields and transfer it to the left portion of the dialog.
    Then use the following FM like this.
    DATA: i_group TYPE lvc_t_sgrp.
          CALL FUNCTION 'LVC_FILTER_DIALOG'
               EXPORTING
                    it_fieldcat   = i_fldcat1
                    it_groups     = i_group
               TABLES
                    it_data       = i_ziteminvoice[]
               CHANGING
                    ct_filter_lvc = i_filter
               EXCEPTIONS
                    no_change     = 1
                    OTHERS        = 2.
    here filter table should have fields from left table above.
    Once you get the filter data, populate range table for each fields and then delete your internal table using these range.
    CASE l_filter-fieldname.
                  WHEN 'ITMNO'.
                    l_itmno-sign = l_filter-sign.
                    l_itmno-option = l_filter-option.
                    l_itmno-low = l_filter-low.
                    l_itmno-high = l_filter-high.
                    APPEND l_itmno TO li_itmno.
                    CLEAR l_itmno.
    DELETE i_ziteminvoice WHERE NOT  itmno IN li_itmno OR
                                          NOT  aedat IN li_aedat OR...
    First check this if it works, else let me know.
    Thanks
    Sourav.

  • Missing reports in Report and Layout manager

    Hi Experts,
    i need to convert with Crystal Converter some PLD Tax reports.
    The problem is that under Tax Reports tree, in report and layout manager, reports of typecode 'RB01' are missing!
    Why are they missing??
    Is there any other way to convert them even if missing?
    i can see them in the tax report form, selecting tax register block and press ok.
    From the print layout designer they are listed.
    Please help.
    Thanks
    Paolo

    Hi Paolo,
    What is your B1 PL? Have you solved your problem? Try to upgrade to the latest PL if you are not in it.
    Thanks,
    Gordon

  • The most precise layout manager

    It's time to decide on a layout. My java game screen is a fairly complex jumble of info in little boxes here and there. Everywhere.
    I'm not a java pro yet, but am I correct in thinking that there is -no- pixel grid layout manager? Meaning, I could define the coords for each element? I don't think there is one like that.
    All that being said, what java layout manager gives you the most precise control over element placement? It looks like the Box or GridBag, but I'm not certain.
    Thank you in advance for your expert oppinion :-)
    Mark Deibert

    From my experience I've found that using a combination
    of layout managers works best for fine tuning things.
    For example you can create a panel for your buttons
    implementing a flow layout then a panel for your
    checkboxes using a gridbag layout etc.
    The code might not be as neat as using a single
    manager but it does give you more control on where
    things go by breaking the GUI up into more manageable
    pieces.I agree with that - I really never use absolute postioning. Think in an object oriented way when you choose LayoutManagers - arrange all components, that are displayable by the same LayoutManager in a separate JPanel with this LayoutManager - add only those components, which are in the same context to that, what this JPanel should do.
    For example - when you want some buttons to show up in the center of JPanel, use two JPanels, one with FlowLayout, where you add the buttons, and add this JPanel to a second one with BorderLayout to its center. If you now want to place these buttons to the bottom of another panel, you easily add it to a JPanel with BorderLayout to its bottom - the hole JPanel, not the buttons. That is also quite fine if you want to repostion those functional units later on - components, that are in a relation to each other will stay together this way and must not be repositioned component by component.
    greetings Marsian

Maybe you are looking for