[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 6866
  • Last Modified:

Adding JPanel into JFrame

Hi!

I need to put some instructional label on top and three buttons at the bottom. I was thinking creating Jpanels for them and inserting into Jframe, but it doesn’t seems to work and the format is messed up. Can some one show me better ways of doing it?

Thanks,
++++++++++
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MyJTextField {
    public static void main(String[] args) {
      JLabel l;
      JButton b;
      final JFrame f = new JFrame("MyJTextField.java Example");
      Container cp = f.getContentPane();
      // Make some 35 column wide text fields
      JTextField nameField = new JTextField(35);
      JTextField streetField = new JTextField(35);
      JTextField cityField = new JTextField(35);
      JTextField countyField = new JTextField(35);
      JTextField zipField = new JTextField(35);
      JTextField phoneField = new JTextField(35);
      //  Now place them in the panl
      cp.setLayout(new GridBagLayout());
      cp.setBackground(UIManager.getColor("control"));
      GridBagConstraints c = new GridBagConstraints();
      
      c.gridx = 0;
      c.gridy = GridBagConstraints.RELATIVE;
      c.gridwidth = 1;
      c.gridheight = 1;
      c.insets = new Insets(2, 2, 2, 2);
      c.anchor = GridBagConstraints.EAST;

      // labels for the text fields
      cp.add(l = new JLabel("Name:", SwingConstants.RIGHT), c);
      cp.add(l = new JLabel("House/Street:", SwingConstants.RIGHT), c);
      cp.add(l = new JLabel("City:", SwingConstants.RIGHT), c);
      cp.add(l = new JLabel("State/County:", SwingConstants.RIGHT), c);
      cp.add(l = new JLabel("Zip/Post code:", SwingConstants.RIGHT), c);
      cp.add(l = new JLabel("Telephone:", SwingConstants.RIGHT), c);
      
      c.gridx = 1;
      c.gridy = 0;
      c.weightx = 1.0;
//       c.weighty = 1.0;
       c.fill = GridBagConstraints.HORIZONTAL;
//       c.fill = GridBagConstraints.BOTH;
      c.anchor = GridBagConstraints.CENTER;
      
      cp.add(nameField, c);
      c.gridx = 1;
      c.gridy = GridBagConstraints.RELATIVE;
      cp.add(streetField, c);
      cp.add(cityField, c);
      cp.add(countyField, c);
      cp.add(zipField, c);
      cp.add(phoneField, c);
      c.weightx = 0.0;
      c.fill = GridBagConstraints.NONE;
      
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Runnable showFrame = new Runnable() {
            public void run() {
                f.pack();
                f.setVisible(true);
            }
          };
      SwingUtilities.invokeLater(showFrame);

    }
}
++++++++++++
0
dkim18
Asked:
dkim18
2 Solutions
 
Dejan PažinCommented:
What you have to do is (i belive that is what you want to do):

1. Make two new JPanels
2. Add buttons to one of them, and labels to the other
3. All the stuff that you have now should be added to a third JPanel
4. The three panels should then be added to Container of JFrame. One to the south, north, and cetner

Here is your code, modified, to show you how to do it:


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MyJTextField
{
  public static void main(String[] args)
  {
    JLabel l;
    JButton b;
    final JFrame f = new JFrame("MyJTextField.java Example");
    Container container = f.getContentPane();

    /// Example Code :: Adding panels with buttons  and instructional labels:
    // Create two panels, and add labels and buttons to them
    // Both panels have simple FlowLayout layout set
    JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
    JPanel instructionsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));

    JLabel instructionLabel1 = new JLabel("Instructions: ");
    JLabel instructionLabel2 = new JLabel(" Learn about Layouts!");
    JButton button1 = new JButton("Button 1");
    JButton button2 = new JButton("Button 2");
    JButton button3 = new JButton("Button 3");

    buttonsPanel.add(button1);
    buttonsPanel.add(button2);
    buttonsPanel.add(button3);
    instructionsPanel.add(instructionLabel1);
    instructionsPanel.add(instructionLabel2);


    /// All the fields that you previously added to JFrame directly, are now added to
    // a separate panel:
    JPanel cp = new JPanel();

    // Make some 35 column wide text fields
    JTextField nameField = new JTextField(35);
    JTextField streetField = new JTextField(35);
    JTextField cityField = new JTextField(35);
    JTextField countyField = new JTextField(35);
    JTextField zipField = new JTextField(35);
    JTextField phoneField = new JTextField(35);
    //  Now place them in the panl
    cp.setLayout(new GridBagLayout());
    cp.setBackground(UIManager.getColor("control"));
    GridBagConstraints c = new GridBagConstraints();

    c.gridx = 0;
    c.gridy = GridBagConstraints.RELATIVE;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.insets = new Insets(2, 2, 2, 2);
    c.anchor = GridBagConstraints.EAST;

    // labels for the text fields
    cp.add(l = new JLabel("Name:", SwingConstants.RIGHT), c);
    cp.add(l = new JLabel("House/Street:", SwingConstants.RIGHT), c);
    cp.add(l = new JLabel("City:", SwingConstants.RIGHT), c);
    cp.add(l = new JLabel("State/County:", SwingConstants.RIGHT), c);
    cp.add(l = new JLabel("Zip/Post code:", SwingConstants.RIGHT), c);
    cp.add(l = new JLabel("Telephone:", SwingConstants.RIGHT), c);

    c.gridx = 1;
    c.gridy = 0;
    c.weightx = 1.0;
//      c.weighty = 1.0;
    c.fill = GridBagConstraints.HORIZONTAL;
//      c.fill = GridBagConstraints.BOTH;
    c.anchor = GridBagConstraints.CENTER;

    cp.add(nameField, c);
    c.gridx = 1;
    c.gridy = GridBagConstraints.RELATIVE;
    cp.add(streetField, c);
    cp.add(cityField, c);
    cp.add(countyField, c);
    cp.add(zipField, c);
    cp.add(phoneField, c);
    c.weightx = 0.0;
    c.fill = GridBagConstraints.NONE;


    // Add all three panels to the container

    container.setLayout(new BorderLayout());
    container.add(instructionsPanel, BorderLayout.NORTH);
    container.add(cp, BorderLayout.CENTER);
    container.add(buttonsPanel, BorderLayout.SOUTH);


    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Runnable showFrame = new Runnable()
    {
      public void run()
      {
        f.pack();
        f.setVisible(true);
      }
    };
    SwingUtilities.invokeLater(showFrame);

  }
}




