简体   繁体   中英

Cannot add JLabel or JButton to a JFrame. The frame won't show it

I'm new to Java. I'm trying to add JLabel to a JFrame but it doesn't show. I've tried adding JButton also but it does't seem to work. I've tried so many things over the past few days.

Anything wrong with my code?

public class F2 extends JPanel implements ActionListener {

    JFrame frame = new JFrame();
    JLabel label = new JLabel();
    int j = 2;
    ArrayList<Person> people = new ArrayList<>();

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        F2 f = new F2();

    }

    public F2() {
        j++;
        frame = new JFrame();
        frame.setSize(1380, 728);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Timer t = new Timer(20, this);
        t.restart();
        label.setText("Test");

        add(label);
frame.pack();
        frame.add(this);
        frame.setVisible(true);

        for (int i = 0; i < 100; i++) {
            people.add(new Person(0));
        }
    }

    public void paint(Graphics g) {
        super.paintComponent(g);
        Places p1 = new Places(g);
        for (Person p : people) {
            p.paint(g); //recall that each Person object has a paint method. We're passing g as the argument
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        repaint();
    }
}

Copying Alex Rudenko answer:

You should have added the label to your panel and then add your panel to the frame. Now your empty panel replaces the label.

this.add(label)
frame.add(this)

Maybe make it also visible and play with the coordinates and the size... or just copy a premade code from the internet... the way you are using the jpanel in the main class is maybe confusing you.

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