Using GridBagLayout with JTExtField

Hello Everybody,
I use the GridBagLayout to lay out panels, and one of them also uses a GridBag. In this panel there are some textfields. When you type into one of them, that causes the panel's size to change and therefore, it changes sizes of all neighboring panels.
What can be wrong?
Here is how I initialize constraints for input fields (and there are also fixed labels before each text field);
cns.ipady=1;
cns.ipadx=1;
cns.weightx=0;
cns.weighty=0;
cns.fill = GridBagConstraints.NONE;
cns.anchor = GridBagConstraints.EAST;
layout.setConstraints(label, cns);
and for text fields
cns.fill = GridBagConstraints.HORIZONTAL;
cns.gridwidth = GridBagConstraints.REMAINDER;
cns.weightx=1.0;
cns.weighty=0;
layout.setConstraints(tf, cns);
thanks,
Sergej.

Been there myself
http://forum.java.sun.com/thread.jsp?forum=57&thread=364047

Similar Messages

  • JTable disturbs gridbaglayout with jtextfields

    Hello, my problem is a JTable, that shrinks my two JTextFields to zero length. I tried to create the gui without the JTable and it works as expected. There should be two JTextFields with fixed length in a row below the JTable in a JTabbedPane. Code:
        jT1 = new JTable( 10,10);
        jSP1 = new JScrollPane( jT1);// without jT1 everything is fine
        jP1 = new JPanel( new BorderLayout());
        jP1.add( jSP1, BorderLayout.CENTER);
        jTP = new JTabbedPane();
        jTP.add( "Tab1", jP1);
        jL1 = new JLabel( "Txt1:");
        jTF1 = new JTextField( "0.00",10);
        jL2 = new JLabel( "Txt2:");
        jTF2 = new JTextField( "0.00",10);
        jP0 = new JPanel(new GridBagLayout());
        jP0.add(jTP, new GridBagConstraints(0, 0, 4, 1, 1.0, 1.0
            ,GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
        jP0.add(jL1, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
            ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 0, 0, 0), 0, 0));
        jP0.add(jTF1, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0
            ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 10, 0, 0), 0, 0));
        jP0.add(jL2, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0
            ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 20, 0, 0), 0, 0));
        jP0.add(jTF2, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0
            ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 10, 0, 0), 0, 0));Setting weightx to 0.5 and GriBagConstraints.HORIZONTAL for the JTextFields makes them variable size, but that' not what I want.

    What about setting iPadx parameter in GridBagConstraints?
    regards,
    Stas

  • Use MousePressed with JTextField

    Hi all,
    I am now facing a problem with the MouseEvent on JTextField.
    I used loop to create a JTextField array to store something. And now, if I click the TextField, the field will change color and a new value will be stored in that textfield array. But I would like to know how to indicate that mouse press action is related to which textfield? Should I use .getSource() ?
    Thanks!
    CK

    Hallo,
    I think that you have posted this in the wrong forum.

  • HELP, HELP, HELP, Problems using GridBagLayout with a BorderLayout

    I have a BorderLayout for my application. I created a JPanel that has the following items added to it:
    1)Button
    2)VisualComponent
    3)ControllerComponent
    The JPanel is then added to the WEST Pane of the BorderLayout. My problem is that I can not get my components in the JPanel to display correctly. The items should be added from top to buttom in my JPanel, but they overlap and display side by side, and some don't appear at all until my entire window application is Maximized. It seems as if all my components are trying to display in one row even though I explicitly add them to different rows as follows:
    1)addUsingGBL(openFile,0,1,2,1);
    2)addUsingGBL(visualComponent,1,1,1,3);
    3)addUsingGBL(controlsComponent,4,1,2,1);
    where addUsingGBL is as follows:
    void addUsingGBL(Component component,int row, int column, int width, int height)
    gbc. gridx = row;
         gbc.gridy = column;
         gbc.gridwidth = width;
         gbc.gridheight = height;
         gbLayout.setConstraints(component, gbc);
         mediaPanel.add(component);
         mediaPanel.doLayout();
    If anyone has any suggestions, I would greatly appreciate it. Entire code is available if needed. Thanks!

    Here is the code, sorry, didn't see that part before.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.media.*;
    public class MediaPlayerDemo extends JFrame /*implements ControllerListener*/{
    private Player player;
    private File file;
    public static JPanel mediaPanel;
    public static JScrollPane scrollableMediaPanel;
    //public static JFrame navigation = new JFrame("Lessons");
    public static Component visualComponent;
    public static Component controlsComponent;
    private static ImageIcon background = new ImageIcon("c:/Tony.jpg");
    public static GridBagConstraints gbc;
    public static GridBagLayout gbLayout;
    //public static panel column;
    //public static Container c;
    // inner class to handler events from media player
    private class EventHandler implements ControllerListener
         public void controllerUpdate( ControllerEvent e )
              if ( e instanceof EndOfMediaEvent)
              //if ( player == null )
              //return;
              player.close();
              //if ( visualComponent != null )
              mediaPanel.remove( visualComponent );
              //if ( controlsComponent != null )
              mediaPanel.remove( controlsComponent );
              mediaPanel.doLayout();
              // doLayout();
              if ( e instanceof RealizeCompleteEvent )
                   //c = getContentPane();
                   // load Visual and Control components if they exist
                   visualComponent =
                   player.getVisualComponent();
                   //visualComponent.setSize(5,5);
                   mediaPanel.doLayout();
                   //**Sets the layout for mediaPanel as GridLayout**
                   //**GridLayouts set the rows and col, **
                   //**& adds contentslt to rt **
                   //scrollableMediaPanel= new JScrollPane(mediaPanel);
                   //scrollableMediaPanel= new JScrollPane(mediaPanel);
                   gbc.weightx = 0;
                   gbc.weighty = 0;
                   gbc.fill = GridBagConstraints.NONE;
                   if ( visualComponent != null )
                   //add comp #2
                   addUsingGBL(visualComponent,1,1,1,3);
                   controlsComponent =
                   player.getControlPanelComponent();
                   if ( controlsComponent != null )
                   //add comp #3
                   //mediaPanel.add(controlsComponent);
                   addUsingGBL(controlsComponent,1,1,1,3);
                   controlsComponent =
                   player.getControlPanelComponent();
                   /*if ( controlsComponent != null )
                   //add comp #3
                   addUsingGBL(controlsComponent,4,1,2,1);
              doLayout();//after all components are added, you must redo your layout
              //**The following is for adding the a container only **
              //**getContentPane().add(mediaPanel,BorderLayout.WEST);**
              //**getContenPane().doLayout(); **
              //**setSize(200,700);//(width, Height) **
              //**show(); **
              }//if
         }//controllerUpdate
    }//eventHandler
    public MediaPlayerDemo()
         //**Title for a container **
         //**super( "Demonstrating the Java Media Player" );**
         mediaPanel = new panelBack(background);//instantiate JPanel Object
         gbLayout = new GridBagLayout();
         mediaPanel.setAlignmentY(TOP_ALIGNMENT);
         mediaPanel.setLayout(gbLayout);
                   gbc = new GridBagConstraints();
                   gbc.fill = GridBagConstraints.NONE;
                   //gbc.anchor = GridBagConstraints.NONE;
         //instatiate JButton object
         JButton openFile = new JButton( "Open file to play" );
         //openFile.setBounds(0, 0, 25, 25);
         //openFile.setVisible(true);
         //JBUTTON ActionListener
         openFile.addActionListener
              new ActionListener()
                   public void actionPerformed( ActionEvent e )
                   openFile();
                   createPlayer();
         );//addActionListener
         //add comp #1
         addUsingGBL(openFile,0,1,2,1);
         //set scrollPane
         scrollableMediaPanel = new JScrollPane(mediaPanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                   JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
         //Set Border
         scrollableMediaPanel.setViewportBorder(new BevelBorder(BevelBorder.RAISED));
    }//Constructor
    private void createPlayer()
         if ( file == null )
              return;
         removePreviousPlayer();
         try
              // create a new player and add listener
              player = Manager.createPlayer( file.toURL() );
              player.addControllerListener( new EventHandler() );
              player.start(); // start player
         catch ( Exception e )
              JOptionPane.showMessageDialog( this,
                   "Invalid file or location", "Error loading file",
                   JOptionPane.ERROR_MESSAGE );
    //Main only useful if creating a container to hold menuPanel
    public static void main(String args[])
         MediaPlayerDemo app = new MediaPlayerDemo();
         app.getContentPane().setLayout(new BorderLayout(0,0));
              app.getContentPane().setBackground(Color.white);
              app.getContentPane().add(scrollableMediaPanel, BorderLayout.WEST);
         app.getContentPane().validate();//re-layout a container for which the layout has changed
         app.setSize(1000,700);//(width, height)
         app.show();
         app.addWindowListener
              new WindowAdapter()
                   public void windowClosing( WindowEvent e )
                   System.exit(0);
    private void openFile()
         JFileChooser fileChooser = new JFileChooser();
         fileChooser.setFileSelectionMode(
              JFileChooser.FILES_ONLY );
         int result = fileChooser.showOpenDialog( this );
         // user clicked Cancel button on dialog
         if ( result == JFileChooser.CANCEL_OPTION )
              file = null;
         else
              file = fileChooser.getSelectedFile();
    private void removePreviousPlayer()
         if ( player == null )
              return;
         player.close();
         if ( visualComponent != null )
              mediaPanel.remove( visualComponent );
         if ( controlsComponent != null )
              mediaPanel.remove( controlsComponent );
         //set background for the JPanel
         public class panelBack extends JPanel
              ImageIcon image;
              panelBack(ImageIcon image)
                   super();
                   this.image=image;
              public void paintComponent(Graphics g)
                   image.paintIcon(this,g,0, 0);
         }//panelback
    void addUsingGBL(Component component,int row, int column, int width, int height)
    gbc = new GridBagConstraints();
         gbc. gridx = row;
         gbc.gridy = column;
         gbc.gridwidth = width;
         gbc.gridheight = height;
         gbLayout.setConstraints(component, gbc);
         mediaPanel.add(component);
         mediaPanel.doLayout();
    }//MediaPlayerDemo

  • HELP, HELP, HELP, Problems using GridBagLayout with BorderLayout

    I have a BorderLayout for my application. I created a JPanel that has the following items added to it:
    1)Button
    2)VisualComponent
    3)ControllerComponent
    The JPanel is then added to the WEST Pane of the BorderLayout. My problem is that I can not get my components in the JPanel to display correctly. The items should be added from top to buttom in my JPanel, but they overlap and display side by side, and some don't appear at all until my entire window application is Maximized. It seems as if all my components are trying to display in one row even though I explicitly add them to different rows as follows:
    1)addUsingGBL(openFile,0,1,2,1);
    2)addUsingGBL(visualComponent,1,1,1,3);
    3)addUsingGBL(controlsComponent,4,1,2,1);
    where addUsingGBL is as follows:
    void addUsingGBL(Component component,int row, int column, int width, int height)
    gbc. gridx = row;
    gbc.gridy = column;
    gbc.gridwidth = width;
    gbc.gridheight = height;
    gbLayout.setConstraints(component, gbc);
    mediaPanel.add(component);
    mediaPanel.doLayout();
    If anyone has any suggestions, I would greatly appreciate it. Entire code is available if needed. Thanks!

    void addUsingGBL(Component component,int row, int column, int width, int height)
    gbc. gridx = row;
    gbc.gridy = column;
    gbc.gridwidth = width;
    gbc.gridheight = height;
    gbLayout.setConstraints(component, gbc);
    mediaPanel.add(component);
    mediaPanel.doLayout();
    }I see that the problem is that you are using the same gridbagconstraints reference to add all your components. In effect, all your components refer to the same gridbagconstraints , you are getting all the components on a single row. The solution to this is simple - Try this out and tell me whether that works...
    void addUsingGBL(Component component,int row, int column, int width, int height)
    //Add this line in the beginning...
    gbc = new GridBagConstraints();
    gbc. gridx = row;
    gbc.gridy = column;
    gbc.gridwidth = width;
    gbc.gridheight = height;
    gbLayout.setConstraints(component, gbc);
    mediaPanel.add(component);
    mediaPanel.doLayout();

  • How can I display JTextFields correctly on a JPanel using GridBagLayout?

    I had some inputfields on a JPanel using the boxLayout. All was ok. Then I decided to change the panellayout to GridBagLayout. The JLabel fields are displayed correctly but the JTextField aren't. They are at the JPanel but have a size of 0??? So we cannot see what we type in these fields... Even when I put some text in the field before putting it on the panel.
    How can I display JTextFields correctly on a JPanel using GridBagLayout?
    here is a shortcut of my code:
    private Dimension sFieldSize10 = new Dimension(80, 20);
    // Create and instantiate Selection Fields
    private JLabel lSearchAbrText = new JLabel();
    private JTextField searchAbrText = new JTextField();
    // Set properties for SelectionFields
    lSearchAbrNumber.setText("ABR Number (0-9999999):");
    searchAbrNumber.setText("");
    searchAbrNumber.createToolTip();
    searchAbrNumber.setToolTipText("enter the AbrNumber.");
    searchAbrNumber.setPreferredSize(sFieldSize10);
    searchAbrNumber.setMaximumSize(sFieldSize10);
    public void createViewSubsetPanel() {
    pSubset = new JPanel();
    // Set layout
    pSubset.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    // Add Fields
    gbc.gridy = 0;
    gbc.gridx = GridBagConstraints.RELATIVE;
    pSubset.add(lSearchAbrNumber, gbc);
    // also tried inserting this statement
    // searchAbrNumber.setText("0000000");
    // without success
    pSubset.add(searchAbrNumber,gbc);
    pSubset.add(lSearchAbrText, gbc);
    pSubset.add(searchAbrText, gbc);
    gbc.gridy = 1;
    pSubset.add(lSearchClassCode, gbc);
    pSubset.add(searchClassCode, gbc);
    pSubset.add(butSearch, gbc);
    }

    import java.awt.*;
    import java.awt.event.*;
    import javax .swing.*;
    public class GridBagDemo {
      public static void main(String[] args) {
        JLabel
          labelOne   = new JLabel("Label One"),
          labelTwo   = new JLabel("Label Two"),
          labelThree = new JLabel("Label Three"),
          labelFour  = new JLabel("Label Four");
        JLabel[] labels = {
          labelOne, labelTwo, labelThree, labelFour
        JTextField
          tfOne   = new JTextField(),
          tfTwo   = new JTextField(),
          tfThree = new JTextField(),
          tfFour  = new JTextField();
        JTextField[] fields = {
          tfOne, tfTwo, tfThree, tfFour
        Dimension
          labelSize = new Dimension(125,20),
          fieldSize = new Dimension(150,20);
        for(int i = 0; i < labels.length; i++) {
          labels.setPreferredSize(labelSize);
    labels[i].setHorizontalAlignment(JLabel.RIGHT);
    fields[i].setPreferredSize(fieldSize);
    GridBagLayout gridbag = new GridBagLayout();
    JPanel panel = new JPanel(gridbag);
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;
    gbc.insets = new Insets(5,5,5,5);
    panel.add(labelOne, gbc);
    panel.add(tfOne, gbc);
    gbc.gridwidth = gbc.RELATIVE;
    panel.add(labelTwo, gbc);
    gbc.gridwidth = gbc.REMAINDER;
    panel.add(tfTwo, gbc);
    gbc.gridwidth = 1;
    panel.add(labelThree, gbc);
    panel.add(tfThree, gbc);
    gbc.gridwidth = gbc.RELATIVE;
    panel.add(labelFour, gbc);
    gbc.gridwidth = gbc.REMAINDER;
    panel.add(tfFour, gbc);
    final JButton
    smallerButton = new JButton("smaller"),
    biggerButton = new JButton("wider");
    final JFrame f = new JFrame();
    ActionListener l = new ActionListener() {
    final int DELTA_X = 25;
    int oldWidth, newWidth;
    public void actionPerformed(ActionEvent e) {
    JButton button = (JButton)e.getSource();
    oldWidth = f.getSize().width;
    if(button == smallerButton)
    newWidth = oldWidth - DELTA_X;
    if(button == biggerButton)
    newWidth = oldWidth + DELTA_X;
    f.setSize(new Dimension(newWidth, f.getSize().height));
    f.validate();
    smallerButton.addActionListener(l);
    biggerButton.addActionListener(l);
    JPanel southPanel = new JPanel(gridbag);
    gbc.gridwidth = gbc.RELATIVE;
    southPanel.add(smallerButton, gbc);
    gbc.gridwidth = gbc.REMAINDER;
    southPanel.add(biggerButton, gbc);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(panel);
    f.getContentPane().add(southPanel, "South");
    f.pack();
    f.setLocation(200,200);
    f.setVisible(true);

  • Not able to display all the componets using GridBagLayout manager

    Hii Javaites
    I m using GridBagLayout manager to display my components.
    But there is some problem.
    I am not able to view the last element of my second Row.
    Can anybody tell me what is wrong.
    This is driving me crazy.
    // code...................................................
    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    pane.setLayout(gridbag)
    c.weightx = c.weighty = 1;
    c.insets = new Insets(5, 5, 5, 5); // 5-pixel margins on all sides
    // First Row
    date_IconLabel= new JLabel("Date")
    c.gridx = 0;
    c.gridy = 0;
    pane.add(date_IconLabel,c);
    textField1= new JTextField(("Text 1");
    c.gridx = 1;
    c.gridy = 0;
    pane.add(textField1 ,c);
    textField2 = new JTextField("Text 2");
    c.gridx = 2;
    c.gridy = 0;
    c.gridwidth=GridBagConstraints.REMAINDER;
    pane.add(textField2 ,c);
    //2nd Row
    date_IconLabel= new JLabel("Date");
    c.gridx = 0;
    c.gridy = 1;
    pane.add(date_IconLabel,c);
    textField3 = new JTextField("Text 3");
    c.gridx = 1;
    c.gridy = 1;
    pane.add(textField3 ,c);
    textField4 = new JTextField("Text 4");
    c.gridx = 2;
    c.gridy = 1;
    pane.add(textField4,c);
    Message was edited by:
    help_eachother

    Hello,
    I create a new Constraint object for every component.
    It might look like nonsense but it is clearer what
    you are really specifying in every component
    constraints.
    I find it otherwise difficult to follow all the
    changes done to the constraint through all the
    components. Reuse is a great thing but in this case
    is confusing.That's why I created a simple subclass of GridBagConstaints with a reset() method and a few other goodies:
    ==================
    import java.awt.GridBagConstraints;
    import java.awt.Insets;
    public class GBC extends GridBagConstraints {
         public GBC() {
              super();
         public GBC(
              int gridx,
              int gridy,
              int gridwidth,
              int gridheight,
              double weightx,
              double weighty,
              int anchor,
              int fill,
              Insets insets,
              int ipadx,
              int ipady) {
              super(
                   gridx,
                   gridy,
                   gridwidth,
                   gridheight,
                   weightx,
                   weighty,
                   anchor,
                   fill,
                   insets,
                   ipadx,
                   ipady);
        public void reset() {
            gridx = RELATIVE;
            gridy = RELATIVE;
            gridwidth = 1;
            gridheight = 1;
            weightx = 0;
            weighty = 0;
            anchor = CENTER;
            fill = NONE;
            insets = new Insets(0, 0, 0, 0);
            ipadx = 0;
            ipady = 0;
        public String toString() {
            final String SEP = System.getProperty("line.separator");
            return "GridBagConstraints" + SEP +
                   "\tgridx = "         + getGridXString()      + SEP +
                   "\tgridy = "         + getGridYString()      + SEP +
                   "\tgridwidth = "     + getGridWidthString()  + SEP +
                   "\tgridheight = "    + getGridHeightString() + SEP +
                   "\tweightx = "       + weightx               + SEP +
                   "\tweighty = "       + weighty               + SEP +
                   "\tanchor = "        + getAnchorString()     + SEP +
                   "\tfill = "          + getFillString()       + SEP +
                   "\tinsets = "        + insets                + SEP +
                   "\tipadx = "         + ipadx                 + SEP +
                   "\tipady = "         + ipady;
        private final String getGridXString() {
            String s = null;
            switch (gridx) {
                case RELATIVE:
                    s = "RELATIVE";
                    break;
                default:
                    s = String.valueOf(gridx);
            return s;
        private final String getGridYString() {
            String s = null;
            switch (gridy) {
                case RELATIVE:
                    s = "RELATIVE";
                    break;
                default:
                    s = String.valueOf(gridy);
            return s;
        private final String getAnchorString() {
            String s = null;
            switch (anchor) {
                //Absolute values
                case CENTER:
                    s = "CENTER";
                    break;
                case NORTH:
                    s = "NORTH";
                    break;
                case NORTHEAST:
                    s = "NORTHEAST";
                    break;
                case EAST:
                    s = "EAST";
                    break;
                case SOUTHEAST:
                    s = "SOUTHEAST";
                    break;
                case SOUTH:
                    s = "SOUTH";
                    break;
                case SOUTHWEST:
                    s = "SOUTHWEST";
                    break;
                case WEST:
                    s = "WEST";
                    break;
                case NORTHWEST:
                    s = "NORTHWEST";
                    break;
                //realtive values
                case PAGE_START:
                    s = "PAGE_START";
                    break;
                case PAGE_END:
                    s = "PAGE_END";
                    break;
                case LINE_START:
                    s = "LINE_START";
                    break;
                case LINE_END:
                    s = "LINE_END";
                    break;
                case FIRST_LINE_START:
                    s = "FIRST_LINE_START";
                    break;
                case FIRST_LINE_END:
                    s = "FIRST_LINE_END";
                    break;
                case LAST_LINE_START:
                    s = "LAST_LINE_START";
                    break;
                case LAST_LINE_END:
                    s = "LAST_LINE_END";
                    break;
            return s;
        private final String getFillString() {
            String s = null;
            switch (fill) {
                case NONE:
                    s = "NONE";
                    break;
                case HORIZONTAL:
                    s = "HORIZONTAL";
                    break;
                case VERTICAL:
                    s = "VERTICAL";
                    break;
                case BOTH:
                    s = "BOTH";
                    break;
            return s;
        private final String getGridWidthString() {
            String s = null;
            switch (gridwidth) {
                case RELATIVE:
                    s = "REALTIVE";
                    break;
                case REMAINDER:
                    s = "REMAINDER";
                    break;
                default:
                    s = String.valueOf(gridwidth);
                    break;
            return s;
        private final String getGridHeightString() {
            String s = null;
            switch (gridheight) {
                case RELATIVE:
                    s = "REALTIVE";
                    break;
                case REMAINDER:
                    s = "REMAINDER";
                    break;
                default:
                    s = String.valueOf(gridheight);
                    break;
            return s;
    }

  • Using gridBagLayout

    I am currently developing a program using gridBagLayout. I am having problems getting the events to work correctly. I have noticed that events only seem to work with a class extending JPanel, and GridBagLayout needs to be written in the class that is extending JFrame.
    I have tryed various ways of writing the program so that I have 2 classes. One implements JPanel and one implementing JFrame, but when I do that I loose all of by buttons and text fields.
    Which parts of GridBagLayout need to be in the JFrame class and which ones can go in the JPanel class so that I can get my events working for my buttons and textfields?

    When I add in my action events they don't work.
    and Now I am working on getting keyevents to work with my buttons . . here are the functions that do not work and an explaination of what is missing. This program thus far is over 400 lines long
    class someClass extends JFrame implements ActionListener, KeyListener
    { final boolean shouldFill = true;
    final boolean shouldWeightX = true; // Some strange true false things
    public someClass()
    { setTitle("Some title"); // the title at the top of the window
    setSize(750, 500); // the size of the window in Pixels
    addWindowListener(new WindowAdapter() // Make sure the window
    { public void windowClosing(WindowEvent e)  //closes and the
    { System.exit(0);         // Program exits instead of
    } // Just hiding
    // This is the setup for implementing gridbaglayout
    // It has to go right here or this program will not work correctly
    Container contentPane = getContentPane(); // Initialize the container
    GridBagLayout gridbag = new GridBagLayout(); // Intitialize the GridBagLayout manager
    contentPane.setLayout(gridbag); // Put the gridbag inside the contentPane
    GridBagConstraints c = new GridBagConstraints(); // Initialize the constriants
    this is just the implimentation of my buttons and such
    //ActionListeners go here
    DoneButton.addActionListener(this);
    RejectPartButton.addActionListener(this);
    AcceptPassButton1.addActionListener(this);
    AcceptPassButton2.addActionListener(this);
    AcceptPassButton3.addActionListener(this);
    RejectPassButton1.addActionListener(this);
    RejectPassButton2.addActionListener(this);
    RejectPassButton3.addActionListener(this);
    serialSize.addActionListener(this);
    // I guess I'll put some KeyListeners here. this program needs them as well
    DoneButton.addKeyListener(this);
    RejectPartButton.addKeyListener(this);
    AcceptPassButton1.addKeyListener(this);
    AcceptPassButton2.addKeyListener(this);
    AcceptPassButton3.addKeyListener(this);
    RejectPassButton1.addKeyListener(this);
    RejectPassButton2.addKeyListener(this);
    RejectPassButton3.addKeyListener(this);
    serialSize.addKeyListener(this);
    // Now every button also has a key listener
    // Events are implemented differently in Swing than they were previously and
    //They are implemented differently from that when you use GridBagLayout
    public void actionPerformed(ActionEvent Aevent)
    { Object source = Aevent.getSource();
    Color color = getBackground();
    if (source == DoneButton)
    { color = color.red;
    else if (source = RejectPartButton)
    { color = color.blue;
    else if (source = AcceptPassButton1)
    { color = color.green;
    setbackground(color);
    repaint();
    // Let's toss in those KeyListener things here
    public void KeyPressed(KeyEvent Kevent)
    { int KeyCode = Kevent.getKeyCode();
    int modifiers = Kevent.getModifiers();
    if ( KeyCode == KeyEvent.VK_ENTER || KeyCode == KeyEvent.VK_TAB)
    { serialSize.requestFocus();
    else { transferFocus();
    public static void main(String[] args)
    { JFrame frame = new Norton3();
    frame.show();
    private JButton DoneButton;
    private JButton RejectPartButton;
    private JButton AcceptPassButton1;
    private JButton AcceptPassButton2;
    private JButton AcceptPassButton3;
    private JButton RejectPassButton1;
    private JButton RejectPassButton2;
    private JButton RejectPassButton3;
    private JTextField serialSize;
    } // end of some class
    // Looks like this is the end of the program

  • Memory problem with JTextFields

    Hello,
    I have a wierd problem with JTextField and the memory.
    I need to fill a JPanel with different Components (including JTextFields), then do some calculation, remove the Components and filling the JPanel again.
    When i so this too often my i get an OutOfMemory Exception. I narrowed to problem down and wrote a small sample program to demonstrate the problem.
    When i call the method doIT (where the Panel is repeatedly filled) from the main-function everything works fine, but when it is called as a result from the GUI-Button-Event the memory for the JTextFields is not freed (even the call of the Garbage collector changes nothing)
    When i only use JButtons to fill the Panel everything works fine.
    Has anyone an idea why this problem occurs and how i can work around it?
    [Edit] I tested it whith java 1.5.0_06, 1.5.0_11, 1.6.0_02
    Thanks
    Marc
    import java.awt.Frame;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.lang.management.ManagementFactory;
    import java.lang.management.MemoryUsage;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class MemoryTestDLG extends JDialog {
         public MemoryTestDLG(Frame owner) {
              // create Dialog with one Button that calls the testMethod
              super(owner);
              JButton b = new JButton("doIT ...");
              b.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        doIT();
                        setVisible(false);
              getContentPane().add(b);
              pack();
         public void doIT() {
              // Testmethod that fills a JPanel 20 times with Components and clears it
              // again
              JPanel p = new JPanel();
              long memUse1 = 0;
              long memUse2 = 0;
              long memUseTemp = 0;
              for (int count = 0; count < 20; count++) {
                   // Clear the panel
                   p.removeAll();
                   // Get memory usage before the task
                   Runtime.getRuntime().gc();
                   memUse1 = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()
                             .getUsed();
                   // Fill Panel with components
                   for (int i = 0; i < 200; i++) {
                        // The Buttons seem to be released without any problem
                        p.add(new JButton("test" + Math.random()));
                        // JTextFields are not released when used from the dialog.
                        p.add(new JTextField("test " + Math.random()));
                   // get memory usage after the task
                   Runtime.getRuntime().gc();
                   memUseTemp = memUse2;
                   memUse2 = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()
                             .getUsed();
                   // print Memory results
                   System.out.println("Memory Usage: " + f(memUse1) + "   ->"
                             + f(memUse2) + " [ Used:" + f(memUse2 - memUse1)
                             + " ] [ Freed: " + f(memUseTemp - memUse1) + "]");
         public String f(long m) // formats the output
              String s = "" + m;
              while (s.length() < 8)
                   s = " " + s;
              return s;
         public static void main(String[] args) {
              MemoryTestDLG d = new MemoryTestDLG(null);
              System.out
                        .println("------------------ Direct Call (all is OK) -------------------");
              d.doIT(); // Memory is freed with every call to JPanel.removeAll()
              System.out
                        .println("------------ Call from Dialog (memory is not freed) -------------");
              // The Memory keeps blocked
              d.setModal(true);
              d.setVisible(true);
              System.exit(0);
    }Message was edited by:
    marcvomorc

    Thank you for your answer,
    In this sample the programm does not run out of memory. But when you look at the output you see, that in the first run (direct call) the memory ist freed immediately when tha panel is cleared but in the second run (from the Button) the memory usage is getting bigger and bigger. Wenn you change the number of components to 2000 (4000)
    // Fill Panel with components
            for (int i = 0; i < 2000; i++) {
                // The Buttons seem to be released without any problem
    //... ...and use the default memory settings (69mb heap) the programm runns out of memory.
    I get the following output:
    ------------------ Direct Call (all is OK) -------------------
    Memory Usage:   445504   -> 8121016 [ Used: 7675512 ] [ Freed:  -445504]
    Memory Usage:   617352   -> 8114336 [ Used: 7496984 ] [ Freed:  7503664]
    Memory Usage:   810488   -> 8491768 [ Used: 7681280 ] [ Freed:  7303848]
    Memory Usage:   943704   -> 8114976 [ Used: 7171272 ] [ Freed:  7548064]
    Memory Usage:   836760   -> 8505072 [ Used: 7668312 ] [ Freed:  7278216]
    Memory Usage:   978352   -> 8114784 [ Used: 7136432 ] [ Freed:  7526720]
    Memory Usage:   835552   -> 8498288 [ Used: 7662736 ] [ Freed:  7279232]
    Memory Usage:   977096   -> 8114312 [ Used: 7137216 ] [ Freed:  7521192]
    Memory Usage:   835640   -> 8498376 [ Used: 7662736 ] [ Freed:  7278672]
    Memory Usage:   977296   -> 8115000 [ Used: 7137704 ] [ Freed:  7521080]
    Memory Usage:   835392   -> 8504872 [ Used: 7669480 ] [ Freed:  7279608]
    Memory Usage:   976968   -> 8115192 [ Used: 7138224 ] [ Freed:  7527904]
    Memory Usage:   836224   -> 8501624 [ Used: 7665400 ] [ Freed:  7278968]
    Memory Usage:   977840   -> 8115120 [ Used: 7137280 ] [ Freed:  7523784]
    Memory Usage:   835664   -> 8498256 [ Used: 7662592 ] [ Freed:  7279456]
    Memory Usage:   976856   -> 8114384 [ Used: 7137528 ] [ Freed:  7521400]
    Memory Usage:   835784   -> 8502848 [ Used: 7667064 ] [ Freed:  7278600]
    Memory Usage:   977360   -> 8114592 [ Used: 7137232 ] [ Freed:  7525488]
    Memory Usage:   835496   -> 8502720 [ Used: 7667224 ] [ Freed:  7279096]
    Memory Usage:   976440   -> 8115128 [ Used: 7138688 ] [ Freed:  7526280]
    ------------ Call from Dialog (memory is not freed) -------------
    Memory Usage:   866504   -> 8784320 [ Used: 7917816 ] [ Freed:  -866504]
    Memory Usage:  7480760   ->14631152 [ Used: 7150392 ] [ Freed:  1303560]
    Memory Usage: 14245264   ->22127104 [ Used: 7881840 ] [ Freed:   385888]
    Memory Usage: 19302896   ->27190744 [ Used: 7887848 ] [ Freed:  2824208]
    Memory Usage: 27190744   ->35073944 [ Used: 7883200 ] [ Freed:        0]
    Memory Usage: 31856624   ->39740176 [ Used: 7883552 ] [ Freed:  3217320]
    Memory Usage: 39740176   ->47623040 [ Used: 7882864 ] [ Freed:        0]
    Memory Usage: 44410480   ->52293864 [ Used: 7883384 ] [ Freed:  3212560]
    Memory Usage: 52293864   ->58569304 [ Used: 6275440 ] [ Freed:        0]
    Memory Usage: 58569304   ->64846400 [ Used: 6277096 ] [ Freed:        0]
    Exception occurred during event dispatching:
    java.lang.OutOfMemoryError: Java heap spacewhen I outcomment the adding of the JButtons the amount of freed memory is 0 in the second run. So my guess is, that there is a problem with freeing the memory for the JTextFields.
    Memory Usage:   447832   -> 6509960 [ Used: 6062128 ] [ Freed:  6332768]
    Memory Usage:   722776   -> 6785632 [ Used: 6062856 ] [ Freed:  5787184]
    ------------ Call from Dialog (memory is not freed) -------------
    Memory Usage:   468880   -> 6770240 [ Used: 6301360 ] [ Freed:  -468880]
    Memory Usage:  6770240   ->13016264 [ Used: 6246024 ] [ Freed:        0]
    Memory Usage: 13016264   ->19297080 [ Used: 6280816 ] [ Freed:        0]
    Memory Usage: 19297080   ->25570152 [ Used: 6273072 ] [ Freed:        0]
    Memory Usage: 25570152   ->31849160 [ Used: 6279008 ] [ Freed:        0]
    Memory Usage: 31849160   ->38124368 [ Used: 6275208 ] [ Freed:        0]
    Memory Usage: 38124368   ->44402072 [ Used: 6277704 ] [ Freed:        0]
    Memory Usage: 44402072   ->50677928 [ Used: 6275856 ] [ Freed:        0]
    Memory Usage: 50677928   ->56955880 [ Used: 6277952 ] [ Freed:        0]
    Memory Usage: 56955880   ->63232152 [ Used: 6276272 ] [ Freed:        0]
    Exception occurred during event dispatching:
    java.lang.OutOfMemoryError: Java heap spaceAdditionally the JPanel I am using is not displayed on the screen. It stays invisible the whole time, but i cannot work around that, because the calculation is depending on the values being in components on the JPanel)
    Marc

  • GridBagLayout with JScrollPane difficulties

    I'm having problems getting the components in a JPanel to layout properly. I'm using GridBagLayout and I'm having problems with adding a JScollPane.
    The JScrollPane in the layout (holding a subclass of a JPanel as its viewport) does not work properly in some case. When the viewport won't display fully, and requires scroll bars, the JScrollPane shrinks to a tiny size (i think just enough to display minimized scroll bars). What do I mean to add to fix this problem?
    Here is the relavent code:
    public ScenePanel()
         SceneImagePanel sceneImagePanel = new SceneImagePanel("Images/library.jpg");
         JScrollPane sceneScroller = new JScrollPane(sceneImagePanel);
         GridBagLayout gridbag = new GridBagLayout();
         GridBagConstraints c = new GridBagConstraints();
         this.setLayout(gridbag);
         c.insets = new Insets(5,5,5,5);
         JButton b1 = new JButton("Left");
         c.anchor = GridBagConstraints.WEST;
         c.fill = GridBagConstraints.VERTICAL;
         c.gridx = 0;
         c.gridy = 0;
         c.gridwidth = 5;
         c.gridheight = 5;
         c.weightx = 0.5;
         c.weighty = 0.5;
         gridbag.setConstraints(b1, c);
         this.add(b1);
         c.anchor = GridBagConstraints.CENTER;
         c.fill = GridBagConstraints.NONE;
         c.gridx = 5;
         c.gridwidth = 10;
         c.weightx = 0.0;
         c.weighty = 0.0;
         gridbag.setConstraints(sceneScroller, c);
         this.add(sceneScroller);
         JButton b2 = new JButton("Right");
         c.anchor = GridBagConstraints.EAST;
         c.fill = GridBagConstraints.VERTICAL;
         c.gridx = 15;
         c.gridwidth = 5;
         c.weightx = 0.5;
         c.weighty = 0.5;
         gridbag.setConstraints(b2, c);
         this.add(b2);
         JButton b3 = new JButton("Bottom");
         c.anchor = GridBagConstraints.SOUTH;
         c.fill = GridBagConstraints.HORIZONTAL;
         c.gridwidth = 20;
         c.gridx = 0;
         c.gridy = 5;
         c.weighty = -0.5;
         gridbag.setConstraints(b3, c);
         this.add(b3);
    //          this.add(sceneScroller, BorderLayout.CENTER);
    }Note: the commented out line at the end displayed the JScrollPane properly (though I want the scroll pane to be sized to fit its viewport, not its container, so I stopped using BorderLayout)

    Alright, I've figured out why the JScrollPane gets shrunk to such a small size...the 'fill' paramenter of the constraint can't be set to NONE. I've set it to 'BOTH' and changed the other constraints of some other components to fit.
    The problem now is that the scroll pane is too big...the scroll pane does not need to actually have either scroll bar in all cases. To accomidate these situations, I want the scroll pane to only be as large as it needs to be to display as much of its viewport is possible. Meaning, if the viewport does not need the scroll pane to take up as much room as is avaliable to it in the JPanel, the scroll pane should only be as large as needed, and leave empty space around it.
    Here is what I have now:
    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    this.setLayout(gridbag);
    c.insets = new Insets(5,5,5,5);
    JButton b1 = new JButton("Left");
    c.anchor = GridBagConstraints.WEST;
    c.fill = GridBagConstraints.VERTICAL;
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 5;
    c.gridheight = 5;
    c.weightx = -0.5;
    c.weighty = 0.5;
    gridbag.setConstraints(b1, c);
    this.add(b1);
    c.anchor = GridBagConstraints.CENTER;
    c.fill = GridBagConstraints.BOTH;
    c.gridx = 5;
    c.gridwidth = 10;
    c.weightx = 0.5;
    gridbag.setConstraints(sceneScroller, c);
    this.add(sceneScroller);
    JButton b2 = new JButton("Right");
    c.anchor = GridBagConstraints.EAST;
    c.fill = GridBagConstraints.VERTICAL;
    c.gridx = 15;
    c.gridwidth = 5;
    c.weightx = -0.5;
    c.weighty = 0.5;
    gridbag.setConstraints(b2, c);
    this.add(b2);
    JButton b3 = new JButton("Bottom");
    c.anchor = GridBagConstraints.SOUTH;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridwidth = 20;
    c.gridx = 0;
    c.gridy = 5;
    c.weighty = -0.5;
    gridbag.setConstraints(b3, c);
    this.add(b3);

  • Facing problem while adding combobox using gridbaglayout

    HI, I have used gridbaglayout in my panel. after adding the gridbaglayout, if i select long value combobox does't display all the value of the selected value. Why?
    This is my code
    cboPrioritySearchValue = new JComboBox();
    cboPrioritySearchValue.setBackground(Color.white);
    cboPrioritySearchValue.addItem("ALL");
    cboPrioritySearchValue.addItem(Priority.NOT.getValue());
    cboPrioritySearchValue.addItem(Priority.ONE.getValue());
    cboPrioritySearchValue.addItem(Priority.TWO.getValue());
    cboPrioritySearchValue.addItem(Priority.THREE.getValue());
    cboPrioritySearchValue.addItem(Priority.FOUR.getValue());
    setConstraints(gbc,gbc.WEST,gbc.NONE,2,1,2,8,new Insets(2,5,5,5),0,0,0,0);
    gbl.setConstraints(cboPrioritySearchValue,gbc);
    panel.add(cboPrioritySearchValue);This is my setConstraints method,
    public GridBagConstraints setConstraints(GridBagConstraints gbc, int anchor,int fill,
                                                 int gridw, int gridh, int gridx, int gridy,
                                                 Insets insets, int ipadx, int ipady,
                                                 int weightx, int weighty)
            gbc.anchor     = anchor;
            gbc.fill       = fill;
            gbc.gridwidth  = gridw;
            gbc.gridheight = gridh;
            gbc.gridx      = gridx;
            gbc.gridy      = gridy;
            gbc.insets     = insets;
            gbc.ipadx      = ipadx;
            gbc.ipady      = ipady;
            gbc.weightx    = weightx;
            gbc.weighty    = weighty;
            return gbc;
        }Edited by: JavaHeroPrince on May 13, 2010 6:58 AM

    Thanks Pete, hopefully its only a temporary problem.Short answer: It is (well ... hopefully).
    Long answer: My server's dying regularly because all the connections fill up in CLOSE_WAIT states. This doesn't seem to have the same root cause as the reported bugs that I can find (issues with older JDKs) so I'm interested in investigating it beyond just upgrading everything to the latest and crossing my fingers. Unfortunately that will take time and I'm a bit pressed for spare time at the moment - so: my apologies; the domain is likely to be down until after the weekend at least.
    After the weekend I'll re-target sscce.org (and .com and .net which I acquired a little while back) to a different server that's not suffering from the problem. Or if Andrew prefers I'll target a server under his control.

  • An difficulty when using GridBagLayout.

    Hi everyone!
    Now, I'm in a Java Swing project and I'm get trouble in using GridBagLayout to layout 2 component. I want to put 2 JTextArea in only one line with the width of them is the same(I've used c.weightx=1 and c.fill=GridBagContraints.HORIZONTAL). But when I fill data into one of them, the width of both is not the same. It's ok to use Spring layout to resolve this problem. But I think GridBagLayout is very flexible, so please help me to resolve this problem using GridBagLayout.
    Thanks a lot.

    if you want both textarea to have the same width, then use a GridLayout.
    as for GridBagLayout, i stop using it, and use third party Layout manager...such as FormLayout, GridBagPlusLayout (awsome), TableLayout, etc..
    they are easier to use, more readiable, and as powerful as GridBagLayout

  • HT202667 Hi - My daughter was using her Apple TV until recently when she got a Smart TV.  Now the Apple TV is not needed so she passed it on to me.  How do I get it transferred over from her Home Sharing account to mine so that I can use it with my PC?

    Hi - My daughter was using her Apple TV until recently when she got a Smart TV.  Now the Apple TV is not needed so she passed it on to me.  How do I get her Home Sharing account transferred over to mine so that I can use it with my PC? Thanks!

    As  Winston Churchill wrote, however you might want to do a factory reset on the Apple TV.
    This way all information pertaining to your daughter will be removed from the device. Specifically if see was sign into any of the streaming service, Netflix, Hulu, etc. her credentials will still be associated with this Apple TV, doing  a factory reset will remove all that and make it as if you purchased the device and just plugged it in.
    regards

  • OPEN CURSOR using a WITH clause in the select query

    Hi,
    I am using Oracle 9i. I have a requirement where I have a REFCURSOR as an OUT parameter for my procedure. I have declared the TYPE and created the procedure.
    In the procedure, I am using OPEN <cursor_name> FOR <query>;
    Ideally this works in most of the cases that I have tried earlier. However, in the current case I am using a WITH clause in my query to get the results.
    I need help in understanding if the above mentioned syntax would not allow me to use the WITH clause in the query.

    What error do you get , seems to work ok for me on 10g
    SQL> begin
      2  open :cv for 'with x as (select * from emp)  select * from x';
      3  end;
      4  /
    PL/SQL procedure successfully completed.
    SQL> print :cv
         EMPNO
    ENAME
    JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7521
    WARD
    SALESMAN        7698 22-FEB-81       1250        500         30
          7566
    JONES
    MANAGER         7839 02-APR-81       2975                    20
         EMPNO

  • My iPhone 4 will not sync my new voice memos from the "Voice Memos" app to my computer. This is frustrating, should not be so hard, can someone please help. I use PC with windows 7 with iPhone version 6.1.3 and iTunes most recent. Thanks.

    My iPhone 4 will not sync my new voice memos from the "Voice Memos" app to my computer. This is frustrating, should not be so hard, can someone please help. I use PC with windows 7 with iPhone version 6.1.3 and iTunes most recent. Thanks.

    In the Music tab of iTunes, do you have 'Include Voice Memos' checked?

Maybe you are looking for