Hello. I am having a slight problem with layout in my program. The Textfield doesn't seem to be aligned with the Message Label.

The program is a GUI MPG calculator. It's supposed to calculate the car's mileage. It's supposed to let the user enter the number of gallons of gas that the car holds, and the number of miles it can be driven on a full tank.

When the calculate MPG button is clicked, the program displays the number of miles that the car may be driven per gallons of gas.

// Programming Challenge #9
// MPGCalculatorWindow.java
// Program designed by X
// Created on 03/30/2012

// This program displays the number of miles that the car may be driven per gallon of gas.

   import java.util.*;
   import javax.swing.*;              // Needed for JOptionPane.
   import java.text.DecimalFormat;  // Keeping proper decimal format.
   import java.awt.*;               // Needed for BorderLayout class.
   import java.awt.event.*;


   public class MPGCalculatorWindow extends JFrame
   {    
   private JPanel panel;                                            // A holding panel
   private JLabel messageLabel;                                 // A message to the user
   private JLabel messageLabel1;                                    // A message to the user
   private JTextField TextField;                                // To hold user input for gallons of gas
   private JTextField TextField1; 
   private JPanel ButtonPanel;                                  // To hold the buttons      
   private JButton calcButton;                                  // To calculate miles per gallon (MPG)
   private JButton exitButton;                                  // To exit the application
   private final int WINDOW_WIDTH = 500;                         // Window width
   private final int WINDOW_HEIGHT = 200;                       // Window height

/** 
Constructor
*/          

  public  MPGCalculatorWindow()
  {

  // Set the title bar text.
     setTitle("MPG Calculator");

  // Set the size of the window.
     setSize(WINDOW_WIDTH, WINDOW_HEIGHT);              

  // Create a BorderLayout manager to content pane.
     setLayout(new BorderLayout(13,15));     

  // Specify an action for the close button.
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  // Build the panel and add it to the frame.
     buildPanel();

  //Add the panel and add it to the frame.
     add(panel);

  // Display the window.
     setVisible(true);
  }
 /**
The buildButtonPanel method adds a label, textfield, and buttons to a pane
 */

  private void buildPanel()
  {
  // Create a panel for the buttons.
     ButtonPanel = new JPanel();

  // Create the label.    
     messageLabel = new JLabel("Enter number of miles " +
        "driven on a full tank:");

    // Create a text field.
     TextField = new JTextField(20);    

    // Create the label.
     messageLabel1 = new JLabel("Enter number of gallons of gas " + 
        "your car holds:");     

    //Create the text field.
     TextField1 = new JTextField(20);


  // Create the buttons with captions
     calcButton = new JButton("Calculate");
     exitButton = new JButton("Exit");

  //Register the action listeners to the buttons.
     calcButton.addActionListener(new CalcButtonListener());
     exitButton.addActionListener(new ExitButtonListener());

  // Add buttons to the button panel
     ButtonPanel.add(calcButton);
     ButtonPanel.add(exitButton);

  // Create a panel object and add let the panel reference to it.
     panel = new JPanel();

  // Add the label, textfield, and button components to the panel.
     panel.add(messageLabel);
     panel.add(messageLabel1);
     panel.add(TextField);
     panel.add(TextField1);
     panel.add(calcButton);
     panel.add(exitButton);
  }

/** Private inner class that handles the event when the user clicks any of the two buttons.
*/
  private class CalcButtonListener implements ActionListener
  {
  /**
  The actionPerformed method executes when the user clicks on the Calculate button.
  @param e the event object.
  */

     public void actionPerformed(ActionEvent e)
     {
        String input1;
        String input2;
        double total_miles;
        double gallons;
        double MPG;


        input1 = TextField.getText();
        input2 = TextField1.getText();
        total_miles = Double.parseDouble(input1);
        gallons = Double.parseDouble(input2);


     // Formula for finding the miles-per-gallon.

        MPG = total_miles/gallons;  

        // Create a DecimalFormat object.
        DecimalFormat formatter = new DecimalFormat("#00.00");


         // Display the calculation

        JOptionPane.showMessageDialog(null,"The total miles that your car may be driven per gallon of gas: " + 
           formatter.format(MPG));
     }

  }


/** Private inner class that handles the event when the user clicks the Exit button.

*/

  private class ExitButtonListener implements ActionListener
  {
     public void actionPerformed(ActionEvent e)
     {
        System.exit(0);

     }
  }

}

The code for the MPG class.

 // MPG.java
// Programming Challenge #9
// 3/31/2012
// Programmed by X


    /**
    This program is an instance of the MPGCalculatorWindow class
    which displays the GUI for MPGCalculatorWindow program.
    */

   public class MPG
   {
  public static void main(String[] args)
  {
     new MPGCalculatorWindow();

  }
}

Textfield doesn't seem to be aligned with the Message Label.

You should look into how to use layout managers. Your code appears to be using the default layout manager for the JPanel class. The are several choices of layout managers. Some times you need to creat a new panel to hold subparts of your GUI and then add that panel to the panel that is added to the frame. Each of the panels can have their own layout manager.

Comments
+1 nestedlayout

I still don't understand after studying the text and your statement. Thanks anyway.

Create a new panel to hold the label and the text field.
add the label and text field to this new panel
add the new panel to the "panel" variable.
Don't add the label and text field to "panle"

The name: panel for a variable makes it confusing to talk about panels. I put the name in "s to show it was a name and not a class

This article has been dead for over six months. Start a new discussion instead.