GridBagLayout Question???

I am new to Java and I am trying to create a window with the fhe fields starting at gridx=0 and gridy=0 but I get the fields centered in the middle of the window. Is there a problem with my code????
Thanks
Ralph
import javax.swing.*;
import java.awt.*;
public class SwingWindow extends JFrame
private GridBagLayout layout;
private GridBagConstraints constraints;
private Container container;
// setup GUI
public SwingWindow()
super("Java Test Window");
container = getContentPane();
layout = new GridBagLayout();
container.setLayout( layout );
// instantiate gridbag contraints
constraints = new GridBagConstraints();
// create GUI Components
JLabel textLabel = new JLabel("Name : ");
JTextField text = new JTextField("",15);
JLabel textLabel2 = new JLabel("Address : ");
JTextField text2 = new JTextField("",15);
// define GUI Component constraints for Textlabel
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.fill = GridBagConstraints.BOTH;
addComponent(textLabel);
// define GUI Component constraints for TextField
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.gridx = 1;
constraints.gridy = 0;
constraints.fill = GridBagConstraints.BOTH;
addComponent(text);
// define GUI Component constraints for Textlabel2
constraints.gridwidth = 1;
constraints.gridx = 0;
constraints.gridy = 1;
constraints.fill = GridBagConstraints.BOTH;
addComponent(textLabel2);
// define GUI Component constraints for TextField2
constraints.gridwidth = 1;
constraints.gridx = 1;
constraints.gridy = 1;
constraints.fill = GridBagConstraints.BOTH;
addComponent(text2);
setSize( 500, 400);
setVisible( true );
} //end constructor
//add a components to the container
private void addComponent( Component component)
layout.setConstraints( component, constraints);
container.add( component );
public static void main(String args [] )
SwingWindow application = new SwingWindow();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
} // End of SwingWindow

Ever hear the expression "Don't try this at home"?
The GridBagLayout is the most powerful and also the most confusing and frustrating layout manager you can use. It's powerful because you can do almost anything with it. It is confusing and frustrating because one little oopsie can send the whole house of cards tumbling down.
You should only use it if you either
are very experienced with layout managers in general
or
are willing to do a lot of research and experimentation.
In your case the problem is caused by one leeeeeetle omission; you forgot to assign weights to the components; all of your constraints have a weight of 0 (although why this completely blows your orientation is still a mystery to me).
Try thisimport javax.swing.*;
import java.awt.*;
public class LayoutDemo extends JFrame
  private GridBagLayout layout;
  private GridBagConstraints constraints;
  private Container container;
  // setup GUI
  public LayoutDemo()
    super ("Java Test Window");
    setSize (500, 400);
    container = getContentPane();
    layout = new GridBagLayout();
    container.setLayout (layout);
    // instantiate gridbag constraints
    constraints = new GridBagConstraints();
    // create GUI Components
    JLabel textLabel = new JLabel ("Name : ");
    JTextField text = new JTextField ("",15);
    JLabel textLabel2 = new JLabel ("Address : ");
    JTextField text2 = new JTextField ("",15);
    // Define global constraints all components
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.weightx = 0;
    constraints.weighty = 0;
    constraints.anchor = GridBagConstraints.NORTHWEST;
    constraints.fill = GridBagConstraints.NONE;
    constraints.insets = new Insets (3, 3, 3, 3); // Leave some space between controls
    // define specific constraints for Textlabel
    constraints.gridx = 0;
    constraints.gridy = 0;
    addComponent (textLabel);
    // define GUI Component constraints for Textlabel2
    constraints.gridx = 0;
    constraints.gridy = 1;
    constraints.weighty = 1.0;
    addComponent (textLabel2);
    // define GUI Component constraints for TextField
    constraints.gridx = 1;
    constraints.gridy = 0;
    constraints.weightx = 1.0;
    constraints.weighty = 0;
    constraints.fill = GridBagConstraints.HORIZONTAL;
    addComponent (text);
    // define GUI Component constraints for TextField2
    constraints.gridx = 1;
    constraints.gridy = 1;
    constraints.weighty = 1.0;
    addComponent (text2);
    setVisible (true );
    return;
    // Enumerate the components with their constraints (debug only)
    Component[] allControls = container.getComponents();
    for (int i = 0; i < allControls.length; ++i)
      GridBagConstraints currentConstraints = layout.getConstraints (allControls );
System.out.println ("x/y = " +
currentConstraints.gridx + ", " +
currentConstraints.gridy +
"; w/h = " +
currentConstraints.gridwidth + ", " +
currentConstraints.gridheight);
} //end constructor
//add a components to the container
private void addComponent( Component component)
layout.setConstraints( component, constraints);
container.add( component );
public static void main (String args [])
JFrame application = new LayoutDemo();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
} // End of SwingWindow

