Why is my JFrame empty?

后端 未结 2 1039
青春惊慌失措
青春惊慌失措 2021-01-29 00:59

I can\'t seem to figure out why my JFrame is empty. Where am I going wrong?

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

public class GUIExample extends JFr

2条回答
  •  半阙折子戏
    2021-01-29 01:31

    First of all this is quite a good try to what you are trying to do. However there seem to be some basic misunderstandings as to how you are coding the GUI.

    There are two ways of making a GUI in java. Either you create frames and panel objects then add your components to them, or you can create and extend your own classes by extends JFrame. But in this case you have tried to do both. You have extended JFrame and you have created the Objects.

    I actually quite like how you've tried to extended the JFrame, so I've continued this and made code that add stuff to your screen!

    See below - GUIExample.java:

    import javax.swing.*; 
    import java.awt.FlowLayout;
    
    public class GUIExample extends JFrame {
    
        JCheckBox box1 = new JCheckBox("Satellite Radio");
        JCheckBox box2 = new JCheckBox("Air Conditioning");
        JCheckBox box3 = new JCheckBox("Manual Tranmission");
        JCheckBox box4 = new JCheckBox("Leather Seats");
        JRadioButton radio1 = new JRadioButton("Car");
        JRadioButton radio2 = new JRadioButton("Pickup Truck");
        JRadioButton radio3 = new JRadioButton("Minivan");
        JTextField text = new JTextField();
        ButtonGroup group = new ButtonGroup();
    
        GUIExample() {
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setSize(500, 500);
            setVisible(true);
    
            newGUI();
        }
    
    
        public void newGUI() {
    
            setLayout(new FlowLayout());
            JPanel panel = new JPanel();
            JPanel textPanel = new JPanel();
    
            add(textPanel);
            add(panel);
    
            panel.add(box1);
            panel.add(box2);
            panel.add(box3);
            panel.add(radio1);
            panel.add(radio2);
            panel.add(radio3);
            group.add(radio1);
            group.add(radio2);
            group.add(radio3);
    
        }
    
    }
    

    test.java:

    public class test {
    
        public static void main(String[] args) {
            GUIExample e = new GUIExample();
        }
    }
    

    To get this working. Compile both of the files and then run your program through test.java.

    Moreover your original solution, nowhere did you add a newGUI() call so all that code becomes redundant. However as the main method is static, you wouldn't be able to call it anyways.

    I hope this helps!

提交回复
热议问题