align the JLabels and JTextFields vertically in different areas

I have 3 TitledBorders to 3 different areas of my frame.
Each region has its own components - JLabels, textfield, etc..
How to align the JLabels and JTextFields vertically in different areas?
for example, for the following test program, how to configure label1, label2, label3 so that their right sides all align them vertically and
TF1, tf2, tf3 so that their left ribs all line up vertically?
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

public class TitledBorderDemo extends JFrame {
  public TitledBorderDemo() {
    super("TitledBorderDemo");

    JTextField tf1 = new JTextField("hello", 6);
    JTextField tf2 = new JTextField("hello", 12);
    JTextField tf3 = new JTextField("test");
    JTextField tf4 = new JTextField("test2");

    JLabel label1 = new JLabel("1234567890ertyuiyup label");
    JLabel label2 = new JLabel("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz long label");
    JLabel label3 = new JLabel("short label");
    JLabel label4 = new JLabel("test");

    JPanel panel_tf = new JPanel(new GridBagLayout());
    JPanel panel_pf = new JPanel(new GridBagLayout());
    JPanel panel_ftf = new JPanel(new GridBagLayout());
    
    GridBagConstraints constraints = new GridBagConstraints(0, 0, 3, 3,
            0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
            new Insets(10, 10, 10, 10), 0, 0);

    constraints.gridx = 0;
    constraints.gridy = 0;
    constraints.gridwidth = 2;
    constraints.anchor = GridBagConstraints.WEST;
    panel_tf.add(label1, constraints);
    
    constraints.gridx = 2;
    constraints.gridwidth = 1;
    constraints.anchor = GridBagConstraints.EAST;
    panel_tf.add(tf1, constraints);

    constraints.gridx = 0;
    constraints.gridy = 1;
    constraints.gridwidth = 2;
    constraints.anchor = GridBagConstraints.WEST;
    panel_pf.add(label2, constraints);

    constraints.gridx = 2;
    constraints.gridwidth = 1;
    constraints.anchor = GridBagConstraints.EAST;
    panel_pf.add(tf2, constraints);
    
    constraints.gridx = 0;
    constraints.gridy = 2;
    constraints.gridwidth = 2;
    constraints.anchor = GridBagConstraints.WEST;
    panel_ftf.add(label3, constraints);

    constraints.gridx = 2;
    constraints.gridwidth = 1;
    constraints.anchor = GridBagConstraints.EAST;
    panel_ftf.add(tf3, constraints);

    constraints.gridx = 3;
    constraints.gridwidth = 1;
    constraints.anchor = GridBagConstraints.WEST;
    panel_ftf.add(label4, constraints);

    constraints.gridx = 4;
    constraints.anchor = GridBagConstraints.EAST;
    panel_ftf.add(tf4, constraints);


    panel_tf.setBorder(new TitledBorder("JTextField1"));
    panel_pf.setBorder(new TitledBorder("JTextField2"));
    panel_ftf.setBorder(new TitledBorder("JTextField3"));

    JPanel pan = new JPanel(new GridLayout(3, 1, 10, 10));
    pan.add(panel_tf);
    pan.add(panel_pf);
    pan.add(panel_ftf);
    this.add(pan);
  }

  public static void main(String args[]) {
    JFrame frame = new TitledBorderDemo();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(600, 450);
    frame.setVisible(true);
  }
}

I forgot how tedious GBL can be straight out of the box, since I usually use a helper class that I wrote for the work of constraints (a common approach).

Anyway, here's a sample program ussing the technique I described previously. Note the horizontal on the panels of 1st and 3rd spacers that are used to "take out" the text fields so they line up on the left with the text of Group 2 field. I also added some glues at the end of these panels to make each Panel to fill in the same width.

import java.awt.*;

import javax.swing.*;
import javax.swing.border.*;

