在JPanel上绘制多个形状

时间:2011-11-01 17:02:40

标签: java swing awt pong

如果这有任何含糊不清的元素,我很抱歉,但我对Java Swing / AWT库感到不知所措(我讨厌GUI编程!)。

基本上我已经用JPanel设置了一个非常基本的JFrame:

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);
}

我的问题是这个;有没有办法动态地将组件绘制到 canPan 对象上?即一个圆圈和一些矩形?当然,这些组件的位置会随着用户输入而改变。

2 个答案:

答案 0 :(得分:3)

是的,覆盖它的paintComponent(Graphics g)方法并绘制传递的Graphics对象的副本(您将随后将其处置)。

有关详细信息,请参阅2D Graphics

答案 1 :(得分:2)

2D Graphics教程(包含代码示例)是您问题的答案,有关herehere

的更多信息