0
 
delphi3Commented:
Hi dkim18,
This is only a FYI. A show of another possible solution.

I have JBuilder X Foundation (a free download from Borland) that has a designer included. I gave it a try on your problem.  I think that the other solution by dejanpazin  given above would fit your needs however.

Delphi3


package mjtfdesignerdemo;

import javax.swing.UIManager;
import java.awt.*;


public class MJTFDesignerDemo {
  boolean packFrame = false;

  //Construct the application
  public MJTFDesignerDemo() {
    MJTFDesignerDemoFrame frame = new MJTFDesignerDemoFrame();
    //Validate frames that have preset sizes
    //Pack frames that have useful preferred size info, e.g. from their layout
    if (packFrame) {
      frame.pack();
    }
    else {
      frame.validate();
    }
    //Center the window
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize = frame.getSize();
    if (frameSize.height > screenSize.height) {
      frameSize.height = screenSize.height;
    }
    if (frameSize.width > screenSize.width) {
      frameSize.width = screenSize.width;
    }
    frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height -
frameSize.height) / 2);
    frame.setVisible(true);
  }
  //Main method
  public static void main(String[] args) {
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    }
    catch(Exception e) {
      e.printStackTrace();
    }
    new MJTFDesignerDemo();
  }
}
 
package mjtfdesignerdemo;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class MJTFDesignerDemoFrame
    extends JFrame {


  JPanel contentPane;
  JPanel jpnlTitle = new JPanel();
  JLabel jlblDirectoryInfo = new JLabel();
  TitledBorder titledBorder1;
  TitledBorder titledBorder2;
  JPanel jpnlPersonalInfo = new JPanel();
  JLabel jlblName = new JLabel();
  TitledBorder titledBorder3;
  TitledBorder titledBorder4;
  JTextField jtfname = new JTextField();
  JPanel jpnlButtons = new JPanel();
  TitledBorder titledBorder5;
  TitledBorder titledBorder6;
  JLabel jlblstreet = new JLabel();
  JLabel jlblcity = new JLabel();
  JLabel jlblstate = new JLabel();
  JLabel jLabel4 = new JLabel();
  JLabel jLabel5 = new JLabel();
  JTextField jtfhouse = new JTextField();
  JTextField jtfcity = new JTextField();
  JTextField jtfstate = new JTextField();
  JTextField jtfzip = new JTextField();
  JTextField jtftelephone = new JTextField();
  JButton jbtnOpen = new JButton();
  JButton jbtnClear = new JButton();
  JButton jbtnClose = new JButton();

  //Construct the frame
  public MJTFDesignerDemoFrame() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
      jbInit();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  //Component initialization
  private void jbInit() throws Exception {
    jLabel5.setFont(new java.awt.Font("SansSerif", 1, 12));
    jLabel5.setText("Telephone:");
    jLabel5.setBounds(new Rectangle(10, 151, 83, 18));
    jtfhouse.setText("");
    jtfhouse.setBounds(new Rectangle(108, 34, 239, 21));
    jtfcity.setText("");
    jtfcity.setBounds(new Rectangle(109, 60, 239, 24));
    jtfstate.setText("");
    jtfstate.setBounds(new Rectangle(108, 90, 240, 22));
    jtfzip.setText("");
    jtfzip.setBounds(new Rectangle(106, 119, 243, 21));
    jtftelephone.setText("");
    jtftelephone.setBounds(new Rectangle(105, 148, 245, 24));
    jlblcity.setFont(new java.awt.Font("SansSerif", 1, 12));
    jlblcity.setForeground(Color.blue);
    jlblstreet.setFont(new java.awt.Font("SansSerif", 1, 12));
    jlblstate.setFont(new java.awt.Font("SansSerif", 1, 13));
    jLabel4.setFont(new java.awt.Font("SansSerif", 1, 12));
    jLabel4.setForeground(Color.blue);
    contentPane = (JPanel)this.getContentPane();
    titledBorder1 = new TitledBorder("");
    titledBorder2 = new TitledBorder("");
    titledBorder3 = new TitledBorder("");
    titledBorder4 = new TitledBorder("");
    titledBorder5 = new TitledBorder("");
    titledBorder6 = new TitledBorder("");
    contentPane.setLayout(null);
    this.setSize(new Dimension(400, 340));
    this.setTitle("Client Data");
    jpnlTitle.setBorder(titledBorder2);
    jpnlTitle.setBounds(new Rectangle(17, 8, 358, 45));
    jpnlTitle.setLayout(null);
    jlblDirectoryInfo.setFont(new java.awt.Font("SansSerif", 1, 16));
    jlblDirectoryInfo.setForeground(Color.blue);
    jlblDirectoryInfo.setText("Personal Data Directory");
    jlblDirectoryInfo.setBounds(new Rectangle(80, 6, 192, 33));
    jpnlPersonalInfo.setBorder(titledBorder4);
    jpnlPersonalInfo.setBounds(new Rectangle(16, 60, 361, 179));
    jpnlPersonalInfo.setLayout(null);
    jlblName.setFont(new java.awt.Font("SansSerif", 1, 12));
    jlblName.setForeground(Color.blue);
    jlblName.setText("Name:");
    jlblName.setBounds(new Rectangle(12, 7, 54, 18));
    jtfname.setMinimumSize(new Dimension(6, 35));
    jtfname.setText("");
    jtfname.setBounds(new Rectangle(108, 10, 240, 21));
    jpnlButtons.setBorder(titledBorder6);
    jpnlButtons.setBounds(new Rectangle(17, 247, 360, 45));
    jpnlButtons.setLayout(null);
    jlblstreet.setText("House/Street:");
    jlblstreet.setBounds(new Rectangle(10, 40, 86, 18));
    jlblcity.setText("City:");
    jlblcity.setBounds(new Rectangle(10, 68, 90, 18));
    jlblstate.setText("State/County:");
    jlblstate.setBounds(new Rectangle(11, 96, 103, 18));
    jLabel4.setText("Zip/Post code:");
    jLabel4.setBounds(new Rectangle(10, 123, 87, 18));
    jbtnOpen.setBounds(new Rectangle(12, 10, 99, 27));
    jbtnOpen.setText("OpenFile");
    jbtnOpen.addActionListener(new MJTFDesignerDemoFrame_jbtnOpen_actionAdapter(this));
    jbtnClear.setBounds(new Rectangle(115, 10, 117, 27));
    jbtnClear.setText("ClearRecord");
    jbtnClear.addActionListener(new MJTFDesignerDemoFrame_jbtnClear_actionAdapter(this));
    jbtnClose.setBounds(new Rectangle(240, 9, 111, 27));
    jbtnClose.setText("Close");
    jbtnClose.addActionListener(new MJTFDesignerDemoFrame_jbtnClose_actionAdapter(this));
    contentPane.add(jpnlButtons, null);
    jpnlButtons.add(jbtnOpen, null);
    jpnlButtons.add(jbtnClear, null);
    jpnlButtons.add(jbtnClose, null);
    contentPane.add(jpnlTitle, null);
    jpnlTitle.add(jlblDirectoryInfo, null);
    contentPane.add(jpnlPersonalInfo, null);
    jpnlPersonalInfo.add(jlblName, null);
    jpnlPersonalInfo.add(jlblstate, null);
    jpnlPersonalInfo.add(jlblcity, null);
    jpnlPersonalInfo.add(jLabel4, null);
    jpnlPersonalInfo.add(jLabel5, null);
    jpnlPersonalInfo.add(jlblstreet, null);
    jpnlPersonalInfo.add(jtfname, null);
    jpnlPersonalInfo.add(jtfhouse, null);
    jpnlPersonalInfo.add(jtfcity, null);
    jpnlPersonalInfo.add(jtfstate, null);
    jpnlPersonalInfo.add(jtfzip, null);
    jpnlPersonalInfo.add(jtftelephone, null);
  }

  //Overridden so we can exit when window is closed
  protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
      System.exit(0);
    }
  }
  void jbtnOpen_actionPerformed(ActionEvent e) {

  }

  void jbtnnewdata_actionPerformed(ActionEvent e) {
 // Insert Open File Action Event Here
  }

  void jbtnClear_actionPerformed(ActionEvent e) {
// Insert Clear Data Action Event Here
  }

  void jbtnClose_actionPerformed(ActionEvent e) {
// Insert Close File Action Event Here
    System.exit(0);
  }



} // end of public class

