简体   繁体   中英

Having trouble adding graphics to JPanel

I have looked online, but I am still having trouble understanding how to add graphics to a JPanel

Here is the code for my panel class:

public class GamePanel extends JPanel {

    public GamePanel(){

    }

    public void paintComponent(Graphics g) {

        g.drawString("asd", 5, 5);
    }

}

And my main method:

public static void main(String[] args) {

    frame.setLayout(new FlowLayout());
    frame.getContentPane().setBackground(Color.WHITE);

    //i is an instance of GamePanel
    frame.add(i);

    frame.setPreferredSize(new Dimension(500, 500));
    frame.pack();
    frame.setVisible(true);

}

Text will only appear in a very tiny section of the screen (this applies to any graphics object I try to draw). What am I doing wrong?

FlowLayout respects preferred sizes of components. Therefore override getPreferredSize to give your JPanel a visible size rather than the default zero size Dimension that the panel currently has after JFrame#pack is called:

class GamePanel extends JPanel {

    public void paintComponent(Graphics g) {
        super.paintComponent(g); // added to paint child components
        g.drawString("asd", 5, 20);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(400, 300);
    }
}

Edit:

To eliminate gap between JPanel and its containing JFrame , set the vertical gap to 0 :

frame.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));

Two things jump out

  1. Your Game panel has no preferred size, which, by default, makes 0x0. FlowLayout will use this information to make decisions about how best to layout your panel. Because the size is 0x0, the repaint manager will ignore it. Try overriding the getPreferredSize method and return a appropriate size or use a layout manager that does not use the preferred size, like BorderLayout
  2. Your paintComponent method MUST call super.paintComponet

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