Pregunta

I have been trying to learn how to use layout manages in java, I have the following code that trys to add the class "StartButton", startbutton is just a class that extends JButton

When I run the code my JFrame is loaded properly and the JPanel is created, I also added a print to layoutItems() to insure that the function is being called.

This is my JPannel code;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JPanel;

public class menuPanel extends JPanel {

    private static final long serialVersionUID = 1L;

    private static final Color BG_COLOR = new Color(0xfaf8ef);


    private startButton startbutton;

    public menuPanel(){
        this.setOpaque(false);
        this.setPreferredSize(new Dimension(300, 400));
        this.setBackground(new Color(107, 106, 104));
        this.setVisible(true);
        setLayout(new GridBagLayout());

        startbutton = new startButton();

        layoutItems();
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.setColor(BG_COLOR);
        g.fillRect(0, 0, this.getSize().width, this.getSize().height);
    }


    public void layoutItems(){
        GridBagConstraints c = new GridBagConstraints();
        System.out.println("lol");
        c.weightx = 0.25;
        c.weighty = 0.175;
        c.gridwidth = 2;
        c.gridx = 1;
        c.gridy = 6;
        this.add(startbutton, c);
    }
}
¿Fue útil?

Solución

Overriding paint rather than paintComponent results in unpredictable behavior in the way that components are painted for any Swing component.

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    ...
}

In fact overriding paintComponent isnt necessary as setBackground(BG_COLOR) will give the equivalent result

Otros consejos

Ignore the recommendation to call pack() on the class above as it does not work for JPanels. Instead, don't set your JPanel's size or preferred size -- let the components themselves and your layout managers do that. Then add all items to the JFrame, call pack() on it after adding all items, and then call setVisible(true) on it, in that order.

Oh, you will want to change your startbutton class name to StartButton since Java class names should begin with an upper case letter, and you should use camel-case names for all identifiers except constants.

If you're still stuck after trying out these recommendations, then consider creating and posting your minimal code example program for us to review, test, and possibly fix.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top