Unable to drawimage on null layout swing

49 views Asked by At

I want to draw some images on screen alongside some JButtons placed in different places of the screen. However whenever I have setLayout(null); the images do not show up on screen. If i don't set it to null I can make the images show up but I can't place my Jbuttons on the desired places.

How can i make so i have setLayout(null); and still be able to draw multiple images on screen while placing my buttons anywhere?

My Frame Class:

public class PFrame extends JFrame {
    JPanel p;
    public PFrame() {
        p = new PPanel();
        p.setBackground(Color.WHITE);
        Container c = getContentPane();
        c.setLayout(null);
        c.add(p);
        setSize(1200,700);
        
        JRadioButton White = new JRadioButton("White");
        ButtonGroup G1 = new ButtonGroup();
        White.setBounds(1000, 30, 80, 50);
        G1.add(White);
        this.add(White);
       //rest of buttons code here...
public class PPanel extends JPanel{

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Image [] vi = ImgArray();
        int x = 0;
        int y = 0;
        int i;
        for (i = 0; i < vi.length / 2; i++) {
            g.drawImage(vi[i],x,y,240,310,null);
            x+= 250;
            
        }
        y = 320;
        x = 0;
        for (i = vi.length / 2; i < vi.length; i++) {
            g.drawImage(vi[i],x,y,240,310,null);
            x+= 250;
        }
    }
}

Main method:

public static void main(String[] args) {
        PersonagensFrame f =new PFrame();
        f.setVisible(true);
        f.repaint();

    }
1

There are 1 answers

1
thatsouris On

I would recomend using anything other then a null layout for swing. You should check out the documentation for layouts such as GridBagLayout and GridLayout; since they are much more friendly in terms of compatibility.

If that isn't what you are looking for, you should also try making two seperate panels, seperating your buttons and images.

Swing was specifically built to incorporate layouts in which they provide.

I hope you figure it out! :)