Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

java - Elements not showing in GridBagLayout

I am using GridBagLayout as JFrame layout. My elements are not showing no matter what i write. Please don't give answers which use anything but GridBagLayout(sorry if it sound rude)

enter image description here

JPanel Panel;
    JButton insertButton = new JButton("Insert");
    GridBagConstraints gbc;

    public MainFrame() {

        this.setTitle("JAVA & MySQL");
        this.setVisible(true);
        this.setBounds(500, 100, 600, 600);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        Panel = new JPanel(new GridBagLayout());
        Panel.setOpaque(true);
        Panel.setBackground(Color.BLUE);
        gbc = new GridBagConstraints();

        gbc.weightx = 1;
        gbc.weighty = 1;
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.insets = new Insets(0, 10, 0, 0);
        gbc.fill = GridBagConstraints.BOTH;

        Panel.add(insertButton, gbc);




    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your code is not clear whats where (is this code inside your frame class) and you have chosen names poorly. By convention field names should start witha lower case letter (to distinguish them from class names).

It appears you never add your panel to the frame, and also you never pack() the frame.

Alter the code like this:

public MainFrame() {
    this.setTitle("JAVA & MySQL");
    // setting visible should come last!
    //this.setVisible(true);
    this.setBounds(500, 100, 600, 600);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);

    Panel = new JPanel(new GridBagLayout());
    Panel.setOpaque(true);
    Panel.setBackground(Color.BLUE);
    gbc = new GridBagConstraints();

    gbc.weightx = 1;
    gbc.weighty = 1;
    gbc.anchor = GridBagConstraints.CENTER;
    gbc.gridx = 1;
    gbc.gridy = 1;
    gbc.insets = new Insets(0, 10, 0, 0);
    gbc.fill = GridBagConstraints.BOTH;

    Panel.add(insertButton, gbc);

    // put the panel into the frame!
    setLayout(new BorderLayout());
    add(Panel, BorderLayout.CENTER);
    pack();
    setVisible(true);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...