Results 1 to 18 of 18
  1. #1
    geekchick is offline Member
    Join Date
    Aug 2010
    Posts
    25
    Rep Power
    0

    Default How to add panel to JFrame?

    Hello,

    I have several classes. One called Buttons, Customer and a Main method. Customer inherits Buttons. In the main method im creating Tabbed Panes, which are showing up, but my panels from my other classes are not visible. Any suggestions?

    Java Code:
    public class Buttons extends JPanel
    {
    	JPanel panel = new JPanel();
    	JFrame frame = new JFrame();
    	private JButton addButton;
    	private JButton modifyButton;
    	private JButton deleteButton;
    	
    	public Buttons()
    	{  
    		super();
    		addButton = new JButton("Add");
    		modifyButton = new JButton("Modify");
    		deleteButton = new JButton("Delete");
    		
    		panel.setLayout(new FlowLayout());
    		panel.add(addButton);
    		panel.add(modifyButton);
    		panel.add(deleteButton);
    		frame.add(panel);
    	}
    
    public Customer()
    	{
    		// Instantiate labels
    		label1 = new JLabel("First Name");
    		label2 = new JLabel("Last Name");
    		label3 = new JLabel("Customer Status");
    		label4 = new JLabel("Dependendt Age");
    		label5 = new JLabel("Customer ID");
    		
    		// Instantiate text boxes
    		text1 = new JTextField(10);
    		text2 = new JTextField(10);
    		
    		// Set the Grid Layout
    		setLayout( new GridLayout(5,2));
    		
    		// Add items to grid
    		panel.add(label1);
    		panel.add(text1);
    	}


    Java Code:
    public class AirlineReservationDemo {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) 
    	{
    		Customer cust = new Customer();
    		JTabbedPane tab = new JTabbedPane();
    		JFrame frame = new JFrame("Airline");
    		tab.add("Customer", cust);
    		tab.add("Flight", null);
    		tab.add("Reservations", null);
    		frame.add(tab, BorderLayout.CENTER);
    		frame.setSize(800,500);
    		frame.setVisible(true);
    	}
    
    }
    Last edited by Fubarable; 08-01-2010 at 06:38 AM.

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

    Default

    On quick inspection, your code won't even compile as the Buttons class appears to have two constructors, one called Buttons and one called Customer.

    I think that you'll need to fix your compile errors before asking logic questions.

    And what is Buttons doing with a JFrame field? What purpose does it serve? Can you explain your logic behind the choices you've made when creating these classes?

  3. #3
    geekchick is offline Member
    Join Date
    Aug 2010
    Posts
    25
    Rep Power
    0

    Default

    Sorry, the Customer class should be:

    public class Customer extends Buttons
    {
    JPanel panel = new JPanel();
    // Declare JLabels
    private JLabel label1;
    private JLabel label2;
    private JLabel label3;
    private JLabel label4;
    private JLabel label5;

    // Declare JTextFields
    private JTextField text1;
    private JTextField text2;
    private JTextField text3;
    private JTextField text4;
    private JTextField text5;
    private JTextField text6;


    public Customer()
    {
    // Instantiate labels
    label1 = new JLabel("First Name");
    label2 = new JLabel("Last Name");
    label3 = new JLabel("Customer Status");
    label4 = new JLabel("Dependendt Age");
    label5 = new JLabel("Customer ID");

    // Instantiate text boxes
    text1 = new JTextField(10);
    text2 = new JTextField(10);

    // Set the Grid Layout
    setLayout( new GridLayout(5,2));

    // Add items to grid
    panel.add(label1);
    panel.add(text1);
    }

    //setLayout();
    }

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

    Default

    I'm not sure why the Customer class extends the Button class. If it is so that you can have a JPanel that has both the JButtons from Buttons and the JTextFields and JLabels from Customer combined, then do don't this way as this is not what inheritance is for, and if you try to do it this way, your program will break. Instead, have Buttons extend JPanel and have Customer do the same, and then use the one JPanel in the other class. In otherwords, extend your program through composition (one class containing another class's objects), and not inheritance.

    Your other problem is that I don't see you ever adding components to the JPanel represented by the class itself. You must do this if you are going to use the class as a JPanel. Instead you seem to be adding your components to a JPanel variable called panel, but this panel is never added to anything else much less a Container that eventually is displayed in a top level container such as a JFrame.

    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 [code] above your pasted code and the tag [/code] below your pasted code like so:

    Java Code:
    [code]
      // your code goes here
      // notice how the top and bottom tags are different
    [/code]
    I edited your first post and added the code tags, now I suggest that you do the same with your last post.

    Much luck!

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

    Default

    For example, a totally worthless GUI example that combines JButtens, JLabels, and JTextFields in one big megillah:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.swing.*;
    
    public class FuSwing1 {
       private static void createAndShowUI() {
          FuSwMainGuiPanel mainGuiPanel = new FuSwMainGuiPanel();
    
          // create the JFrame
          JFrame frame = new JFrame("Fu Swing1");
          
          // and place the main GUI Panel into its contentPane
          frame.getContentPane().add(mainGuiPanel);
          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();
             }
          });
       }
    }
    
    class FuSwMainGuiPanel extends JPanel {
       public FuSwMainGuiPanel() {
          setLayout(new BorderLayout(10, 10));
          int ebGap = 18;
          setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
          
          // here we combine both JPanels into one JPanel using BorderLayout
          add(new OtherFields(), BorderLayout.CENTER);
          add(new Buttons(), BorderLayout.SOUTH);
       }
       
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D)g;
          g2.setPaint(new GradientPaint(0, 0, new Color(70, 70, 255), 
                   getWidth(), getHeight(), new Color(0, 0, 20)));
          g2.fillRect(0, 0, getWidth(), getHeight());
       }
    }
    
    /*
     * Contains several buttons in a linear grid
     */
    class Buttons extends JPanel {
       public static final String[] BTN_NAMES = {"Mon", "Tues", "Wed", "Thurs"};
    
       public Buttons() {
          setOpaque(false);
          setLayout(new GridLayout(1, 0, 15, 0));
          for (String btnName : BTN_NAMES) {
             JButton btn = new JButton(btnName);
             btn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                   btnActionPerformed(e);
                }
             });
             add(btn);
          }
       }
    
       private void btnActionPerformed(ActionEvent e) {
          // TODO finish method
          
       }
    }
    
    /*
     * Contains JLabels and JFields in a tabular structure
     */
    class OtherFields extends JPanel {
       public static final String[] LABEL_NAMES = {"Jan", "Feb", "Mar", "Apr"};
       private Map<String, JTextField> fieldMap = new HashMap<String, JTextField>();
    
       public OtherFields() {
          setOpaque(false);
          setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(),
                   BorderFactory.createEmptyBorder(9, 9, 9, 9)));
          setLayout(new GridBagLayout());
          for (int i = 0; i < LABEL_NAMES.length; i++) {
             addLabelField(i, LABEL_NAMES[i]);
          }
       }
       
       public String getFieldText(String labelName) {
          JTextField field = fieldMap.get(labelName);
          if (field == null) {
             return null;
          } else {
             return field.getText();
          }
       }
    
       private void addLabelField(int i, String labelName) {
          JTextField field = new JTextField(10);
          fieldMap.put(labelName, field);
          
          JLabel label = new JLabel(labelName);
          label.setForeground(Color.lightGray);
          label.setFont(label.getFont().deriveFont(Font.BOLD, 24));
          GridBagConstraints gbc = new GridBagConstraints(0, i, 1, 1, 0.05, 1.0,
                   GridBagConstraints.WEST, GridBagConstraints.BOTH, 
                   new Insets(5, 0, 5, 25), 0, 0);
          add(label, gbc);
          
          gbc = new GridBagConstraints(1, i, 1, 1, 1.0, 1.0,
                   GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, 
                   new Insets(5, 5, 5, 0), 0, 0);
          add(field, gbc);
    
       }
    }

  6. #6
    geekchick is offline Member
    Join Date
    Aug 2010
    Posts
    25
    Rep Power
    0

    Default

    I created a Button class so my other pages could inherit it, as I have 2 other classes (pages) that need the same functionality with only the Add, Modify and Delete Buttons

  7. #7
    geekchick is offline Member
    Join Date
    Aug 2010
    Posts
    25
    Rep Power
    0

    Default

    Also, do i need to add my JPanel to the JFrame in Main? Or does that need to be done in each class? I'm baffeled as to why none of my components are not showing up.

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

    Default

    Quote Originally Posted by geekchick View Post
    I created a Button class so my other pages could inherit it, as I have 2 other classes (pages) that need the same functionality with only the Add, Modify and Delete Buttons
    But again, this is not what inheritance is for. Sure create a Button class with this functionality, but rather than have the other GUI's inherit it, give them instance of it and let them use these instances for the functionality. For example in my code above, I create a Buttons class that holds JButtons and an OtherFields class that holds JLabels and JTextFields, and then in the main GUI, I place instances of these classes into the main GUI:
    Java Code:
    class FuSwMainGuiPanel extends JPanel {
       public FuSwMainGuiPanel() {
          setLayout(new BorderLayout(10, 10));
          int ebGap = 18;
          setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
          
          //  *** here we combine both JPanels into one JPanel using BorderLayout
          add(new OtherFields(), BorderLayout.CENTER);
          add(new Buttons(), BorderLayout.SOUTH);
       }

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

    Default

    Quote Originally Posted by geekchick View Post
    Also, do i need to add my JPanel to the JFrame in Main? Or does that need to be done in each class? I'm baffeled as to why none of my components are not showing up.
    Here in your main method, you're adding an instance of the Customer class to a JTabbedPane and then adding that JTabbedPane to the JFrame:

    Java Code:
    	public static void main(String[] args) 
    	{
    		Customer cust = new Customer();           // create Customer instance
    		JTabbedPane tab = new JTabbedPane();
    		JFrame frame = new JFrame("Airline");
    		tab.add("Customer", cust);                    // add Customer instance to JTabbedPane
    		tab.add("Flight", null);
    		tab.add("Reservations", null);
    		frame.add(tab, BorderLayout.CENTER);    // add the JTabbedPane to the JFrame
    So therefore your components must be somehow added to the Customer JPanel itself. It's fine to add them to a JPanel called panel from within Customer if you eventually add that JPanel to customer via:

    Java Code:
    public Customer()
    {
       // Instantiate labels
       label1 = new JLabel("First Name");
       label2 = new JLabel("Last Name");
       label3 = new JLabel("Customer Status");
       label4 = new JLabel("Dependendt Age");
       label5 = new JLabel("Customer ID");
       
       // Instantiate text boxes
       text1 = new JTextField(10);
       text2 = new JTextField(10);
    
       // Set the Grid Layout
       setLayout( new GridLayout(5,2));
       
       // Add items to grid
       panel.add(label1);
       panel.add(text1);
    
       add(panel);  // ****** here ***** add panel to Customer
    }
    You'll also need to take layouts into consideration here, but that's another whole chapter.
    Last edited by Fubarable; 08-01-2010 at 03:43 PM.

  10. #10
    geekchick is offline Member
    Join Date
    Aug 2010
    Posts
    25
    Rep Power
    0

    Default

    Thanks you! That worked. I will post my code, in case someone else is having a similiar issue

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

  12. #12
    geekchick is offline Member
    Join Date
    Aug 2010
    Posts
    25
    Rep Power
    0

    Default

    Java Code:
    public class Buttons extends JPanel
    {
    	JPanel panel = new JPanel();
    	JFrame frame = new JFrame();
    	private JButton addButton;
    	private JButton modifyButton;
    	private JButton deleteButton;
    	
    	public Buttons()
    	{  
    		super();
    		addButton = new JButton("Add");
    		modifyButton = new JButton("Modify");
    		deleteButton = new JButton("Delete");
    		
    		panel.setLayout(new FlowLayout());
    		panel.add(addButton);
    		panel.add(modifyButton);
    		panel.add(deleteButton);
    		add(panel);
    	}
    
    	
    	
    }
    Java Code:
    public class CustomerInformation extends JPanel
    {
    	JPanel panel = new JPanel();
    	// Declare JLabels
    	private JLabel label1;
    	private JLabel label2;
    	private JLabel label3;
    	private JLabel label4;
    	private JLabel label5;
    	
    	// Declare JTextFields
    	private JTextField text1;
    	private JTextField text2;
    	private JTextField text3;
    	private JTextField text4;
    	private JTextField text5;
    	private JTextField text6;
    	
    
    	public CustomerInformation()
    	{
    		// Instantiate labels
    		label1 = new JLabel("First Name");
    		label2 = new JLabel("Last Name");
    		label3 = new JLabel("Customer Status");
    		label4 = new JLabel("Dependendt Age");
    		label5 = new JLabel("Customer ID");
    		
    		// Instantiate text boxes
    		text1 = new JTextField(10);
    		text2 = new JTextField(10);
    		text3 = new JTextField(10);
    		text4 = new JTextField(10);
    		text5 = new JTextField(10);
    		
    		// Set the Grid Layout
    		panel.setLayout( new GridLayout(5, 2));
    		
    		// Add items to grid
    		panel.add(label1);
    		panel.add(text1);
    		panel.add(label2);
    		panel.add(text2);
    		panel.add(label3);
    		panel.add(text3);
    		panel.add(label4);
    		panel.add(text4);
    		panel.add(label5);
    		panel.add(text5);
    		
    		
    		add(panel);
    	}
    	
    	
    }
    Java Code:
    public class Customer extends JPanel
    {
    	JPanel panel = new JPanel();
    	
    	public Customer()
    	{
    		
    		panel.setLayout(new BorderLayout());
    		panel.add(new Buttons(), BorderLayout.NORTH);
    		panel.add(new CustomerInformation(), BorderLayout.CENTER);
    		
    		add(panel);
    		
    	}
    }

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

    Default

    Note that in many of your classes, you can get rid of the JPanel panel variable and just add components directly to your class's JPanel (like you do at the end when you add(panel)).

  14. #14
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default

    I would recommend that it would be very useful for you to examine Fubarable's example. It very good for understanding how to work with frames, panel, button, label, textfields, maps, layouts.

    Let's simplify that example:
    We have public class FuSwing1.
    In that class we have function: private static void createAndShowUI().
    So in that function we are calling object that is panel, and we are setting frame, and adding that panel to frame.

    Java Code:
    // and place the main GUI Panel into its contentPane
          frame.getContentPane().add(mainGuiPanel);
    NOTE: when you are adding panel to frame, don't use something like: frame.add(panel); It is better to use getContentPane() because you don't adding panel to frame directly but to it's contentpane.

    In function we are calling object that is panel. But where is that object created? It is created in class FuSwMainGuiPanel extends JPanel.
    In FuSwMainGuiPanel's constructor we are adding two panels Buttons and OtherFields.

    Conclusion:
    So we have situation that in the public class FuSwing1 we defined function for showing graphic user interface. In that function we have frame. Panel defined with class FuSwMainGuiPanel is added to this frame. But FuSwMainGuiPanel also has two panels added to it. That two panels are Buttons and OtherFields.

    Question for Fubarable: In Buttons constructor, and in OtherFields constructor you have "setOpaque(false);". For what "setOpaque(false);" is used? I am asking you because I don't know usage of that :(

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

    Default

    Question for Fubarable: In Buttons constructor, and in OtherFields constructor you have "setOpaque(false);". For what "setOpaque(false);" is used? I am asking you because I don't know usage of that
    This was totally unnecessary for the example, so my apologies for putting it in. I was trying to "pretty-up" a pretty boring and simple GUI example by giving it a background blue gradient. Since the background was painted on the main JPanel, and since JPanels are by default opaque, I made the subpanels non-opaque so that this background could show through, that's all.

    But I regret doing it as it only muddies the main issue here: how to add components to containers and how to use layouts.

  16. #16
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default

    In class CustomerInformation try to use arrays of components. It will save you some time and program would be readable.

    for example change:
    Java Code:
    private JTextField text1;
    	private JTextField text2;
    	private JTextField text3;
    	private JTextField text4;
    	private JTextField text5;
    	private JTextField text6;
    with:
    Java Code:
    private JTextField[] texts = new JTextField[6];
    this:
    Java Code:
    text1 = new JTextField(10);
    		text2 = new JTextField(10);
    		text3 = new JTextField(10);
    		text4 = new JTextField(10);
    		text5 = new JTextField(10);
    with:
    Java Code:
    for(int i = 0; i < texts.length; i++)
    			texts[i]=new JTextField(10);
    and so on. :cool:

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

    Default

    Quote Originally Posted by cselic View Post
    In class CustomerInformation try to use arrays of components. It will save you some time and program would be readable.
    Yep, or a Map or other Collection. I sort of prefer the Map/HashMap since it maps the JTextField to its corresponding JLabel text. This will of course break if two JLabels are named the same. :(

  18. #18
    cselic is offline Senior Member
    Join Date
    Apr 2010
    Location
    Belgrade, Serbia
    Posts
    278
    Rep Power
    5

    Default

    But I regret doing it as it only muddies the main issue here: how to add components to containers and how to use layouts.
    No, no, no. I have nothing against using setOpaque().
    I have asked you that because I have seen that maybe 10-20 times in programs and I really don't now what is usage of that.
    I asked you to learn that not to criticize.

Similar Threads

  1. Replies: 5
    Last Post: 06-14-2010, 06:10 PM
  2. Replies: 6
    Last Post: 04-12-2010, 11:33 AM
  3. Adding a panel to a panel
    By rclausing in forum New To Java
    Replies: 7
    Last Post: 02-02-2010, 05:56 AM
  4. Passing data from one JFrame to another JFrame
    By tarami in forum New To Java
    Replies: 3
    Last Post: 08-06-2009, 05:44 PM
  5. Replies: 4
    Last Post: 04-22-2009, 11:02 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
  •