bananaman
bananaman

Reputation: 9

JPanel doesn't add button and text field

I don't understand why the panel.add(txtnum1) and panel.add(button2) doesn't show up when I compile the program. The panel.add(button) works just fine, my compiler doesn't throw any warning or errors, did I miss something?

package gui;

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

public class GUI {
 public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(new Dimension(300, 500));
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();
    panel.setBackground(Color.GRAY);
    frame.getContentPane().add(panel);
    JButton button = new JButton("Submit");
    panel.add(button);

    JTextField txtnum1 = new JTextField();
    txtnum1.setPreferredSize(new Dimension(30, 50));
    panel.add(txtnum1);

    JButton button2 = new JButton("Clear");
    panel.add(button2);
 }

}

Upvotes: 0

Views: 1537

Answers (2)

Valy
Valy

Reputation: 583

When implementing GUI applications with Swing, I like to have this approach in the code that builds the JFrame (we assume a simple GUI that does not have JPanel containers inside JPanel containers and stuff like that):

  1. Create JFrame and initialize it
  2. Create JPanel
  3. Create GUI components for that panel and add them
  4. Add panel to the JFrame (repeat from 2) for every JPanel inside the JFrame)
  5. Make the JFrame visible on the screen

So, your code would look something like this:

package gui;

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

public class GUI {
 public static void main(String[] args) {
    /* step 1 */
    JFrame frame = new JFrame();
    frame.setSize(new Dimension(300, 500));
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    /* step 2 */
    JPanel panel = new JPanel();
    panel.setBackground(Color.GRAY);

    /* step 3 */
    JButton button = new JButton("Submit");
    panel.add(button);

    JTextField txtnum1 = new JTextField();
    txtnum1.setPreferredSize(new Dimension(30, 50));
    panel.add(txtnum1);

    JButton button2 = new JButton("Clear");
    panel.add(button2);

    /* step 4 */
    frame.getContentPane().add(panel);
    /* step 5 */
    frame.setVisible(true);
 }

}

Tested and it works in Eclipse.

Upvotes: 2

san A
san A

Reputation: 177

You should call setVisible(true) at the end, after all components have been added.

Put frame.setVisible(true); at the end and it will work as expected.

Upvotes: 0

Related Questions