编程语言
首页 > 编程语言> > java – 在JPanel上绘制多个形状

java – 在JPanel上绘制多个形状

作者:互联网

如果这有任何含糊不清的元素,我很抱歉,但我对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对象上?即一个圆圈和一些矩形?这些组件的位置当然会随用户输入而改变.

解决方法:

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

有关更多信息,请参阅2D Graphics.

标签:pong,java,swing,awt
来源: https://codeday.me/bug/20190902/1793568.html