class MJTFDesignerDemoFrame_jbtnOpen_actionAdapter implements java.awt.event.ActionListener {
  MJTFDesignerDemoFrame adaptee;

  MJTFDesignerDemoFrame_jbtnOpen_actionAdapter(MJTFDesignerDemoFrame adaptee) {
    this.adaptee = adaptee;
  }
  public void actionPerformed(ActionEvent e) {
    adaptee.jbtnOpen_actionPerformed(e);
  }
}

class MJTFDesignerDemoFrame_jbtnClose_actionAdapter implements java.awt.event.ActionListener {
  MJTFDesignerDemoFrame adaptee;

  MJTFDesignerDemoFrame_jbtnClose_actionAdapter(MJTFDesignerDemoFrame adaptee) {
    this.adaptee = adaptee;
  }
  public void actionPerformed(ActionEvent e) {
    adaptee.jbtnClose_actionPerformed(e);
  }
}

class MJTFDesignerDemoFrame_jbtnClear_actionAdapter implements java.awt.event.ActionListener {
  MJTFDesignerDemoFrame adaptee;

  MJTFDesignerDemoFrame_jbtnClear_actionAdapter(MJTFDesignerDemoFrame adaptee) {
    this.adaptee = adaptee;
  }
  public void actionPerformed(ActionEvent e) {
    adaptee.jbtnClear_actionPerformed(e);
  }
}




0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now