简体   繁体   中英

How can I make my JPanels/JFrames actually show up?

I have a widget designed to compile different pieces of information about each "plate", and each piece of information is stored in a JLabel. I've put all of the JLabels into a JPanel (one JPanel for each plate) and then put the JPanel into a JFrame, because that seemed to be the consensus on the internet for the best way to get the JPanel to actually show up. When I construct the widgets in another class, I create an array of widgets (one widget for each plate), so the goal is to have this array of widgets (which are really just a JFrame that holds a JPanel that holds several JLabels) appear. I'm not sure where I'm going wrong, as I'm using setVisible() and I'm using the add(Component) method. Any input is very appreciated!!

public class BeltView extends JPanel implements BeltObserver {

    private Belt belt;
    private BeltViewWidget[] _widgets;

    public BeltView(Belt b) {
        this.belt = b;
        belt.registerBeltObserver(this);
        setLayout(new GridLayout(belt.getSize(), 1));
        _widgets = new BeltViewWidget[belt.getSize()];
        for (int i = 0; i < belt.getSize(); i++) {
            if (belt != null && belt.getPlateAtPosition(i) != null) {
                BeltViewWidget widget = new BeltViewWidget(belt, i);
                _widgets[i] = widget;
            }
        }
        for (int j = 0; j < _widgets.length; j++) {
            if (_widgets[j] != null) {
                add(_widgets[j]);
                _widgets[j].setVisible(true);
            }
        }
    }

Widget constructor (from widget class):

public BeltViewWidget(Belt belt, int position) {
    JPanel _widget_panel = new JPanel();
    JFrame _frame = new JFrame();
    _belt = belt;
    _position = position;
    Plate p = _belt.getPlateAtPosition(_position);
    _widget_panel.setVisible(true);
    _widget_panel.setLayout(new GridLayout());
    refresh();
}

You can do something like this:

public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame();
frame.setTitle("My First Swing Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Welcome");
frame.add(label);
frame.pack();
frame.setVisible(true);

}

I dont think you are setting the _frame visible with true.

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