简体   繁体   中英

My JPanel won't show up (Java)

I don't understand why my JPanel won't show up since I used pack() and setVisible(true) It just run the application and nothing happens. This is my code

import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

import javax.swing.*;

import java.awt.event.*;
import java.awt.*;

import javax.swing.JFrame;

public class TestGUI extends JFrame {

    private JPanel _panel1 = new JPanel();
    private JTextArea _txtarea = new JTextArea(10, 10);
    private JTextField _txtfield = new JTextField();

    public TestGUI() {
        add(_panel1);
        _panel1.setLayout(new BorderLayout());
        _panel1.add(_txtarea);
        _panel1.add(_txtfield);
        validate();
        _panel1.setVisible(true);
        _panel1.setSize(500, 500);
    }

    public static void main(String[] args) {
        new TestGUI();
    }
}

I suggest showing the JFrame as well, as it contains your JPanel .

Try this as your main()

public static void main(String[] args) {
  SwingUtilities.invokeLater(new Runnable() {
    public void run() {
      new TestGUI().setVisible(true);
    }
  });
}

You have a few issues in your code. You are not setting the Layout correctly. BorderLayout requires positioning.

Once you have added the components to the JFrame, you either set a size for it or call pack() method, so that you JFrame assumes the size needed to fit the subcomponents.

Here is an a sample:

class TestGUI extends JFrame {

        private JPanel _panel1 = new JPanel();
        private JTextArea _txtarea = new JTextArea(10, 10);
        private JTextField _txtfield = new JTextField();

        public TestGUI() {
            add(_panel1);
            _panel1.setLayout(new BorderLayout());

            // border layout is done by positioning like center, south north etc.
            _panel1.add(_txtarea, BorderLayout.CENTER);
            _panel1.add(_txtfield, BorderLayout.NORTH);

            // set the size before making it visible
            _panel1.setSize(500, 500);
            setVisible(true);

            // call pack() so that the Frame assumes the needed space only
            pack();

            // set a default close method so that your frame  exits on close.
           setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    }

Next it is a good practice to spawn your JFrame through SwingUtilities.invokeLater or EventQueue.invokeLater , so that it is handled by the Event Dispatch Thread in it's own good time when processing the queue of events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM