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? i.e. 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.