Similar Messages

  • Another GridBagLayout question

    I still don't get it. Why is it that the weightx is not working properly? The proportion between the label and textfield is greater than the insets I have specified which is 5. Could someone help please.
    JLabel l;
    JComponent comp;             
    JPanel panel = new JPanel();
    panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    comp = new JPanel(new GridBagLayout());
    comp.setBorder(BorderFactory.createTitledBorder(""));
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.WEST;
    gbc.fill = GridBagConstraints.NONE;
    gbc.insets = new Insets(5, 5, 5, 5);
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.weightx = .1;
    l = new JLabel("ID", JLabel.LEFT);  // This lines up correctly
    comp.add(l, gbc);
    gbc.gridx++;
    gbc.weightx = .9;
    supplierID = new JTextField(5); // This is too far from the label
    comp.add(supplierID, gbc);
    gbc.gridx = 0;
    gbc.gridy++;
    l = new JLabel("Supplier", JLabel.LEFT);
    comp.add(l, gbc);
    gbc.gridx++;
    supplierName = new JTextField("supplier name", 30);             
    comp.add(supplierName, gbc);          
    panel.add(comp);
    comp = new JPanel(new GridBagLayout());
    comp.setBorder(BorderFactory.createTitledBorder("Address"));
    gbc.gridx = 0;
    gbc.gridy = 0;
    l = new JLabel("Mail Addr", JLabel.LEFT);
    comp.add(l, gbc);
    gbc.gridx++;
    supplierAddress1 = new JTextField(20);
    comp.add(supplierAddress1, gbc);
    gbc.gridx++;
    l = new JLabel("Ship Addr", JLabel.LEFT);
    comp.add(l, gbc);
    gbc.gridx++;
    supplierAddress2 = new JTextField(20);
    comp.add(supplierAddress2, gbc);             
    panel.add(comp);            
    return panel;

    Hi allenvpn,
    The weights are used to figure out where to add the extra space to. When dealing with labels you should have their weights set to zero because there is no need to expand them.
    You just have to make the weightx zero for your labels: (ID, Supplier) and make the weightx one for your textfields.
    gbc.weigthx = 0;
    l = new JLabel("ID", JLabel.LEFT); // This lines up correctly
    comp.add(l, gbc);
    gbc.weightx = 1;
    supplierName = new JTextField("supplier name", 30);      
    comp.add(supplierName, gbc);
    gbc.weightx = 0;
    l = new JLabel("Supplier", JLabel.LEFT);
    comp.add(l, gbc);
    gbc.weightx = 1;
    supplierName = new JTextField("supplier name", 30);      
    comp.add(supplierName, gbc);
    This will allow your textfields to align on the left side just beyond the longest label.
    Regards,
    Manfred.

  • GridBagLayout - Question about Creating Borders for Cells

    Hello Everyone,
    I am implementing a table-like design using a Grid Bag Layout and I do not wish to use a J Table. Since a grid bag layout utilizes cells (rows and columns) to create its' design, I was wondering if any of you knew of a way to create borders for the cells inside of a Grid Bag Layout.
    The reason I ask is because, lets say for instance cell (1, 0) may occupy a single J Label. I can easily create a border for this particular cell or label, by calling label.setBorder(). However, what if a single cell occupied two JLabels and they were sort of strangely aligned. I wouldn't be able to call setBorder on the labels anymore because that will just create two separate sets of borders. What I want to do is create a border for that particular cell.
    The final result that I want it to look like is almost identical to a J Table where all the rows and columns have separating lines between all the cells. Something similar to this...
    http://www.wwffinc.com/other-images/table1-693771.jpg
    Thanks in advance!
    Brian

    However, what if a single cell occupied two JLabels and they were sort of strangely aligned. I wouldn't be able to call setBorder on the labels anymore because that will just create two separate sets of bordersThen create a panel and add the two labels to the panel. Then add the border to the panel.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.

  • Question about gridbaglayout

    hi all,
    i am developing an application that is run on windows and unix. my resolution is 800x600 the resolution of the unix box is 1024x768. when i develop the app on my computer using setbounds to place components where i want them to be and then run it on the unix machine the components do not expand to the resolution. will gridbaglayout solve this problem for me or do i need to look at other avenues.
    thanks

    by Design when your resize a Java window, all its components will be resized too.
    You told aboout setBounds... it is not a good deal... Try to use gridBagLayout and set the relathionship between a window components...
    are you using setDimension ??
    yes, GridBagLayout should solve all your problems...
    an example? http://www.lia.ufc.br/~gaucho/Arm/Demo.htm

  • GridBagLayout & Canvas question

    I hit a snag during my homework assignment. I am in the making of a RTS game, and want to draw on a Canvas, which I'm placing within a Panel that has a GridbagLayout using the following code:
    pane = new Panel(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    //pane.add(new Label(), c);
    c.gridx = 0;
    c.gridy = 0;
    c.fill = GridBagConstraints.BOTH;
    pane.add(field, c);As I understand this should place and size the field (Canvas) to fill out all the available space in the panel, but all I see is a big white nothing. http://users.hszk.bme.hu/~fm649/javasnag0.png The funny thing is that if I delete the comment tag before
    pane.add(new Label(), c);then I actually get what I wanted, the field (Canvas) is drawn correctly in the appropriate place and size (except for the label itself in the center of the window). http://users.hszk.bme.hu/~fm649/javasnag1.png Any ideas why is this happening?
    Thanks in advance, Mike

    the making of a RTS game, and want to draw on a
    Canvas, which I'm placing within a Panel that has aYou want to draw on a canvas? By default canvas is not equiped to do this. If you want a canvas you can draw on, check out my code below. If you are using AWT instead of swing you might have to modify this a little, but it shouldn't be too hard
    You are welcome to use and modify this code, but please do not change the package or take credit for it as your own work.
    tjacobs.ui.PaintArea.java
    ====================
    * Created on Jun 15, 2005 by @author Tom Jacobs
    package tjacobs.ui;
    import java.awt.image.BufferedImage;
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.ImageIcon;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    import javax.swing.SwingUtilities;
    import tjacobs.MathUtils;
    * PaintArea is a component that you can draw in similar to but
    * much simpler than the windows paint program.
    public class PaintArea extends JComponent {
         BufferedImage mImg; //= new BufferedImage();
         int mBrushSize = 1;
         private boolean mSizeChanged = false;
         private Color mColor1, mColor2;
         static class PaintIcon extends ImageIcon {
              int mSize;
              public PaintIcon(Image im, int size) {
                   super(im);
                   mSize = size;
         public PaintArea() {
              super();
              setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
              addComponentListener(new CListener());
              MListener ml = new MListener();
              addMouseListener(ml);
              addMouseMotionListener(ml);
              setBackground(Color.WHITE);
              setForeground(Color.BLACK);
         public void paintComponent(Graphics g) {
              if (mSizeChanged) {
                   handleResize();
              //g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
              g.drawImage(mImg, 0, 0, null);
              //super.paintComponent(g);
              //System.out.println("Image = " + mImg);
              //System.out.println("Size: " + mImg.getWidth() + "," + mImg.getHeight());
         public void setBackground(Color c) {
              super.setBackground(c);
              if (mImg != null) {
                   Graphics g = mImg.getGraphics();
                   g.setColor(c);
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
         public void setColor1(Color c) {
              mColor1 = c;
         public void setColor2(Color c) {
              mColor2 = c;
         public Color getColor1() {
              return mColor1;
         public Color getColor2() {
              return mColor2;
         class ToolBar extends JToolBar {
              ToolBar() {
                   final ColorButton fore = new ColorButton();
                   fore.setToolTipText("Foreground Color");
                   final ColorButton back = new ColorButton();
                   back.setToolTipText("Background Color");
                   JComboBox brushSize = new JComboBox();
                   //super.createImage(1, 1).;
                   FontMetrics fm = new FontMetrics(getFont()) {};
                   int ht = fm.getHeight();
                   int useheight = fm.getHeight() % 2 == 0 ? fm.getHeight() + 1 : fm.getHeight();
                   final BufferedImage im1 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = im1.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2, useheight / 2, 1, 1);
                   g.dispose();
                   //im1.setRGB(useheight / 2 + 1, useheight / 2 + 1, 0xFFFFFF);
                   final BufferedImage im2 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im2.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 1, useheight / 2 - 1, 3, 3);
                   g.dispose();
    //               im2.setRGB(useheight / 2 - 1, useheight / 2 - 1, 3, 3, new int[] {     0, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0}, 0, 1);
                   final BufferedImage im3 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im3.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 2, useheight / 2 - 2, 5, 5);
                   g.dispose();
    //               im3.setRGB(useheight / 2 - 2, useheight / 2 - 2, 5, 5, new int[] {     0, 0, 0xFFFFFF, 0, 0, 
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0, 0, 0xFFFFFF, 0, 0}, 0, 1);
                   //JLabel l1 = new JLabel("1 pt", new ImageIcon(im1), JLabel.LEFT);
                   //JLabel l2 = new JLabel("3 pt", new ImageIcon(im2), JLabel.LEFT);
                   //JLabel l3 = new JLabel("5 pt", new ImageIcon(im3), JLabel.LEFT);
                   brushSize.addItem(new PaintIcon(im1, 1));
                   brushSize.addItem(new PaintIcon(im2, 3));
                   brushSize.addItem(new PaintIcon(im3, 5));
                   //brushSize.addItem("Other");
                   add(fore);
                   add(back);
                   add(brushSize);
                   PropertyChangeListener pl = new PropertyChangeListener() {
                        public void propertyChange(PropertyChangeEvent ev) {
                             Object src = ev.getSource();
                             if (src != fore && src != back) {
                                  return;
                             Color c = (Color) ev.getNewValue();
                             if (ev.getSource() == fore) {
                                  mColor1 = c;
                             else {
                                  mColor2 = c;
                   fore.addPropertyChangeListener("Color", pl);
                   back.addPropertyChangeListener("Color", pl);
                   fore.changeColor(Color.BLACK);
                   back.changeColor(Color.WHITE);
                   brushSize.addItemListener(new ItemListener() {
                        public void itemStateChanged(ItemEvent ev) {
                             System.out.println("ItemEvent");
                             if (ev.getID() == ItemEvent.DESELECTED) {
                                  return;
                             System.out.println("Selected");
                             Object o = ev.getItem();
                             mBrushSize = ((PaintIcon) o).mSize;
                   //Graphics g = im1.getGraphics();
                   //g.fillOval(0, 0, 1, 1);
                   //BufferedImage im1 = new BufferedImage();
                   //BufferedImage im1 = new BufferedImage();
         protected class MListener extends MouseAdapter implements MouseMotionListener {
              Point mLastPoint;
              public void mouseDragged(MouseEvent me) {
                   Graphics g = mImg.getGraphics();
                   if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                        g.setColor(mColor1);
                   } else {
                        g.setColor(mColor2);
                   Point p = me.getPoint();
                   if (mLastPoint == null) {
                        g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        //g.drawLine(p.x, p.y, p.x, p.y);
                   else {
                        g.drawLine(mLastPoint.x, mLastPoint.y, p.x, p.y);
                        //g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        double angle = MathUtils.angle(mLastPoint, p);
                        if (angle < 0) {
                             angle += 2 * Math.PI;
                        double distance = MathUtils.distance(mLastPoint, p) * 1.5;
                        if (angle < Math.PI / 4 || angle > 7 * Math.PI / 4 || Math.abs(Math.PI - angle) < Math.PI / 4) {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x, mLastPoint.y + i, p.x, p.y + i);
                                  g.drawLine(mLastPoint.x, mLastPoint.y - i, p.x, p.y - i);
    //                              System.out.println("y");
    //                              System.out.println("angle = " + angle / Math.PI * 180);
                        else {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x + i, mLastPoint.y, p.x + i, p.y);
                                  g.drawLine(mLastPoint.x  - i, mLastPoint.y, p.x - i, p.y);
    //                              System.out.println("x");
    //                    System.out.println("new = " + PaintUtils.printPoint(p));
    //                    System.out.println("last = " + PaintUtils.printPoint(mLastPoint));
                        //System.out.println("distance = " + distance);
                        //Graphics2D g2 = (Graphics2D) g;
                        //g2.translate(mLastPoint.x + mBrushSize / 2, mLastPoint.y);
                        //g2.rotate(angle);
                        //g2.fillRect(0, 0, (int) Math.ceil(distance), mBrushSize);
                        //g2.rotate(-angle);
                        //g2.translate(-mLastPoint.x + mBrushSize / 2, -mLastPoint.y);
    //                    g.setColor(Color.RED);
    //                    g.drawRect(p.x, p.y, 1, 1);
                   mLastPoint = p;
                   g.dispose();
                   repaint();
              public void mouseMoved(MouseEvent me) {}
              public void mouseReleased(MouseEvent me) {
                   mLastPoint = null;
         private void handleResize() {
              Dimension size = getSize();
              mSizeChanged = false;
              if (mImg == null) {
                   mImg = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
                   Graphics g = mImg.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
              else {
                   int newWidth = Math.max(mImg.getWidth(),getWidth());
                   int newHeight = Math.max(mImg.getHeight(),getHeight());
                   if (newHeight == mImg.getHeight() && newWidth == mImg.getWidth()) {
                        return;
                   BufferedImage bi2 = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = bi2.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, bi2.getWidth(), bi2.getHeight());
                   g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
                   g.dispose();
                   mImg = bi2;
         public JToolBar getToolBar() {
              if (mToolBar == null) {
                   mToolBar = new ToolBar();
              return mToolBar;
         private ToolBar mToolBar;
         public static void main (String args[]) {
              PaintArea pa = new PaintArea();
              JPanel parent = new JPanel();
              parent.setLayout(new BorderLayout());
              parent.add(pa, BorderLayout.CENTER);
              pa.setPreferredSize(new Dimension(150, 150));
              parent.add(pa.getToolBar(), BorderLayout.NORTH);
              WindowUtilities.visualize(parent);
         protected class CListener extends ComponentAdapter {
              public void componentResized(ComponentEvent ce) {
                   mSizeChanged = true;
    MathUtils.java
    ===========
    * Created on Nov 7, 2004 by @author Tom Jacobs
    package tjacobs;
    import java.awt.Point;
    * Simple math routines spelled out. There's euclideanDistance, factorial,
    * combinations, distance.<p>
    * Pretty standard really.
    public class MathUtils {
         private MathUtils() {
              super();
         public static double euclideanDistance(Point p1, Point p2) {
              return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
         public static int factorial(int x) {
              int pow = 1;
              while (x > 1) {
                   pow = pow * x;
                   x--;
              return pow;
         public static int getCombinations(int total, int picks, boolean replacing, boolean ordered) {
              int ans = 0;
              if (replacing && ordered) {
                   ans = (int)Math.pow(total, picks);
                   //total / Math.pow(totalpicks)
              else if (!replacing && ordered){
                   ans = factorial (total);
                   ans /= factorial(total - picks);
              } else if (replacing && !ordered) {
                   ans = factorial(total + picks - 1);
                   ans /= factorial(picks);
                   ans /= factorial(total - picks);
              else if (!replacing && !ordered) {
                   ans = factorial(total);
                   ans/= factorial(picks);
                   ans/= factorial(total - picks);               
              return ans;
         public static double distance (Point p1, Point p2) {
              return distance(p1.x, p1.y, p2.x, p2.y);
         public static double distance(double x1, double y1) {
              return distance(x1, y1, 0, 0);
         public static double distance (double x1, double y1, double x2, double y2) {
              return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
         public static double angle (Point p1, Point p2) {
              return angle(p1.x, p1.y, p2.x, p2.y);
         public static double angle (double x1, double y1, double x2, double y2) {
              double xdiff = x1 - x2;
              double ydiff = y1 - y2;
              double tan = xdiff / ydiff;
              double atan = Math.atan2(ydiff, xdiff);
              return atan;
         public static double reflectOff(double ray, double reflectOff) {
              return reflectOff + reflectOff - ray;
         //Testing only
    /*     public static void main(String args[]) {
              System.out.println(reflectOff(0, Math.PI / 4) / Math.PI);
              System.out.println(reflectOff(Math.PI / 2, Math.PI) / Math.PI);
              System.out.println(reflectOff(5 * Math.PI / 4, Math.PI / 2) / Math.PI);
              System.out.println(reflectOff(Math.PI, Math.PI / 2));
    WindowUtils.java
    ===============
    package tjacobs.ui;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.ImageIcon;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.JPopupMenu;
    import javax.swing.Popup;
    import javax.swing.SwingUtilities;
    public abstract class WindowUtilities {
         public static final int RESIZE_MARGIN_SIZE = 4;
         private static Window sExitWindow = null;
         public static interface CreatePopupWindow {
              public JDialog createPopupWindow(Point p);
         * Returns an point which has been adjusted to take into account of the
         * desktop bounds, taskbar and multi-monitor configuration.
         * <p>
         * This adustment may be cancelled by invoking the application with
         * -Djavax.swing.adjustPopupLocationToFit=false
        public static Point adjustPopupLocationToFitScreen(Component popup, Component invoker, int xposition, int yposition) {
         Point p = new Point(xposition, yposition);
            if(//popupPostionFixDisabled == true ||
                        GraphicsEnvironment.isHeadless())
                return p;
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            Rectangle screenBounds;
            Insets screenInsets;
            GraphicsConfiguration gc = null;
            // Try to find GraphicsConfiguration, that includes mouse
            // pointer position
            GraphicsEnvironment ge =
                GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice[] gd = ge.getScreenDevices();
            for(int i = 0; i < gd.length; i++) {
                if(gd.getType() == GraphicsDevice.TYPE_RASTER_SCREEN) {
    GraphicsConfiguration dgc =
    gd[i].getDefaultConfiguration();
    if(dgc.getBounds().contains(p)) {
    gc = dgc;
    break;
    // If not found and we have invoker, ask invoker about his gc
    if(gc == null && invoker != null) {
    gc = invoker.getGraphicsConfiguration();
    if(gc != null) {
    // If we have GraphicsConfiguration use it to get
    // screen bounds and insets
    screenInsets = toolkit.getScreenInsets(gc);
    screenBounds = gc.getBounds();
    } else {
    // If we don't have GraphicsConfiguration use primary screen
    // and empty insets
    screenInsets = new Insets(0, 0, 0, 0);
    screenBounds = new Rectangle(toolkit.getScreenSize());
    int scrWidth = screenBounds.width -
    Math.abs(screenInsets.left+screenInsets.right);
    int scrHeight = screenBounds.height -
    Math.abs(screenInsets.top+screenInsets.bottom);
    Dimension size;
    size = popup.getPreferredSize();
    if( (p.x + size.width) > screenBounds.x + scrWidth )
    p.x = screenBounds.x + scrWidth - size.width;
    if( (p.y + size.height) > screenBounds.y + scrHeight)
    p.y = screenBounds.y + scrHeight - size.height;
    /* Change is made to the desired (X,Y) values, when the
    PopupMenu is too tall OR too wide for the screen
    if( p.x < screenBounds.x )
    p.x = screenBounds.x ;
    if( p.y < screenBounds.y )
    p.y = screenBounds.y;
    return p;
         public static MouseListener addAsPopup(final CreatePopupWindow cpw, Component owner) {
              if (cpw == null || owner == null) {
                   return null;
              MouseListener ml = new MouseAdapter() {
                   CreatePopupWindow create = cpw;
                   public void mousePressed(MouseEvent ev) {
                        testPopup(ev);
                   public void mouseReleased(MouseEvent ev) {
                        testPopup(ev);
                   private void testPopup(MouseEvent ev) {
                        if (ev.isPopupTrigger()) {
                             final JDialog pop = create.createPopupWindow(ev.getPoint());
                             //pop.setUndecorated(true);
                             if (pop == null) {
                                  return;
                             Window w = SwingUtilities.getWindowAncestor(ev.getComponent());
                             pop.setLocation(ev.getX() + w.getX(), ev.getY() + w.getY());
                             pop.pack();
                             pop.addWindowListener(new WindowAdapter() {
                                  public void windowDeactivated(WindowEvent we) {
                                       pop.dispose();
                             pop.setFocusableWindowState(true);
                             pop.setVisible(true);
                             pop.requestFocus();
                             //pop.show();
              owner.addMouseListener(ml);
              return ml;
         public static MouseListener addAsPopup(final JPopupMenu popup, Component owner) {
              if (popup == null || owner == null) {
                   return null;
              //popup.setUndecorated(true);
              MouseListener ml = new MouseAdapter() {
                   JPopupMenu pop = popup;
                   public void mousePressed(MouseEvent ev) {
                        testPopup(ev);
                   public void mouseReleased(MouseEvent ev) {
                        testPopup(ev);
                   private void testPopup(MouseEvent ev) {
                        if (ev.isPopupTrigger()) {
                             //pop.setLocation(ev.getPoint());
                             //pop.pack();
                             //pop.setVisible(true);
                             //JPopupMenu pop = new JPopupMenu();
                             //pop.add(new JMenuItem("Hi"));
                             pop.show(ev.getComponent(), ev.getX(), ev.getY());
              owner.addMouseListener(ml);
              return ml;
         public static MouseListener addAsPopup(final JDialog popup, Component owner) {
              if (popup == null || owner == null) {
                   return null;
              //popup.setUndecorated(true);
              MouseListener ml = new MouseAdapter() {
                   Window pop = popup;
                   public void mousePressed(MouseEvent ev) {
                        testPopup(ev);
                   public void mouseReleased(MouseEvent ev) {
                        testPopup(ev);
                   private void testPopup(MouseEvent ev) {
                        if (ev.isPopupTrigger()) {
                             pop.setLocation(ev.getPoint());
                             pop.pack();
                             pop.setVisible(true);
              owner.addMouseListener(ml);
              return ml;
         public static Point getBottomRightOfScreen(Component c) {
         Dimension scr_size = Toolkit.getDefaultToolkit().getScreenSize();
         Dimension c_size = c.getSize();
         return new Point(scr_size.width - c_size.width, scr_size.height - c_size.height);
         public static Window visualize(Component c) {
              return visualize(c, sExitWindow == null);
         public static Window visualize(Image im) {
              return visualize(new JLabel(new ImageIcon(im)));
         public static Window visualize (Component c, int width, int height) {
              return visualize(c, sExitWindow == null, width, height);
         public static Window visualize(Component c, boolean exit, int width, int height) {
              JFrame f;
              Window w;
              if (c instanceof Window) {
                   w = (Window) c;
              else {
                   f = new JFrame();
                   f.getContentPane().add(c);
                   w = f;
              // to be thread safe, this should be synchonized.
              // but it doesn't really matter in everyday situations
              if (sExitWindow == null) {
                   sExitWindow = w;
              w.setSize(width, height);
              w.setLocation(100, 100);
              if (exit) {
                   w.addWindowListener(new WindowClosingActions.Exit());
              w.setVisible(true);
              return w;          
         public void center(Window w) {
              Dimension dim = w.getSize();
              Dimension scr = Toolkit.getDefaultToolkit().getScreenSize();
              w.setLocation((scr.width - dim.width)/2, (scr.height - dim.height)/2);
         public static Window visualize(Component c, boolean exit) {
              JFrame f;
              Window w;
              if (c instanceof Window) {
                   w = (Window) c;
              else {
                   f = new JFrame();
                   f.getContentPane().add(c);
                   w = f;
              w.pack();
              w.setLocation(100, 100);
              if (exit) {
                   w.addWindowListener(new WindowClosingActions.Exit());
              w.setVisible(true);
              return w;

  • Various questions (GridBagLayout, Showing Panel, Paste)

    Hi everybody,
    I'm quite new to GUI and swing programming and I'm having some problems. I'm trying to use a GridBagLoyaout, to add Components I use the following method:
    protected void add(Component c, int posx, int posy, int lenx, int leny, int weightx, int weighty){
         GridBagConstraints constraints = new GridBagConstraints();
         constraints.gridx = posx;
         constraints.gridy = posy;
         constraints.gridwidth = lenx;
         constraints.gridheight = leny;
         constraints.weightx = weightx;
         constraints.weighty = weighty;
         constraints.fill = GridBagConstraints.NONE;
         constraints.anchor = GridBagConstraints.WEST;
         add(c, constraints);
    }this method is in an abstract class which extends JPanel and which is extended by all of my panels.
    About that I have to say that there is a panel which contains other panel, in this way:
         JTextField name = new JTextField(40);
         JTextField surname = new JTextField(40);
         JTextArea notes = new JTextArea(4, 50);
         JPanel address = new AddressPane();
         JPanel[] phones = {new PhonePane(), new PhonePane(), new PhonePane(), new PhonePane()};
         JButton add = new JButton("Aggiungi");
         JButton cancel = new JButton("Annulla");
         JButton delete = new JButton("Cancella");
         JButton search = new JButton("Cerca");
         JButton edit = new JButton("Modifica");
         JButton remove = new JButton("Elimina");I add the declared component to the "main panel" using tese methods, which call the previous described add method
    private void addMandatoryButtons(){
         add(delete, 2, 4+phones.length, 1, 1, 0, 0);
         add(cancel, 3, 4+phones.length, 1, 1, 0, 0);
    private void addPanes(){
         add(address, 0, 2, 4, 1, 0, 0);
         address.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Indirizzo"));
         for(int i=0;i<phones.length;i++){
              add(phones, 0, 3+i, 4, 1, 0, 0);
              phones[i].setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Telefono " + String.valueOf(i+1)));
    protected void addTextFields(){
         add(surname, 1, 0, 3, 1, 40, 0);
         add(name, 1, 1, 3, 1, 40, 0);
    private void addTextAreasWithBorders(){
         JPanel notesPanel = new JPanel();
         notesPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Note"));
         notesPanel.add(notes);
         notes.setLineWrap(true);
         add(notesPanel, 0, 3+phones.length, 4, 1, 0, 0);
    In the AddressPane and Phone Frame I add the components, in the same way, using these methods:
    protected void addTextFields(){
         add(street, 1, 0, 3, 1, 30, 0);
         add(number, 5, 0, 1, 1, 5, 0);
         add(zip, 1, 1, 1, 1, 7, 0);
         add(town, 3, 1, 1, 1, 20, 0);
         add(country, 1, 2, 5, 1, 30, 0);
    private void addCombo(){
         Province[] lista = AddressBookManager.current().getAllProvinces();
         province.setEditable(true);
         for(int i=0; i < lista.length; i++)
              province.addItem(lista.getCode());
         add(province, 5, 1, 1, 1, 2, 0);
    protected void addTextFields(){
         add(prefix, 1, 0, 1, 1, 8, 0);
         add(number, 3, 0, 1, 1, 15, 0);
         add(note, 5, 0, 1, 1, 50, 0);
    private void addCheckBox(){
         add(cellulare, 6, 0, 1, 1, 0, 0);
    And the result being is really bad...
    Apart the labels the other components are bad sized, if the window is not enlarged at the maximum the JTextFields are as short as they cannot be seen; being the window enlarged the pane is not shown as rectangle, but it's a kind of polygon made of different rectangles one on another.
    What is my fault? What do I miss?
    Then I have another question: I have a kind of desktop and in order to open a "window" I call this method
    public void openWindow(JPanel panel){
         this.panel = panel;
         getContentPane().add(panel, BorderLayout.CENTER);
         repaint();
    }But why I don't see the newly added panel until I resize the desktop window??
    Last but not least question, I'm trying to implement a paste emthod, but how do I know where I have to paste having more than one JTextComponent? How do I get to know where is the caret?
    I tried with the methods isFocusOwner(), getCaret()!=null and getCaretPosition()>=0.
    I hope to get answerd to all of my questions soon, thanks a lot in advance.
    Best regards.
    Giorgio

    Help me...
    Hi everybody,
    I'm quite new to GUI and swing programming and I'm
    having some problems. I'm trying to use a
    GridBagLoyaout, to add Components I use the following
    method:
    protected void add(Component c, int posx, int posy,
    int lenx, int leny, int weightx, int weighty){
    GridBagConstraints constraints = new
    GridBagConstraints();
         constraints.gridx = posx;
         constraints.gridy = posy;
         constraints.gridwidth = lenx;
         constraints.gridheight = leny;
         constraints.weightx = weightx;
         constraints.weighty = weighty;
         constraints.fill = GridBagConstraints.NONE;
         constraints.anchor = GridBagConstraints.WEST;
         add(c, constraints);
    }this method is in an abstract class which extends
    JPanel and which is extended by all of my panels.
    About that I have to say that there is a panel which
    contains other panel, in this way:
         JTextField name = new JTextField(40);
         JTextField surname = new JTextField(40);
         JTextArea notes = new JTextArea(4, 50);
         JPanel address = new AddressPane();
    JPanel[] phones = {new PhonePane(), new PhonePane(),
    new PhonePane(), new PhonePane()};
         JButton add = new JButton("Aggiungi");
         JButton cancel = new JButton("Annulla");
         JButton delete = new JButton("Cancella");
         JButton search = new JButton("Cerca");
         JButton edit = new JButton("Modifica");
         JButton remove = new JButton("Elimina");I add the declared component to the "main panel" using
    tese methods, which call the previous described add
    method
    private void addMandatoryButtons(){
         add(delete, 2, 4+phones.length, 1, 1, 0, 0);
         add(cancel, 3, 4+phones.length, 1, 1, 0, 0);
    private void addPanes(){
         add(address, 0, 2, 4, 1, 0, 0);
         address.setBorder(BorderFactory.createTitledBorder(Bor
    erFactory.createEtchedBorder(), "Indirizzo"));
         for(int i=0;i<phones.length;i++){
              add(phones, 0, 3+i, 4, 1, 0, 0);
              phones[i].setBorder(BorderFactory.createTitledBorder(
    orderFactory.createEtchedBorder(), "Telefono " +
    String.valueOf(i+1)));
    protected void addTextFields(){
         add(surname, 1, 0, 3, 1, 40, 0);
         add(name, 1, 1, 3, 1, 40, 0);
    private void addTextAreasWithBorders(){
         JPanel notesPanel = new JPanel();
         notesPanel.setBorder(BorderFactory.createTitledBorder(
    orderFactory.createEtchedBorder(), "Note"));
         notesPanel.add(notes);
         notes.setLineWrap(true);
         add(notesPanel, 0, 3+phones.length, 4, 1, 0, 0);
    In the AddressPane and Phone Frame I add the
    components, in the same way, using these methods:
    protected void addTextFields(){
         add(street, 1, 0, 3, 1, 30, 0);
         add(number, 5, 0, 1, 1, 5, 0);
         add(zip, 1, 1, 1, 1, 7, 0);
         add(town, 3, 1, 1, 1, 20, 0);
         add(country, 1, 2, 5, 1, 30, 0);
    private void addCombo(){
    Province[] lista =
    AddressBookManager.current().getAllProvinces();
         province.setEditable(true);
         for(int i=0; i < lista.length; i++)
              province.addItem(lista.getCode());
         add(province, 5, 1, 1, 1, 2, 0);
    protected void addTextFields(){
         add(prefix, 1, 0, 1, 1, 8, 0);
         add(number, 3, 0, 1, 1, 15, 0);
         add(note, 5, 0, 1, 1, 50, 0);
    private void addCheckBox(){
         add(cellulare, 6, 0, 1, 1, 0, 0);
    And the result being is really bad...
    Apart the labels the other components are bad sized,
    if the window is not enlarged at the maximum the
    JTextFields are as short as they cannot be seen; being
    the window enlarged the pane is not shown as
    rectangle, but it's a kind of polygon made of
    different rectangles one on another.
    What is my fault? What do I miss?
    Then I have another question: I have a kind of desktop
    and in order to open a "window" I call this method
    public void openWindow(JPanel panel){
         this.panel = panel;
         getContentPane().add(panel, BorderLayout.CENTER);
         repaint();
    }But why I don't see the newly added panel until I
    resize the desktop window??
    Last but not least question, I'm trying to implement a
    paste emthod, but how do I know where I have to paste
    having more than one JTextComponent? How do I get to
    know where is the caret?
    I tried with the methods isFocusOwner(),
    getCaret()!=null and getCaretPosition()>=0.
    I hope to get answerd to all of my questions soon,
    thanks a lot in advance.
    Best regards.
    Giorgio

  • Please, help a newbie:  Question about animating expanding containers

    Hi All,
    Short Version of my Question:
    I'm making a media player that needs to have an animation for panels sliding up and down and left and right, and the method I've been using to do this performs far slower than the speed I believe is possible, and required. What is a fast way to make a high performance animation for such an application?
    Details:
    So far, to do the animation, I've been using JSplitPanes and changing the position of the divider in a loop and calling paintImmediately or paintDirtyRegion like so:
    public void animateDividerLocation( JSplitPane j, int to, int direction) {
    for(int i=j.getDividerLocation(); i>=to; i-=JUMP_SIZE) {
    j.setDividerLocation(i);
    j.validate();
    j.paintImmediately(0, 0, j.getWidth(), j.getHeight());
    The validate and paintImmediately calls have been necessary to see any changes while the loop is going. I.e., if those calls are left out, the components appear to just skip right to where they were supposed to animate to, without having been animated at all.
    The animation requirement is pretty simple. Basically, the application looks like it has 3 panels. One on the right, one on the left, and a toolbar at the bottom. The animation just needs to make the panels expand and contract.
    Currenly, the animation only gets about, say, 4 frames a second on the 800 MHz Transmeta Crusoe processor, 114 MB Ram, Windows 2000 machine I must use (to approximate the performance of the processor I'll be using, which will run embedded Linux), even though I've taken most of the visible components out of the JPanels during the animation. I don't think this has to do with RAM reaching capacity, as the harddrive light does not light up often. Even if this were the case, the animation goes also goes slow (about 13 frames a second) on my 3 GHz P4 Windows XP if I keeps some JButtons, images etc., inside the JPanels. I get about 50 frames/sec on my 3 GHz P4, if I take most of the JButtons out, as I do for the 800 MHz processor. This is sufficient to animate the panels 400 pixels across the screen at 20 pixels per jump, but it isn't fast or smooth enough to animate across 400 pixels moving at 4 pixel jumps. I know 50 frames/sec is generally considered fast, but in this case, there is hardly anything changing on the screen (hardly any dirty pixels per new frame) and so I'd expect there to be some way to make the animation go much faster and smoother, since I've seen games and other application do much more much faster and much smoother.
    I'm hoping someone can suggest a different, faster way to do the animation I require. Perhaps using the JSplitPane trick is not a good idea in terms of performance. Perhaps there are some tricks I can apply to my JSplitPane trick?
    I haven't been using any fancy tricks - no double buffering, volatile images, canvas or other animation speed techniques. I haven't ever used any of those things as I'm fairly new to Swing and the 2D API. Actually I've read somewhere that Swing does double buffering without being told to, if I understood what I read. Is doing double buffering explicitly still required? And, if I do need to use double buffering or canvas or volatile images or anything else, I'm not sure how I would apply those techiniques to my problem, since I'm not animating a static image around the screen, but rather a set of containers (JSplitPanes and JPanels, mostly) and components (mostly JButtons) that often get re-adjusted or expanded as they are being animated. Do I need to get the Graphics object of the top container (would that contain the graphics objects for all the contained components?) and then double buffer, volatile image it, do the animation on a canvas, or something like that? Or what?
    Thanks you SO much for any help!
    Cortar
    Related Issues(?) (Secondary concerns):
    Although there are only three main panels, the actual number of GUI components I'm using, during the time of animation, is about 20 JPanels/JSplitPanes and 10 JButtons. Among the JPanels and the JSplitPanes, only a few JPanels are set to visible. I, for one, don't think this higher number of components is what is slowing me down, as I've tried taking out some components on my 3GHz machine and it didn't seem to affect performance much, if any. Am I wrong? Will minimizing components be among the necessary steps towards better performance?
    Anyhow, the total number of JContainers that the application creates (mostly JPanels) is perhaps less than 100, and the total number of JComponents created (mostly JButtons and ImageIcons) is less than 200. The application somehow manages to use up 50 MBs RAM. Why? Without looking at the code, can anyone offer a FAQ type of answer to this?

    You can comment out the lines that add buttons to the panels to see the behavior with empty panels.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.Timer;
    public class DancingPanels
        static GridBagLayout gridbag = new GridBagLayout();
        static Timer timer;
        static int delay = 40;
        static int weightInc = 50;
        static boolean goLeft = false;
        public static void main(String[] args)
            final GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.weighty = 1.0;
            gbc.fill = gbc.HORIZONTAL;
            final JPanel leftPanel = new JPanel(gridbag);
            leftPanel.setBackground(Color.blue);
            gbc.insets = new Insets(0,30,0,30);
            leftPanel.add(new JButton("1"), gbc);
            leftPanel.add(new JButton("2"), gbc);
            final JPanel rightPanel = new JPanel(gridbag);
            rightPanel.setBackground(Color.yellow);
            gbc.insets = new Insets(30,50,30,50);
            gbc.gridwidth = gbc.REMAINDER;
            rightPanel.add(new JButton("3"), gbc);
            rightPanel.add(new JButton("4"), gbc);
            final JPanel panel = new JPanel(gridbag);
            gbc.fill = gbc.BOTH;
            gbc.insets = new Insets(0,0,0,0);
            gbc.gridwidth = gbc.RELATIVE;
            panel.add(leftPanel, gbc);
            gbc.gridwidth = gbc.REMAINDER;
            panel.add(rightPanel, gbc);
            timer = new Timer(delay, new ActionListener()
                    gbc.fill = gbc.BOTH;
                    gbc.gridwidth = 1;
                public void actionPerformed(ActionEvent e)
                    double[] w = cycleWeights();
                    gbc.weightx = w[0];
                    gridbag.setConstraints(leftPanel, gbc);
                    gbc.weightx = w[1];
                    gridbag.setConstraints(rightPanel, gbc);
                    panel.revalidate();
                    panel.repaint();
            JFrame f = new JFrame("Dancing Panels");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(panel);
            f.setSize(400,300);
            f.setLocation(200,200);
            f.setVisible(true);
            timer.start();
        private static double[] cycleWeights()
            if(goLeft)
                weightInc--;
            else
                weightInc++;
            if(weightInc > 100)
                weightInc = 100;
                goLeft = true;
            if(weightInc < 0)
                weightInc = 0;
                goLeft = false;
            double wLeft = weightInc/ 100.0;
            double wRight = (100 - weightInc)/100.0;
            return new double[]{wLeft, wRight};
    }

  • Here is my GridBagLayout version of the code

         public void constructGUI()
               c= getContentPane();
              //Construct the menus and their listeners
              JMenu filemenu = new JMenu("File");
              JMenuItem saveas= new JMenuItem ("Save Amortization As");
              saveas.addActionListener(new ActionListener(){
                   public void actionPerformed (ActionEvent e)
                        JFileChooser filechooser = new JFileChooser ();
                        filechooser.setFileSelectionMode ( JFileChooser.FILES_ONLY);
                        int result = filechooser.showSaveDialog (null);
                        if (result== JFileChooser.CANCEL_OPTION)
                             return;
                        File filename = filechooser.getSelectedFile();
                        if (filename==null||filename.getName().equals (" "))
                             JOptionPane.showMessageDialog( null, "Invalid File Name", "Invalid FileName", JOptionPane.ERROR_MESSAGE );
                        else {
                             try
                                  System.out.println("I am ready to create the streams");
                                  FileOutputStream file = new FileOutputStream(filename, true);
                                  OutputStreamWriter filestream = new OutputStreamWriter(new BufferedOutputStream(file));
                                  String info= "The data is based on"+"\n";
                                  filestream.write(info);
                                  System.out.println("I wrote the first string called info");
                                  String interestdata= "INTEREST:"+" "+interest+"\n";
                                  filestream.write(interestdata);
                                  String timedata="The amortization period is:"+" "+time+"\n";
                                  filestream.write(timedata);
                                  String loandata="The money borrowed is:"+" "+moneyFormat.format(loannumber)+"\n";
                                  filestream.write(loandata);
                                  String totals= "Total of Payments Made:"+" " +moneyFormat.format(totalpayments)+"\n"+"Total Interest Paid:"+"  "+moneyFormat.format(totalinterest)+"\n";
                                  filestream.write(totals);
                                  String filestring = "PAYMENT NUMBER"+"   " + "PAYMENT" + "   " + " PRINCIPLE" + "   " + "INTEREST" +"   " + " BALANCE" + "\n";
                                  filestream.write(filestring);
                                  double loannumberkf= loannumber;
                                  System.out.println(timenumber);
                                  for (int j=1; j<=timenumber ; j++ )
                                       double principlekf=payment-loannumberkf*z;
                                       double balancef=loannumberkf-principlekf;
                                       String display ="\n"+ Integer.toString(j)+"                " + moneyFormat.format(payment)+"        "+ moneyFormat.format(principlekf)+ "     "+moneyFormat.format(loannumberkf*z)+ "     "+ moneyFormat.format(balancef)+"\n";
                                       filestream.write(display);
                                       loannumberkf=loannumberkf-principlekf;
                                  filestream.flush();
                                  file.close();
                             catch ( IOException ioException )
                                  JOptionPane.showMessageDialog (null, "File Does not exist", "Invalid File Name", JOptionPane.ERROR_MESSAGE);
                        }//end of else
                 } //end anonymous inner class
              filemenu.add(saveas);
              JMenuItem exit= new JMenuItem ("Exit");
              exit.addActionListener( new ActionListener() {
                        public void actionPerformed (ActionEvent e)
                             System.exit(0);
                   } //end anonymous inner class
              ); // end call to ActionListener
              filemenu.add(exit);
              JMenuItem summaries=new JMenuItem ("Save Summaries As");
              MenuHandler menuhandler= new MenuHandler();
              summaries.addActionListener(menuhandler);
              filemenu.add(summaries);
              //construct the second JMenu
              JMenu colorchooser=new JMenu("Color Chooser");
              JMenuItem colorchooseritem=new JMenuItem("Choose Color");
              colorchooseritem.addActionListener (new ActionListener() {
                                  public void actionPerformed(ActionEvent e)
                                       color=JColorChooser.showDialog(Mortgagecalculation.this, "Choose a Color", color);
                                       c.setBackground(color);
                                       c.repaint();
                         ); //end of registration
              colorchooser.add(colorchooseritem);
              //third menu
              JMenu service = new JMenu("Services");
              JMenuItem s1= new JMenuItem ("Display Amortization");
              JMenuItem s2= new JMenuItem ("Calender");
              service.add(s1);
              service.add(s2);
              //Create menu bar and add the two JMenu objects
              JMenuBar menubar = new JMenuBar();
              setJMenuBar(menubar);
              menubar.add(filemenu); // end of menu construction
              menubar.add(colorchooser);
              menubar.add(service);
              //set the layout manager for the JFrame
              gbLayout = new GridBagLayout();
              c.setLayout(gbLayout);
              gbConstraints = new GridBagConstraints();
              //construct table and place it on the North part of the Frame
              JLabel tablelabel=new JLabel ("The Table below displays amortization values after you press O.K. on the payments window. Payments window appears after you enter the values for rate, period and loan");
              mydefaulttable = new DefaultTableModel();
                   mydefaulttable.addColumn("PAYMENT NUMBER");
                   mydefaulttable.addColumn ("PAYMENT AMOUNT");
                   mydefaulttable.addColumn ("PRINCIPLE");
                   mydefaulttable.addColumn ("INTEREST");
                   mydefaulttable.addColumn("LOAN BALANCE");
              Box tablebox=Box.createVerticalBox();   
              mytable=new JTable(mydefaulttable);
              tablelabel.setLabelFor(mytable);
              JScrollPane myscrollpane= new JScrollPane (mytable);
              tablebox.add(tablelabel);
              tablebox.add(myscrollpane);
              //gbConstraints.weightx = 100;
              //gbConstraints.weighty = 50;
              //gbConstraints.fill = GridBagConstraints.BOTH;
              gbConstraints.anchor = GridBagConstraints.NORTH;
              addComponent(tablebox,0,0,3,1,GridBagConstraints.NORTH);
            //c.add (tablebox, BorderLayout.NORTH);
              //create center panel
              JLabel panellabel=new JLabel("Summarries");
              MyPanel panel =new MyPanel();
              panel.setSize (10, 50);
              panel.setBackground(Color.red);
              panellabel.setLabelFor(panel);
              Box panelbox=Box.createVerticalBox();
              panelbox.add(panellabel);
              panelbox.add(panel);
              //gbConstraints.weightx = 50;
              //gbConstraints.weighty = 100;
            //gbConstraints.fill = GridBagConstraints.BOTH;
              gbConstraints.anchor = GridBagConstraints.CENTER;
              addComponent(panelbox,1,1,1,1,GridBagConstraints.CENTER);
              //c.add (panelbox, BorderLayout.CENTER);
              //add time in the SOUTH part of the Frame
              Panel southpanel=new Panel();
              southpanel.setBackground(Color.magenta);
              Date time=new Date();
              String timestring=DateFormat.getDateTimeInstance().format(time);
              TextField timefield=new TextField("The Date and Time in Chicago is:"+" "+timestring, 50);
              southpanel.add(timefield);
              //gbConstraints.weightx = 100;
              //gbConstraints.weighty = 1;
              //gbConstraints.fill = GridBagConstraints.HORIZONTAL;
              gbConstraints.anchor = GridBagConstraints.SOUTH;
              addComponent(southpanel,0,2,3,1,GridBagConstraints.SOUTH);
              //c.add(southpanel, BorderLayout.SOUTH);
              //USE "BOX LAYOUT MANAGER" TO ARRANGE COMPONENTS LEFT TO RIGHT WITHIN THE SOUTH PART OF THE FRAME
              //Create a text area to output more information about the application.Place it in a box and place box EAST
              Font f=new Font("Serif", Font.ITALIC+Font.BOLD, 16);
              string="-If you would like to exit this program\n"+
              "-click on the exit menu item \n"+
                   "-if you would like to save the table as a text file \n"+
                   "-click on Save As menu item \n"+"-You can reenter new values for calculation\n"+
                   " as many times as you would like.\n"+
                   "-You can save the summaries also on a different file\n"+
                   "-Files are appended";
              JLabel infolabel= new JLabel ("Information About this Application", JLabel.RIGHT);
              JTextArea textarea=new JTextArea(25,25);
              textarea.setFont(f);
              textarea.append(string);
              infolabel.setLabelFor(textarea);
              Box box =Box.createVerticalBox();
              box.add(infolabel);
              box.add(new JScrollPane (textarea));
              //gbConstraints.weightx = 50;
              //gbConstraints.weighty = 100;
              //gbConstraints.fill = GridBagConstraints.BOTH;
              gbConstraints.anchor = GridBagConstraints.SOUTHEAST;
              addComponent(box,2,1,1,1,GridBagConstraints.SOUTHEAST);
              //c.add(box, BorderLayout.EAST);
              //Create the text fields for entering data and place them in a box WEST
              Panel panelwest = new Panel();
              //create the first panelwest and place the text fields in it
              Box box1=Box.createVerticalBox();
              JLabel rate= new JLabel ("Enter Rate", JLabel.RIGHT);
              interestfield=new JTextField ("Enter Interest here and press Enter", 15);
              rate.setLabelFor(interestfield);
              box1.add(rate);
              box1.add(interestfield);
              JLabel period=new JLabel("Enter Amortization Periods", JLabel.RIGHT);
              timenumberfield=new JTextField("Enter amortization period in months and press Enter", 15);
              period.setLabelFor(timenumberfield);
              box1.add(period);
              box1.add(timenumberfield);
              JLabel loan=new JLabel("Enter Present Value of Loan", JLabel.RIGHT);
              loanamountfield =new JTextField ("Enter amount of loan and press Enter", 15);
              loan.setLabelFor(loanamountfield);
              box1.add(loan);
              box1.add(loanamountfield);
              JLabel submit = new JLabel("Press Submit Button to Calculate", JLabel.RIGHT);
              submitbutton= new JButton("SUBMIT");
              submit.setLabelFor(submitbutton);
              box1.add(submit);
              box1.add(submitbutton);
              panelwest.add(box1);
              //Add the panel to the content pane
              //gbConstraints.weightx = 50;
              //gbConstraints.weighty = 100;
              //gbConstraints.fill = GridBagConstraints.BOTH;
              gbConstraints.anchor = GridBagConstraints.SOUTHWEST;
              addComponent(panelwest,0,1,1,1,GridBagConstraints.SOUTHWEST);
              //c.add(panelwest, BorderLayout.WEST);
              //Event handler registration for text fields and submit button
              TextFieldHandler handler=new TextFieldHandler();
              interestfield.addActionListener(handler);
              timenumberfield.addActionListener(handler);
              loanamountfield.addActionListener(handler);
              submitbutton.addActionListener(handler);
              setSize(1000, 700);   
              setVisible(true);
              System.out.println("repainting table, constructor");
              System.out.println("I finished repainting. End of ConstructGUI");
         } // END OF CONSTUCTGUI
         // addComponent() is developed here
         private void addComponent(Component com,int row,int column,int width,int height,int ancor)
              //set gridx and gridy
              gbConstraints.gridx = column;
              gbConstraints.gridy = row;
              //set gridwidth and gridheight
              gbConstraints.gridwidth = width;
              gbConstraints.gridheight = height;
              gbConstraints.anchor = ancor;
              //set constraints
              gbLayout.setConstraints(com,gbConstraints);
              c.add(com);          
         

    Quit cross-posting (in different forums) every time you have a question.
    Quit multi-posting (asking the same questions twice) when you ask a question.
    Start responding to your old questions indicating whether the answers you have been given have been helpfull or not.
    Read the tutorial before asking a question. Start with [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use GridBag Layout. Of course its the most difficult Layout Manager to master so I would recommend you use various combinations of the other layout managers to achieve your desired results.
    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 (SSCCE) 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.

  • Max. no. of rows in GridbagLayout

    Is there any limit for number of rows (y) in GridbagLayout?
    Recently I mistyped the 'Y' parameters as 888 during creating a GUI. The code compiled smoothly but it gave ArrayIndexOutOfBoundsException: 888 at run time.
    Anybody has some idea about it.
    vinod

    A word of advice; don't post the same question in a number of forums. You have posted it here in three different forums. The folks who will be the most help to you read most of the forums and the extra posting causes a waste of time and bandwidth.<BR><BR>My personal take on your problem is that if you are getting more than 65k rows, Excel is the wrong tool. You are looking at data, not information. The human mind doesn't really work that way, and while you might be getting the number out and be replacing an oldgreenbar report, I'd suggest that you look at what you really want to find out.<BR><BR>When drilling, you are normally looking for exceptions -- best performance and/or worst performance -- and the people who need the information need to know what they are looking for. Doing a report that returns 65K rows is not going to make it easier to manage a business. Think about using ranking, top 5% returns, and possibly some flags in the database to narrow the focus. Also, attribute dimesnions or focussing the drill can help.<BR><BR>I've done various types of decision support, analysis, and Executive Information Systems for over 20 years and I've seen what can be really useful. If a customer asks for a massive report, I try to determine how the information will be used and while it may be easy to give the customer what is requested, I normally also probvide my best estimation of a tool that provides the same information in a much more digestible way, using graphics, exception reporting, and better data orgainzation.<BR><BR>A 65k row drill doesn't really help anyone. There are better ways to get the same type of information.

  • Problem with the GridBagLayout Manager

    Hello i am new to Java Swing and i am facing a problem with the GridBagLayout layout manager . the code in question is attached. First compile and run the code. It will execute w/o probs . Then go to the "Console" tab. There the diff components (6 buttons and 1 text area) are haphazardly arranged where as all measures where taken to prevent it in the code. The GridBagLayout manager for this tab is not working properly please help.
    The code in question:-
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class MainForm extends JFrame{
         JTabbedPane jtp = new JTabbedPane();
         Container generalContainer; // container for the general pane
         Container consoleContainer; // container for the console pane
         GridBagLayout consoleLayout = new GridBagLayout(); // GridBagLayout for the console
         GridBagConstraints consoleConstraints;// GridBagConstraints for the console
         public MainForm()
              super("Welcome to Grey Griffin -- Network Simulator");
              setSize(700,600);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              JPanel generalPane = new JPanel();
              generalPane.setLayout(new BoxLayout(generalPane, BoxLayout.Y_AXIS));
              JPanel consolePane = new JPanel();
              consolePane.setLayout(new BoxLayout(consolePane, BoxLayout.Y_AXIS));
              JPanel designPane = new JPanel();
              designPane.setLayout(new BoxLayout(designPane, BoxLayout.Y_AXIS));
              JPanel outputPane = new JPanel();
              outputPane.setLayout(new BoxLayout(outputPane, BoxLayout.Y_AXIS));
              //Setting up Layout for all the tabs
               //for general tab
               FlowLayout layout= new FlowLayout();
               generalContainer = generalPane;
               layout.setAlignment(FlowLayout.CENTER);
               generalContainer.setLayout( layout );
               //for  console tab
               consoleContainer = consolePane;
               consoleConstraints = new GridBagConstraints();
               // *******Finished********
              //********** All buttons text areas are declared here**********
                //*******for the general tab**********
              JButton generalCreate = new JButton("Create a New Network");
              JButton generalOpen = new JButton("Open an Existing Network");
              JButton generalSave = new JButton("Save the Network");
              JButton generalSaveAs = new JButton("Save As..........");
              JButton generalExit = new JButton("Exit");
              //******END******
             //*******for the console tab
                 //text area          
              JTextArea consoleCode = new JTextArea();
              consoleCode.setEditable(true);
              consoleCode.setMaximumSize(new Dimension(700,400));
              consoleCode.setAlignmentX(0.0f);
                   //text area complete
                 //*******for the Console tab**********
              JButton consoleCompile = new JButton("Compile Code");
              JButton consoleSimulate = new JButton("Simulate Code");
              JButton consoleReset = new JButton("Reset");
              JButton consoleOpen = new JButton("Open script files");
              JButton consoleSave = new JButton("Save script files");
              JButton consoleConvert = new JButton("Convert Script files to graphical form");
              //***************END****************
         //Adding buttons and text areas to there respective tabs
              // for the general tab
              generalContainer.add(generalCreate);
              generalContainer.add(generalOpen);
              generalContainer.add(generalSave);
              generalContainer.add(generalSaveAs);
             generalContainer.add(generalExit);
             //****END****
              // for the console tab          
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleOpen,0,0,1,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleSave,1,1,1,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleConvert,1,2,1,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleCode,1,0,3,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleCompile,2,0,1,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleSimulate,2,1,1,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleReset,2,2,1,1);
              //****END****
              // adding the tabs
              jtp.addTab("General",null,generalPane,"Choose General Options");
              jtp.addTab("Design",null,designPane,"Design your own network!!");
              jtp.addTab("Console",null,consolePane,"Type commands in console for designing");
              jtp.addTab("Output",null,outputPane,"View output");
              getContentPane().add(jtp, BorderLayout.CENTER);
              //****END****
         //This method is used to ad the buttons in the GridBagLayout of the Console tab
         private void addComp( Component c,int row,int column,int width,int height)
            // set gridx and gridy
            consoleConstraints.gridx=column;
            consoleConstraints.gridy=row;
            //set gridwidth and grid height
            consoleConstraints.gridwidth=width;
            consoleConstraints.gridheight=height;
            //set constraints
            consoleLayout.setConstraints(c,consoleConstraints);
            consoleContainer.add(c);     
         class TabManager implements ItemListener
              Component tab;
              public TabManager(Component tabToManage)
                   tab = tabToManage;
         public void itemStateChanged(ItemEvent ie)
              int index=jtp.indexOfComponent(tab);
             if (index!=-1)
                  jtp.setEnabledAt(index,ie.getStateChange()== ItemEvent.SELECTED);
             MainForm.this.repaint();
    public static void main(String args[])
         MainForm form = new MainForm();
         form.setVisible(true);
    }

    Thanks for the suggestions. I did away with the GridBagLayout Altogether :-D
    and put all the buttons in a seperate JPanel and added that JPanel into the Console tabs container which was using a BorderLayout this time. Take a look
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class MainForm extends JFrame{
         JTabbedPane jtp = new JTabbedPane();
         public MainForm()
              super("Welcome to Grey Griffin -- Network Simulator");
              setSize(800,600);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              JPanel generalPane = new JPanel();
              generalPane.setLayout(new BoxLayout(generalPane, BoxLayout.Y_AXIS));
              JPanel consolePane = new JPanel();
              consolePane.setLayout(new BoxLayout(consolePane, BoxLayout.Y_AXIS));
              JPanel designPane = new JPanel();
              designPane.setLayout(new BoxLayout(designPane, BoxLayout.Y_AXIS));
              JPanel outputPane = new JPanel();
              outputPane.setLayout(new BoxLayout(outputPane, BoxLayout.Y_AXIS));
              //Setting up Layout for all the tabs
              //**for the general tab
               Container generalContainer;
               FlowLayout layoutGeneral= new FlowLayout();
               generalContainer = generalPane;
               layoutGeneral.setAlignment(FlowLayout.CENTER);
               generalContainer.setLayout( layoutGeneral );
               //**for the console tab
                Container consoleContainer;
                consoleContainer = consolePane;
                consoleContainer.setLayout(new BorderLayout() );
               //Creating buttonpanel for adding the buttons
                JPanel buttonPanel1 = new JPanel();
                buttonPanel1.setLayout(new GridLayout(1,3));
                JPanel buttonPanel2 = new JPanel();
                buttonPanel2.setLayout(new GridLayout(1,3));
              // All buttons / text areas / images are declared here
              //**Buttons for the general tab**//
              JButton generalCreate = new JButton("Create a New Network");
              JButton generalOpen = new JButton("Open an Existing Network");
              JButton generalSave = new JButton("Save the Network");
              JButton generalSaveAs = new JButton("Save As..........");
              JButton generalExit = new JButton("Exit");
              //declaring the buttons
              JButton consoleCompile = new JButton("Compile");
              JButton consoleRun = new JButton("Run");
              JButton consoleReset = new JButton("Reset");
              JButton consoleOpen = new JButton("Open script files");
              JButton consoleSave = new JButton("Save script files");
              JButton consoleConvert = new JButton("Convert Script files to graphical form");
              //declares the textarea where the code is written
              JTextArea consoleCode = new JTextArea();
              consoleCode.setEditable(true);
              consoleCode.setMaximumSize(new Dimension(500,600));
              consoleCode.setAlignmentX(0.0f);
              //Adding buttons and text areas to there respective tabs     
              //**Buttons and text pads for the general tab**
                   generalContainer.add(generalCreate);
              generalContainer.add(generalOpen);
              generalContainer.add(generalSave);
              generalContainer.add(generalSaveAs);
                 generalContainer.add(generalExit);
              //adding buttons to the button panel 1
              buttonPanel1.add(consoleOpen);
              buttonPanel1.add(consoleSave);
              buttonPanel1.add(consoleConvert);
              //adding buttons to the button panel2          
              buttonPanel2.add(consoleRun);
              buttonPanel2.add(consoleReset);
              buttonPanel2.add(consoleCompile);
              //adding button panels and textarea
              consoleContainer.add(buttonPanel1,BorderLayout.NORTH);
              consoleContainer.add(consoleCode,BorderLayout.CENTER);
              consoleContainer.add(new JScrollPane(consoleCode));
              consoleContainer.add(buttonPanel2,BorderLayout.SOUTH);
              //adding the tabs          
              jtp.addTab("General",null,generalPane,"Choose General Options");
              jtp.addTab("Design",null,designPane,"Design your own network!!");
              jtp.addTab("Console",null,consolePane,"Type commands in console for designing");
              jtp.addTab("Output",null,outputPane,"View output");
              getContentPane().add(jtp, BorderLayout.CENTER);
         class TabManager implements ItemListener
              Component tab;
              public TabManager(Component tabToManage)
                   tab = tabToManage;
         public void itemStateChanged(ItemEvent ie)
              int index=jtp.indexOfComponent(tab);
             if (index!=-1)
                  jtp.setEnabledAt(index,ie.getStateChange()== ItemEvent.SELECTED);
             MainForm.this.repaint();
    public static void main(String args[])
         MainForm form = new MainForm();
         form.setVisible(true);
    }

  • Using GridBagLayout to fill the full width of a JFrame, ...

    I have two quick questions regarding GridBagLayout.
    1st, I would like the fill the full width of a JFrame with a JPanel. I have tried:
    JFrame frame = new JFrame();
    //Set width and height of frame
    JPanel panel = createFilledPanel();
    panelConstraints.gridx = 0;
    panelConstraints.gridy = 0;
    panelConstraints.fill = GridBagConstraints.HORIZONTAL;But this fails to stretch the panel to the full width of the frame.
    2nd, I would like to align the elements in a panel to the farthest left they can go. I have tried:
    element.anchor = GridBagConstraints.LINE_START;But this aligns all the elements I do this to, to the same starting position horizontally, but not all the way left.
    I would appreciate help with either or both of these questions!

    weightx or weighty : Easy way to understand is priority amongs components and if this componets get setting
    with weightx = 1.0 then this components 's width and height values are respected to be kept over others.
    It just says that, putting the weight on this components over others. kept all others attributes of this componets first
    over other components.
    I hope my jebrish explanation help -

  • Maximum size of a JComboBox in a GridBagLayout

    I'm having a problem with a JComboBox inside a GridBagLayout. The general layout is a GridBag with labels / combo / textfields on the first line, a large table in a scrollpane that takes all columns on the second line, and a few labels / combo / textfields on the third.
    As long as the combo on the first combo is empty, it looks fine. When it gets populated, the combo gets resized to the size of the largest text. I would like to have it smaller and truncate the text.
    I tried to set maximum size, but the GridBag doesnt care. I've been trying with weightx but no success.
    What should I do ?

    And I would be interested which LayoutManager you prefer using.I don't use a single Layout Manager. I use a combination of Layout Managers to do the job. Thats why this question doesn't have a specific example. Remember LayoutManagers can be nested. The default layout manager for a frame is a border layout. That great for the general look of your application.
    a) you add a toolbar to the north
    b) you add a status bar to the south
    c) you add your main panel to the center.
    the main panel in turrn may use nested panels depending on your requirements. I don't do a lot of screen design but I typically use BorderLayout, FlowLayout, GridLayout and BoxLayout. GridBagLayout and SpringLayout have too many constraints to learn and master. They may be good for a GUI tool that only uses a single layout manager for the entire GUI, but I believe a better design is to break down the form into smaller more manageable areas and group components and use the appropriate layout manager for the group. That may or may not be a GridBagLayout for the small group, but I don't think you should force the entire form to use a GridbagLayout.

  • Question about using scrollRectToVisible?

    hello all:
    From the java doc, it says that
    "void scrollRectToVisible(Rectangle)
    (in JComponent) If the component is in a container that supports scrolling, such as a scroll pane, then calling this method scrolls the scroll pane such that the specified rectangle is visible. "
    I have a small program with the following code:
    jScrollPane1.getViewport().add(bar); // bar is a subclass of JComponent
    // bar.scrollRectToVisible(new Rectangle(0, 0, 430, 50));
    bar.setPreferredSize(new Dimension(430, 50));
    When the size of bar changed, I only need to reset the PreferredSize of bar, then
    the ScrollPane will resize correctly.
    My question is: where should i use scrollRectToVisible?
    thank you
    -Daniel

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ScrollingToView {
      public static void main(String[] args) {
        final JPanel panel = new JPanel(new GridBagLayout());
        final GridBagConstraints gbc = new GridBagConstraints();
        gbc.weighty = 1.0;
        gbc.insets = new Insets(10,0,10,0);
        gbc.gridwidth = gbc.REMAINDER;
        JButton addButton = new JButton("add button");
        ActionListener l = new ActionListener() {
          int buttonCount = 0;
          public void actionPerformed(ActionEvent e) {
            JButton button = new JButton("Button " + ++buttonCount);
            panel.add(button, gbc);
            panel.revalidate();
        addButton.addActionListener(l);
        panel.addComponentListener(new ComponentAdapter() {
          public void componentResized(ComponentEvent e) {
            Component[] components = panel.getComponents();
            if(components.length > 0) {
              Component component = components[components.length-1];
              Rectangle r = component.getBounds();
              r.y += gbc.insets.bottom;
              //System.out.println("r = " + r);
              panel.scrollRectToVisible(r);
        JPanel northPanel = new JPanel();
        northPanel.add(addButton);
        JFrame f= new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(northPanel, "North");
        f.getContentPane().add(new JScrollPane(panel));
        f.setSize(400,300);
        f.setLocation(400,300);
        f.setVisible(true);
    }

  • Exact column (row) size with GridBagLayout??

    Hello there,
    I have a question regarding GridBagLayout and EXACT (relative) dimensions
    of columns and rows. Have you ever had (and solved) this problem? Thank you
    for help!!
    My situations: let's say I'd like to have two buttons, the first should fill
    up 1/4 of the horizontal space and the second should fill up the remaining
    3/4 of the space. But I'd like them to fill up the space EXACTLY (if there
    is enough space of course, I'm not speaking about horizontal space 10
    pixels...). I tried to achieve this by the following code:
    GridBagLayout grid = new GridBagLayout();
    getContentPane().setLayout(grid);
    GridBagConstraints c = new GridBagConstraints();
    // button1
    JButton b1 = new JButton("A");
    c.gridx = 0; c.gridy = 0;
    c.gridwidth = 1; c.gridheight = 1;
    c.weightx = 1.0; c.weighty = 1.0; // <--- weigthx is 1.0 the other
    button will have 3.0
    c.fill = GridBagConstraints.BOTH;
    c.ipadx = 0; c.ipady = 0;
    c.insets = new Insets(0,0,0,0);
    grid.setConstraints(b1, c);
    getContentPane().add(b1);
    // button2
    JButton b2 = new JButton("B");
    c.gridx = 1; c.gridy = 0;
    c.gridwidth = 1; c.gridheight = 1;
    c.weightx = 3.0; c.weighty = 1.0; // <--- weigthx is 3.0 the first has
    1.0
    c.fill = GridBagConstraints.BOTH;
    c.ipadx = 0; c.ipady = 0;
    c.insets = new Insets(0,0,0,0);
    grid.setConstraints(b2, c);
    getContentPane().add(b2);
    This really lays out the buttons in fashiion 1:3 but not exactly, there
    always about 10-15 pixels that are extra...
    I tried to have the weigthx in range <0, 1> so, the button b1 has weigthx =
    0.25 and the second one has weigth = 0.75. But it does not work either...
    Can you help me please?
    David
    ps. Why do I need this exact layout? Because I have 3 tabs (JTabbedPane) and
    all of them display components with this 1:3 layout. But when I click on
    different tabs I can see that the boundary betweeen the two components
    "jumps" slightly from tab to tab which drives me crazy because things like
    this should not be part of program that wants to look "professionally-done".

    Ok, but I don't know the dimensions... I wanted the Layout manager to do the job. I was wondering, maybe I didn't set something else. But thank you!!
    ps. how come that the layout manager displays the layout almost perfectly? the ratio is almost 1:3 but not exactly.

  • Can we use GridBagLayout in JInternal Frame

    i've a question that can we use gridbaglayout in JInternalFrame?

    Yes:
    internalFrame.getContentPane().setLayout(new GridBagLayout());
    // Add children to be laid out to internalFrame,getContentPane()
    //or if you prefer:
    JPanel p = new JPanel(new GridBagLayout());
    internaleFrame.getContentPane().add(p);
    // Add children to be laid out to 'p'
    //

Maybe you are looking for