public class TitledBorderDemo extends JFrame {
  public TitledBorderDemo() {
    super("TitledBorderDemo");

    JLabel nameLabel = new JLabel("Name");
    JTextField nameText = new JTextField(20);

    JLabel addressLabel = new JLabel("Address (City & State)");
    JTextField addressText = new JTextField(40);

    JLabel phoneLabel = new JLabel("Phone");
    JTextField phoneText = new JTextField(20);

    int longWidth = addressLabel.getPreferredSize().width;

    GridBagConstraints constraints = new GridBagConstraints();

    //--------------------

    JPanel p1 = new JPanel(new GridBagLayout());
    p1.setBorder(createBorder("Name"));

    constraints.gridx = 0;
    constraints.gridy = 0;
    constraints.anchor = GridBagConstraints.EAST;
    constraints.insets = new Insets(4,6,4,6);
    p1.add(nameLabel, constraints);

    constraints.gridx = 1;
    constraints.anchor = GridBagConstraints.WEST;
    p1.add(nameText, constraints);

    constraints.gridx = 2;
    constraints.anchor = GridBagConstraints.WEST;
    constraints.fill = GridBagConstraints.HORIZONTAL;
    constraints.weightx = 1.0;
    p1.add(Box.createHorizontalGlue(), constraints);

    constraints.gridx = 0;
    constraints.gridy = 1;
    constraints.fill = GridBagConstraints.NONE;
    constraints.weightx = 0.0;
    p1.add(Box.createHorizontalStrut(longWidth), constraints);

    //--------------------

    JPanel p2 = new JPanel(new GridBagLayout());
    p2.setBorder(createBorder("Address"));

    constraints.gridx = 0;
    constraints.gridy = 0;
    constraints.anchor = GridBagConstraints.EAST;
    constraints.insets = new Insets(4,6,4,6);
    p2.add(addressLabel, constraints);

    constraints.gridx = 1;
    constraints.anchor = GridBagConstraints.WEST;
    p2.add(addressText, constraints);

    constraints.gridx = 2;
    constraints.anchor = GridBagConstraints.WEST;
    constraints.fill = GridBagConstraints.HORIZONTAL;
    constraints.weightx = 1.0;
    p2.add(Box.createHorizontalGlue(), constraints);

    constraints.gridx = 0;
    constraints.gridy = 1;
    constraints.fill = GridBagConstraints.NONE;
    constraints.weightx = 0.0;
    p2.add(Box.createHorizontalStrut(longWidth), constraints);

    //--------------------

    JPanel p3 = new JPanel(new GridBagLayout());
    p3.setBorder(createBorder("Phone"));

    constraints.gridx = 0;
    constraints.gridy = 0;
    constraints.anchor = GridBagConstraints.EAST;
    constraints.insets = new Insets(4,6,4,6);
    p3.add(phoneLabel, constraints);

    constraints.gridx = 1;
    constraints.anchor = GridBagConstraints.WEST;
    p3.add(phoneText, constraints);

    constraints.gridx = 2;
    constraints.anchor = GridBagConstraints.WEST;
    constraints.fill = GridBagConstraints.HORIZONTAL;
    constraints.weightx = 1.0;
    p3.add(Box.createHorizontalGlue(), constraints);

    constraints.gridx = 0;
    constraints.gridy = 1;
    constraints.fill = GridBagConstraints.NONE;
    constraints.weightx = 0.0;
    p3.add(Box.createHorizontalStrut(longWidth), constraints);

    //--------------------

    JPanel panel = new JPanel(new GridBagLayout());

    constraints.gridx = 0;
    constraints.gridy = 0;
    constraints.fill = GridBagConstraints.HORIZONTAL;
    constraints.weightx = 1.0;
    panel.add(p1, constraints);

    constraints.gridy = 1;
    panel.add(p2, constraints);

    constraints.gridy = 2;
    panel.add(p3, constraints);

    this.add(new JScrollPane(panel));
  }

  private Border createBorder(String title)
  {
    TitledBorder b = new TitledBorder(title);
    b.setTitleColor(Color.RED.darker());
    return b;
  }

  public static void main(String args[]) {
    JFrame frame = new TitledBorderDemo();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}

Tags: Java

Similar Questions

  • by aligning the front and back of the cards to collect

    I designed a model of 2.5x3.5 9 cards to Exchange, but when I take it the printer front and back are not aligned. Can someone help me to align the front and back. When I print on my printer, they seem well but when I take them to printing, the alignment is off. Need help!

    It's weird.

    What is the difference?

    Viewing at 100% in Photoshop?

    You provide the printer with a PDF file?  (I had some strange things happen with PDF on more than one occasion.)

    Did you use guides to align layers/objects?

    You flatten the output file?

  • All my shortcuts on the desktop and start menu - all programs are showing up with blank windows pages icon.

    Original title: broken shortcut

    ALL my shortcuts on the desktop and start menu - all programs are showing up with blank windows pages icon and the name of the file and .lnk I uninstalled something and it happened that I tried system recovery and everything else that I uninstalled the States are back but this how can I solve this?

    Hello

    1. what changes have been made to your computer before the problem?

    Follow these steps and check if they help.

    Step 1:

    I would say you rebuild the icon cache and check if the problem persists.

