Results 1 to 6 of 6
  1. #1
    Wolverine is offline Member
    Join Date
    Apr 2009
    Posts
    11
    Rep Power
    0

    Default [SOLVED] how to align JTextFiels[dimension] and JComboBox[dimension]

    Hi i whould to ask if somebody knows some method or some modality to align JTextFields[dimension] and JComboBox[dimension] that have tha same dimension

    I put my code with the issue that put JTextField-ies and JComboBox column:


    package grafica;

    import java.util.ArrayList;

    import java.awt.GridBagLayout;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.ButtonGroup;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JTextField;
    import javax.swing.JComboBox;

    import Gestione.*;

    public class PannelloInserimentoGiocatori extends JPanel{

    private GridBagLayout gridlayout;
    private Box riga1,riga21,riga22;
    private JComboBox[] list;
    private JLabel e1,e2;
    private JTextField[] nGiocatori;
    private int nElementi;
    private ArrayList<Giocatore> lista; //bisogna recuperare i dati da un file;
    //private Start start;
    /**
    * Costruttore che mi realizza i pannelli con le JTextField in cui inserire i nomi dei giocatori e le JComboBox
    * con cui si sceglie il ruolo
    * @param il titolo del pannello corrispondente
    */



    public PannelloInserimentoGiocatori(GridBagLayout gr)
    {

    super();
    this.gridlayout=gr;
    // creo la riga delle etichette inserisci nome e ruolo
    e1 = new JLabel("nome giocatore");
    e2 = new JLabel("scelta ruolo");

    e2.setHorizontalAlignment(JTextField.RIGHT);
    riga1 = new Box(BoxLayout.X_AXIS);
    riga1.add(e1);
    riga1.add(Box.createHorizontalStrut(100));
    riga1.add(e2);

    //creo la colonna dei textfields dove inserire i nomi
    riga21 = new Box(BoxLayout.Y_AXIS);

    nGiocatori = new JTextField[25];
    list = new JComboBox[25];
    for(int i=0;i<nGiocatori.length;i++)
    {
    nGiocatori[i] = new JTextField(20);
    list[i] = new JComboBox();
    list[i].setEditable(false);

    list[i].addItem("Portiere");
    list[i].addItem("Difensore");
    list[i].addItem("Centrocampista");
    list[i].addItem("Attaccante");
    riga21.add(nGiocatori[i]);
    riga21.add(list[i]);
    }

    this.add(riga1);
    this.add(riga21);

    }

    public void PannelloInserimentoGiocatoriTest()
    {
    //super();
    // creo la riga delle etichette inserisci nome e ruolo
    e1 = new JLabel("nome giocatore");
    e2 = new JLabel("scelta ruolo");
    riga1 = new Box(BoxLayout.X_AXIS);
    riga1.add(e1);
    riga1.add(Box.createHorizontalStrut(100));
    riga1.add(e2);

    //creo la colonna dei textfields dove inserire i nomi
    riga21 = new Box(BoxLayout.Y_AXIS);

    nGiocatori = new JTextField[25];
    for(int i=0;i<nGiocatori.length;i++)
    {
    nGiocatori[i] = new JTextField(20);
    }

    for(int i=0;i<nGiocatori.length;i++)
    {
    riga21.add(nGiocatori[i]);
    }

    riga21.add(Box.createVerticalStrut(100));

    riga22 = new Box(BoxLayout.Y_AXIS);

    list = new JComboBox[25];
    for(int i=0;i<list.length;i++)
    {
    list[i] = new JComboBox();
    list[i].setEditable(false);

    list[i].addItem("Portiere");
    list[i].addItem("Difensore");
    list[i].addItem("Centrocampista");
    list[i].addItem("Attaccante");
    riga22.add(list[i]);

    }



    lista = new ArrayList<Giocatore>();

    this.add(riga1);
    this.add(riga21);
    this.add(riga22);

    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Can you go into a bit more detail as to:
    1) just exactly what you are trying to do, and
    2) how your current code does not do what you want?

    Also, when posting code here, please use code tags so that your code will retain its formatting and thus will be readable -- after all, your goal is to get as many people to read your post and understand your code as possible, right?

    To do this, highlight your pasted code (please be sure that it is already formatted when you paste it into the forum; the code tags don't magically format unformatted code) and then press the code button, and your code will have tags.

    Another way to do this is to manually place the tags into your code by placing the tag [cod&#101;] above your pasted code and the tag [/cod&#101;] below your pasted code like so:

    Java Code:
    [cod&#101;]
      // your code goes here
      // notice how the top and bottom tags are different
    [/cod&#101;]
    Best of luck.

  3. #3
    Wolverine is offline Member
    Join Date
    Apr 2009
    Posts
    11
    Rep Power
    0

    Default

    Thanks Fubarable for your hint,as you had seen my english isn't very good...and also i'm not frequent with forum.
    Anyway i'm what i'm tring to is in more general make a GUI for a program that manage a list of soccer players.I just made the structure of management information systems,than i will to create a GUI to employ that.

    First of all my java knowledge are basically,just teoretical,university degrees,and very small pratics.
    My ideas is to have a program desktop divided in three areas,the first one in the left,where i have table with players'name and players' features;
    than a second block where i would like put some bottons and a little area,and the threth areas in the rigth where i have a list of 25 JTextFileds connected with the same numbers of JComBOx.
    The user would able to write is preferded player name in the JTextFiled and than select the rule.
    So the first thing is how i can divided in the best way my desktop,and what class,Component can i use?
    I'm not very pratic with comlex Gui,i must made this for 27th may:o)

    Java Code:
       
         package grafica;
    
    import java.util.ArrayList;
    
    import javax.swing.*;
    import javax.swing.SpringLayout;
    import java.awt.*;
    import java.awt.event.*;
    
    import Gestione.*;
    
    public class PannelloInserimentoGiocatori2 extends JPanel implements ActionListener 
                                                                        {
    	
    	private JComponent[] campi; 
    	private SpringUtilities spring;
    	private Box riga1,riga21,riga22;
    	private JComboBox[] list;
    	private JLabel e1,e2;
    	private JTextField[] nGiocatori;
    	private int nElementi;
    	private ArrayList<Giocatore> lista; //bisogna recuperare i dati da un file;
    	
    	final static int GAP =5;
    	/**
    	 * Costruttore che mi realizza i pannelli con le JTextField in cui inserire i nomi dei giocatori e le JComboBox 
    	 * con cui si sceglie il ruolo
    	 * @param  il titolo del pannello corrispondente
    	 */
    	
    	
    	
    	public PannelloInserimentoGiocatori2()
    	{
    		
    		super();
    		JPanel pannello = new JPanel(new SpringLayout());
    		 // creo la riga delle etichette inserisci nome e ruolo
    		e1 = new JLabel("nome giocatore");
    		e2 = new JLabel("scelta ruolo");
    		e2.setHorizontalAlignment(JTextField.RIGHT);
    		
    		riga1 = new Box(BoxLayout.X_AXIS);
    		riga1.add(e1);
    		riga1.add(Box.createHorizontalStrut(100));
    		riga1.add(e2);
    		
    		creo la colonna dei textfields dove inserire i nomi
    		riga21 = new Box(BoxLayout.Y_AXIS);
    		
    		
    		
    		nGiocatori = new JTextField[25];
    		
    		list = new JComboBox[25];
    		for(int i=0;i<nGiocatori.length;i++) 
    		{
    		   nGiocatori[i] = new JTextField(20);
    		   list[i] = new JComboBox();
    		   list[i].setEditable(false);
    			
    		   list[i].addItem("Portiere");
    		   list[i].addItem("Difensore");
    		   list[i].addItem("Centrocampista");
    		   list[i].addItem("Attaccante");
    		   riga21.add(nGiocatori[i]);
    		   riga21.add(list[i]);
    		}
    		
    		this.add(riga1);
    		this.add(riga21);
    
             public void PannelloInserimentoGiocatoriTest()
    	{
    		
    	    // creo la riga delle etichette inserisci nome e ruolo
    		e1 = new JLabel("nome giocatore");
    		e2 = new JLabel("scelta ruolo");
    		riga1 = new Box(BoxLayout.X_AXIS);
    		riga1.add(e1);
    		riga1.add(Box.createHorizontalStrut(100));
    		riga1.add(e2);
    		
    		//creo la colonna dei textfields dove inserire i nomi
    		riga21 = new Box(BoxLayout.Y_AXIS);
    		
    		nGiocatori = new JTextField[25];
    		for(int i=0;i<nGiocatori.length;i++) 
    		{
    		   nGiocatori[i] = new JTextField(20);
    		   nGiocatori[i].setHorizontalAlignment(JTextField.RIGHT);
    		}	
    		
    		for(int i=0;i<nGiocatori.length;i++)
    		{
    			//riga21.add(nGiocatori[i]);
    		}
    		
    		riga21.add(Box.createVerticalStrut(100));		
    		
    		riga22 = new Box(BoxLayout.Y_AXIS);
    		
    		list = new JComboBox[25];
    		for(int i=0;i<list.length;i++)
    		{
    			list[i] = new JComboBox();
    			list[i].setEditable(false);
    			
    			list[i].addItem("Portiere");
    			list[i].addItem("Difensore");
    			list[i].addItem("Centrocampista");
    			list[i].addItem("Attaccante");
    			//riga22.add(list[i]);
    			
    		}
    		
    		
    		
    		lista = new ArrayList<Giocatore>();
    		
    		this.add(riga1);
    		this.add(riga21);
    		this.add(riga22);
    }
    that my code doesn't do is that JTextField[] and JComboBOx[] are in the same column,in this way:

    JTextField[0]
    JComboBox[0]
    JTextField[1]
    JComboBox[1]

    than the Label e1 and e2 are in left,but they would stay in Bottom,one over column' s JTextField and the other over JComboBox

  4. #4
    Wolverine is offline Member
    Join Date
    Apr 2009
    Posts
    11
    Rep Power
    0

    Default

    I found this utility class for structure Gui:

    Java Code:
    /*
     * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     *
     *   - Redistributions of source code must retain the above copyright
     *     notice, this list of conditions and the following disclaimer.
     *
     *   - Redistributions in binary form must reproduce the above copyright
     *     notice, this list of conditions and the following disclaimer in the
     *     documentation and/or other materials provided with the distribution.
     *
     *   - Neither the name of Sun Microsystems nor the names of its
     *     contributors may be used to endorse or promote products derived
     *     from this software without specific prior written permission.
     *
     * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
     * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
     * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
     * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
     * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
     * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
     * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     */ 
    
    package components;
    
    import javax.swing.*;
    import javax.swing.SpringLayout;
    import java.awt.*;
    
    /**
     * A 1.4 file that provides utility methods for
     * creating form- or grid-style layouts with SpringLayout.
     * These utilities are used by several programs, such as
     * SpringBox and SpringCompactGrid.
     */
    public class SpringUtilities {
        /**
         * A debugging utility that prints to stdout the component's
         * minimum, preferred, and maximum sizes.
         */
        public static void printSizes(Component c) {
            System.out.println("minimumSize = " + c.getMinimumSize());
            System.out.println("preferredSize = " + c.getPreferredSize());
            System.out.println("maximumSize = " + c.getMaximumSize());
        }
    
        /**
         * Aligns the first <code>rows</code> * <code>cols</code>
         * components of <code>parent</code> in
         * a grid. Each component is as big as the maximum
         * preferred width and height of the components.
         * The parent is made just big enough to fit them all.
         *
         * @param rows number of rows
         * @param cols number of columns
         * @param initialX x location to start the grid at
         * @param initialY y location to start the grid at
         * @param xPad x padding between cells
         * @param yPad y padding between cells
         */
        public static void makeGrid(Container parent,
                                    int rows, int cols,
                                    int initialX, int initialY,
                                    int xPad, int yPad) {
            SpringLayout layout;
            try {
                layout = (SpringLayout)parent.getLayout();
            } catch (ClassCastException exc) {
                System.err.println("The first argument to makeGrid must use SpringLayout.");
                return;
            }
    
            Spring xPadSpring = Spring.constant(xPad);
            Spring yPadSpring = Spring.constant(yPad);
            Spring initialXSpring = Spring.constant(initialX);
            Spring initialYSpring = Spring.constant(initialY);
            int max = rows * cols;
    
            //Calculate Springs that are the max of the width/height so that all
            //cells have the same size.
            Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0)).
                                        getWidth();
            Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0)).
                                        getWidth();
            for (int i = 1; i < max; i++) {
                SpringLayout.Constraints cons = layout.getConstraints(
                                                parent.getComponent(i));
    
                maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth());
                maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight());
            }
    
            //Apply the new width/height Spring. This forces all the
            //components to have the same size.
            for (int i = 0; i < max; i++) {
                SpringLayout.Constraints cons = layout.getConstraints(
                                                parent.getComponent(i));
    
                cons.setWidth(maxWidthSpring);
                cons.setHeight(maxHeightSpring);
            }
    
            //Then adjust the x/y constraints of all the cells so that they
            //are aligned in a grid.
            SpringLayout.Constraints lastCons = null;
            SpringLayout.Constraints lastRowCons = null;
            for (int i = 0; i < max; i++) {
                SpringLayout.Constraints cons = layout.getConstraints(
                                                     parent.getComponent(i));
                if (i % cols == 0) { //start of new row
                    lastRowCons = lastCons;
                    cons.setX(initialXSpring);
                } else { //x position depends on previous component
                    cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST),
                                         xPadSpring));
                }
    
                if (i / cols == 0) { //first row
                    cons.setY(initialYSpring);
                } else { //y position depends on previous row
                    cons.setY(Spring.sum(lastRowCons.getConstraint(SpringLayout.SOUTH),
                                         yPadSpring));
                }
                lastCons = cons;
            }
    
            //Set the parent's size.
            SpringLayout.Constraints pCons = layout.getConstraints(parent);
            pCons.setConstraint(SpringLayout.SOUTH,
                                Spring.sum(
                                    Spring.constant(yPad),
                                    lastCons.getConstraint(SpringLayout.SOUTH)));
            pCons.setConstraint(SpringLayout.EAST,
                                Spring.sum(
                                    Spring.constant(xPad),
                                    lastCons.getConstraint(SpringLayout.EAST)));
        }
    
        /* Used by makeCompactGrid. */
        private static SpringLayout.Constraints getConstraintsForCell(
                                                    int row, int col,
                                                    Container parent,
                                                    int cols) {
            SpringLayout layout = (SpringLayout) parent.getLayout();
            Component c = parent.getComponent(row * cols + col);
            return layout.getConstraints(c);
        }
    
        /**
         * Aligns the first <code>rows</code> * <code>cols</code>
         * components of <code>parent</code> in
         * a grid. Each component in a column is as wide as the maximum
         * preferred width of the components in that column;
         * height is similarly determined for each row.
         * The parent is made just big enough to fit them all.
         *
         * @param rows number of rows
         * @param cols number of columns
         * @param initialX x location to start the grid at
         * @param initialY y location to start the grid at
         * @param xPad x padding between cells
         * @param yPad y padding between cells
         */
        public static void makeCompactGrid(Container parent,
                                           int rows, int cols,
                                           int initialX, int initialY,
                                           int xPad, int yPad) {
            SpringLayout layout;
            try {
                layout = (SpringLayout)parent.getLayout();
            } catch (ClassCastException exc) {
                System.err.println("The first argument to makeCompactGrid must use SpringLayout.");
                return;
            }
    
            //Align all cells in each column and make them the same width.
            Spring x = Spring.constant(initialX);
            for (int c = 0; c < cols; c++) {
                Spring width = Spring.constant(0);
                for (int r = 0; r < rows; r++) {
                    width = Spring.max(width,
                                       getConstraintsForCell(r, c, parent, cols).
                                           getWidth());
                }
                for (int r = 0; r < rows; r++) {
                    SpringLayout.Constraints constraints =
                            getConstraintsForCell(r, c, parent, cols);
                    constraints.setX(x);
                    constraints.setWidth(width);
                }
                x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
            }
    
            //Align all cells in each row and make them the same height.
            Spring y = Spring.constant(initialY);
            for (int r = 0; r < rows; r++) {
                Spring height = Spring.constant(0);
                for (int c = 0; c < cols; c++) {
                    height = Spring.max(height,
                                        getConstraintsForCell(r, c, parent, cols).
                                            getHeight());
                }
                for (int c = 0; c < cols; c++) {
                    SpringLayout.Constraints constraints =
                            getConstraintsForCell(r, c, parent, cols);
                    constraints.setY(y);
                    constraints.setHeight(height);
                }
                y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
            }
    
            //Set the parent's size.
            SpringLayout.Constraints pCons = layout.getConstraints(parent);
            pCons.setConstraint(SpringLayout.SOUTH, y);
            pCons.setConstraint(SpringLayout.EAST, x);
        }
    but i'not able to use in my code

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    There are many many ways of laying out components in a container, and I think that the key here is to learn about as many of the layout managers as you can, especially the simpler ones (e.g., FlowLayout, GridLayout, BoxLayout, BorderLayout), and to nest layout using components inside one another. For instance, a simple way (over-simple?) of arranging your components would be to use a BoxLayout.LINE_AXIS overall, then add your textpanel/combobox combinations into a JPanel that uses a GridLayout with 2 columns, and then place this into a JScrollPane. Then place the two JLabels into another JPanel and place the label holding panel and the JScrollpane into another JPanel that uses a BorderLayout (the labels on top and the scrollpane in the center).... the iterations can be endless. For instance:
    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.SwingConstants;
    
    public class Fu3Swing {
      private static final String[] LIST_STRINGS = { 
        "Portiere", "Difensore",
        "Centrocampista", "Attaccante" 
      };
      private static final String NOME_GIOCATORE = "nome giocatore";
      private static final String SCELTA_RUOLO = "scelta ruolo";
      private static final int COMBO_COUNT = 30;
    
      private JPanel mainPanel = new JPanel();
      private JComboBox[] list = new JComboBox[COMBO_COUNT];
      private JTextField[] nGiocatori = new JTextField[COMBO_COUNT];
    
      public Fu3Swing() {
        JPanel gridPanel = new JPanel(new GridLayout(0, 2, 5, 5));
        JPanel topPanel = new JPanel(new  GridLayout(0, 2, 5, 5));
        
        topPanel.add(new JLabel(NOME_GIOCATORE, SwingConstants.CENTER));
        topPanel.add(new JLabel(SCELTA_RUOLO, SwingConstants.CENTER));
        
        for (int i = 0; i < list.length; i++) {
          nGiocatori[i] = new JTextField(20);
          list[i] = new JComboBox(LIST_STRINGS);
          list[i].setEditable(false);
          
          gridPanel.add(nGiocatori[i]);
          gridPanel.add(list[i]);
        }
        
        JScrollPane gridScroll = new JScrollPane(gridPanel);
        Dimension gsSize = gridScroll.getPreferredSize();
        gridScroll.setPreferredSize(new Dimension(gsSize.width + 15, 500));
        
        JPanel rightPanel = new JPanel(new BorderLayout());
        rightPanel.add(topPanel, BorderLayout.PAGE_START);
        rightPanel.add(gridScroll, BorderLayout.CENTER);
        
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.LINE_AXIS));
        mainPanel.add(Box.createHorizontalStrut(200));
        mainPanel.add(new JLabel("Other stuff goes here"));
        mainPanel.add(Box.createHorizontalStrut(200));
        mainPanel.add(rightPanel);
      }
    
      public JPanel getPanel() {
        return mainPanel;
      }
    
      private static void createAndShowUI() {
        JFrame frame = new JFrame("Fubarable Swing App");
        frame.getContentPane().add(new Fu3Swing().getPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
    	createAndShowUI();
          }
        });
      }
    }
    You can read up on using layout managers here: Laying Out Components within a Container
    Last edited by Fubarable; 05-18-2009 at 03:58 AM.

  6. #6
    Wolverine is offline Member
    Join Date
    Apr 2009
    Posts
    11
    Rep Power
    0

    Default

    Fubarable thanks you very much...i just compile your code,it just mades what i look for to do in the first inquiry...so this problem is solved.Than i'm going to follow your suggestion for the complete structure...maybe i need more help in immediate future...
    Now just ask you i make this post like solved?

Similar Threads

  1. noob: two-dimension array
    By bobmasta5 in forum New To Java
    Replies: 5
    Last Post: 03-15-2009, 11:42 PM
  2. JPanel in agreement with dimension of pictures
    By KamilR in forum AWT / Swing
    Replies: 1
    Last Post: 04-28-2008, 07:38 AM
  3. Replies: 2
    Last Post: 04-27-2008, 07:51 PM
  4. Arraylist to a 2- dimension array conversion
    By mars123 in forum New To Java
    Replies: 1
    Last Post: 12-06-2007, 11:24 AM
  5. JTextArea - text align
    By bradder in forum AWT / Swing
    Replies: 1
    Last Post: 11-29-2007, 07:08 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •