【问题标题】:Drawing multiple shapes onto a JPanel在 JPanel 上绘制多个形状
【发布时间】:2011-11-02 01:10:08
【问题描述】:

如果这有任何歧义,我深表歉意,但我对 Java Swing/AWT 库有点不知所措(我讨厌 GUI 编程!)。

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

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 对象上?即一个圆圈和一些矩形?这些组件的位置当然会随着用户输入而改变。

【问题讨论】:

    标签: java swing awt pong


    【解决方案1】:

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

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

    【讨论】:

    • 好的,谢谢,我的讲师之前提到过一些关于这个的事情。 Graphics 对象究竟做了什么?请原谅我的无知;我从来没有真正做过这种工作。
    • @VisionIncision,见Graphics
    【解决方案2】:

    2D Graphics 教程(带有代码示例)您的问题的答案,更多关于herehere

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-05
      相关资源
      最近更新 更多