    a. press the keyboard Windows logo key combination + R to bring up the Run dialog box.
    b. type cmd and press ENTER to open the command prompt window.
    c. in the command prompt window, type the following commands pressing ENTER after each line:
    Taskkill /f /im explorer.exe
    attrib-h "%userprofile%\Local Settings\Application Data\IconCache.db.
    del "%userprofile%\Local Settings\Application Data\IconCache.db.
    Explorer.exe

    d. this restart Windows Explorer and rebuild the cache icons as needed.

    Step 2:

    Test the issue in a new user account.

  • Photoshop Elements 8, how to show the value, the hue and saturation of a specific area of a pickture?

    Hello

    Photoshop Elements 8, how to show the value, the hue and saturation of a specific area of the image?

    How to choose the area? Which tool?

    Thank you in advance, Karl

    Make sure first that your range of information is visible: window menu / Info (shortcut F8)

    In this palette, click the small icon 'more '.

    Select "Palette Options".

    and choose HSB to second reading of palette.

  • Align the labels and the lovs in a proper order?

    Hello

    I have 3 panelgroupLayouts plg1 and plg2 plg3 with Halign:center and page layout: horizontal.
    Under each panelgroupLayout an output label and an af:selectOneChoice are here.
    Under plg1; label: empno
    Under plg2; label: employeeName
    Under plg1; label: empadd
    for this reason my lovs and labels are not aligned in the same line vertivally.

    How to organize these all labels and all the socs a vertical in order to make the look n feel neat?

    All suggestions will be really useful?

    Thank you.

    Then put the panelFormLayout inside the panelGroupLayout and set its halign "Center".
    Here is an example.

    
    
    
      
        
        
          
            
              
                
                
              
              
                
              
              
                
                
              
              
                
                
              
            
          
        
      
    
    
  • To access the controls and their values in different JFrames and forms

    Hi all - is it possible to access controls and their associated information? For example, in my old .NET application, I got a form where users could enter usernames/people with disabilities and also preferences for the launch of other external tools. The user filled in the text boxes and made a few selections on combo boxes etc. - I then recorded in an ini file which is loaded at run time. Then from anywhere in the application I could do something like:

    Dim strUserName As String = frmUserSettings.txtUserName.Text//for username
    Dim optLocalorRemote as String = frmUserSettings.cmbLocalorRemote.SelectedItem.ToString () //for selected item in the drop-down list box
    Dim optSomeOption as Object = frmSomeForm.SomeControl.Value //etc etc...

    You can call any control in any form and obtain its associated variables and also call any method belonging to him in .NET or void. Is it possible to do in the frameworks for Swing? I did some research but can't seem to find the equivalent in Swing

    If it is not possible can then someone point me in the right direction on how to do it? Do I need to define a class and I then have to instantiate each control in the class and have the getters/setters or y at - it an easier way? I essentially have an obligation to access related information across different forms in the application

    I found this:
    http://StackOverflow.com/questions/4958600/get-a-swing-component-by-name
    But this seems to return the control names and no values?

