[英]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!). 如果这有任何含糊不清的元素,我很抱歉,但我对Java Swing / AWT库感到不知所措(我讨厌GUI编程!)。
Basically I have set up a very basic JFrame with a JPanel as such: 基本上我已经用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);
}
My question is this; 我的问题是这个; is there a way of drawing components dynamically onto the canPan object?
有没有一种方法可以动态地将组件绘制到canPan对象上? 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). 是的,覆盖它的
paintComponent(Graphics g)
方法并绘制传递的Graphics
对象的副本(您将随后将其处置)。
For more information, see 2D Graphics . 有关更多信息,请参阅2D图形 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.