简体   繁体   中英

Drawing multiple shapes onto a JPanel

I apologise if this has any element of ambiguity, but I am kind of overwhelmed by the Java Swing/AWT libraries (I hate GUI programming!).

Basically I have set up a very basic JFrame with a JPanel as such:

public void drawGUI() {
    //Instantiate the JFrame.
    mainFrame = new JFrame("Ping Pong alpha1");
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainFrame.setLayout(new BorderLayout());

    //Instantiate & setup the JPanels.
    btnPan = new JPanel();
    canPan = new JPanel();
    canPan.setLayout(new BoxLayout(canPan, BoxLayout.PAGE_AXIS));
    statPan = new JPanel();
    statPan.setLayout(new BoxLayout(statPan, BoxLayout.PAGE_AXIS));

    //Add JPanels to mainFrame.
    mainFrame.add(btnPan, BorderLayout.PAGE_END);
    mainFrame.add(canPan, BorderLayout.CENTER);
    mainFrame.add(statPan, BorderLayout.LINE_END);

    //Instantiate & setup JMenuBar.
    menuBar = new JMenuBar();
    mainFrame.add(menuBar, BorderLayout.PAGE_START);

    //Instantiate JMenu's & JMenuItem's.
    gameMenu = new JMenu("Game");
    helpMenu = new JMenu("Help");
    newGame = new JMenuItem("New Game");
    exit = new JMenuItem("Exit Game");
    about = new JMenuItem("About");

    //Add JMenuItems to their JMenu's.
    gameMenu.add(newGame);
    gameMenu.add(exit);
    helpMenu.add(about);
    menuBar.add(gameMenu);
    menuBar.add(helpMenu);

    //Add items to JPanels.
    canvas = new PongCanvas();
    mainFrame.getContentPane().add(canvas);

    //Set window parameters and pack.
    mainFrame.pack();
    mainFrame.setSize(800, 600);
    mainFrame.setResizable(false);
    mainFrame.setVisible(true);
}

My question is this; is there a way of drawing components dynamically onto the canPan object? ie a circle and some rectangles? The position of these components will of course change with user input.

Yes, override it's paintComponent(Graphics g) method and draw on a copy of the passed Graphics object (which you will subsequently dispose of).

For more information, see 2D Graphics .

2D图形教程(带代码示例)是您问题的答案,更多关于此处此处的内容

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