    Thanks in advance for any advice or help - we appreciate it! :)

    Hello Matt,

    for what you do with files .ini, java provides the java.util.Properties class.
    To access the other JFrames and forms (JPanels), you pass a reference to this framework/Panel to the place (class or method) where you want to retrieve information from this framework/Panel.
    Example:

    public class MyFrame extends JFrame {
      JPanel myPanel1= new JPanel(...);
    ...
      MyVeryOwnPanel mvop= new MyVeryOwnPanel(myPanel1,...);
    }
    

    Now within mvop, you can look at what happened to myPanel1.

    HTH

  • Copy and paste the position and size of two different objects

    Greetings,

    I have a question, quite a delicate. Is it possible how can I copy and paste the position and the size of two objects?

    Let's say I have a 2 circle y 5 cm x 5 cm x 2 cm and its position, I a square of size 3 x 7 cm and its position is y 0 x 0 cm.

    How can I copy and paste in one step of order / position of circles and the size squared, so I can get the square of 2 x 2 cm and 5 cm x 5 cm position?

    Something like copy + paste in place with a different logic. I hope you understand what I want.

    I now do it manually, I'm copy the size and position of one object to another [ctrl + c > ctrl + v] but it takes quiet a while,

    Thank you for your suggestions,

    concerning

    Bryan

    Which would probably need a script, then maybe ask in the respective subforum...

    Mylenium

  • How to align the product and the image of the product on the same line?

    ScreenHunter_217 Jan. 25 15.06.jpg

    I'm having a problem trying to make the image of the product and the title of the product to be on the same line. Can someone help me?

    To do this, right-click in this general area to 'inspect element' and change the display to "block" for the hidden liquid section. Who must disclose and thus allow you to activate and save.

    See screenshot below.

  • My computer (including the desktop and menu/task bar) screen are not the size of the screen of my computer?

    Somehow, I adjusted the size of my desk, bar of tasks and new windows that open. The windows are currently "maximized", but do not take to the top of my computer screen size. There is a black box around all the sides of my screen (including my desktop and the taskbar). How normal view again?

    Thank you

    Hello

    If a separate monitor (not a laptop), it will be setting of physical geometry on it then you can move all the
    the screen to the right and enlarge if necessary. Also right click an empty area of the desktop - graphic properties.
    Search for geometry settings (PCs and laptops).

    If a laptop computer Right Click a white office - properties Graphics - look at the horizontal settings.

    If necessary contact your system support manufacturer and check their documents and online forums. Do the
    even with the monitor manufacturer if different from the manufacturer of the system.

    Right click on desktop - customize - display settings

    =======================================

    You can also try a system back restore to before that you did.

    How to make a Vista system restore
    http://www.Vistax64.com/tutorials/76905-System-Restore-how.html
    I hope this helps.
    Rob - bicycle - Mark Twain said it is good.

  • Can I do compare material using hsdio during the generation and clock speed of CQI are different

    Hello

    my application needs to generate a digital stream to A clock frequency with width of bus (number of bits) very from 1 to 4 bits

    IAE response will always be on the bit but with a B clock frequency.

    1. can I use the advice hsdio hardware comparison mechanism.

    2 If the answer is YES, there is any sample that can help me to get started.

    Thanks in advance

    Daniel Gabel

    Hello

    Yes, you can compare material with different rates of acquisition and generation.  There are several examples that are provided with the NOR-HSDIO driver.  There are some examples of physical comparison you would like to check.

    Jon S

  • Search engine continues to change the logo of firefox with 'Search The Web' and takes me to different search engines, Bing or Google so far. I don't want to. It used to be always on the Google, and I want to again permanently on Google. Help?

    Just like the States mentioned above. This refers to the search bar on the right. I don't want to remove it, I like to use. I want to get back the Google value permanently. Even if I turn it on to Google in the drop-down menu, when I restart Firefox, it changes back. Once again, instead of any other logo of search engine, it has a small logo of Firefox, saying 'Web search' next to him in grey if no text is entered. He often gives Bing search results, even if I deleted Bing in search engines installed.

    I also checked the default search engine in topic: config, and despite what I describe above, the default value is still on Google.

    Why this is happening and how to fix it? It didn't happen until the other day here, so it would be after the update to Firefox 6.

    Go to your add-ons Manager and disable extensions test pilot.

    Fixed a problem. Someone should pay me now!

  • How do you align the buttons and text near the edge of a window of browser?

    In Muse.pngIn Browser.png

    The image to the left, it's what I'll do. However, unfortunately my output appears as you see on the right side.

    I am a new user of Adobe Muse, no matter which input you can provide would be greatly appreciated.

    Select your item you want pinned and use the tool of the handle.

  • Can multiple users access the account and use services on different computers?

    ?

    Hi vighter,

    A subscription is related to an individual Adobe ID and password. The license agreement allows this user to access the subscription on up to two devices, but not at the same time.

    Best,

    Sara

  • The markings and data to a different tablespace tables

    Hello

    Asked me to new tablespace tablespace of table1. I used the alter table move ts2 table_name1 and he successfully created. But the problem is that I need to transfer all the documents/data from table_name1 to his new assignment of tablespace. By the way in which we use the oracle 8i, but there is no RMAN features.

    Help, please.
    Thank you

    When the user command ALTER TABLE TableName MOVE move orders moves all records to new tablespace with DDL

    but you need tp rebuild indexes on the underlying table changes command MOVE do INDEX unusable, so you need to rebuild the INDEXES on the tables... You don't need to worry abt another thing

  • Open a window of normal (non-private) and the journal in a site. Open a private window and go to the site and it shows that you are connected. 11 IE does not work. Why FF?

    V32.0.2.

    It is certainly not my experience.

    Have you changed your configuration before you post? Your "more details of the system" seems to show that you have configured to automatically start in private browsing mode, you can select in the Firefox Options:

    "3-bar" menu button (or tools) > Options > privacy

    If the value is "Firefox will: don't remember history ' change the dropdown to" Firefox will be: use the custom settings for history "to reveal the current configuration.

    What is the box ticked for "always use the private browsing mode"?

    If Yes, then what you have found is logical: private windows share a pool of "session only" cookies separate Windows non-private, and you have all the non-private with automatic private browsing windows.

Maybe you are looking for