如何在另一个JPanel内的JPanel上绘制形状? [英] How do you draw shapes on a JPanel, which is within another JPanel?
问题描述
我目前正在尝试在JFrame
内另一个JPanel
内的JPanel
上绘制形状.
I'm currently trying to draw shapes on a JPanel
, which is within another JPanel
, within a JFrame
.
我搜索了Google和Youtube,发现如何在具有一个面板的JFrame
中绘制形状,但是没有发现任何可以帮助我完成工作的东西. (也许我没看到什么).
I've searched Google and Youtube and found out how to draw shapes within a JFrame
that has one panel, but have found nothing which can help me with what I'm doing. (maybe I'm not seeing something).
到目前为止我看到的代码:
Code I've seen so far:
public class GameScreen
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.red);
g.drawRect(100, 10, 30, 40);
}
public static void main(String[] args)
{
GameScreen gs = new GameScreen();
JFrame f = new JFrame();
f.setTitle("");
f.setSize(400,400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(gs);
}
当我只处理一个面板时,这一切都很好,但是我想在我创建的第一个面板内的面板上显示形状.
This is all good for when I'm dealing with just one panel, but I wanna display shapes on a panel which is within the 1'st panel I've created.
推荐答案
以与现在相同的方式将JPanel添加到JFrame,但是使用您自己的JPanel子类来完成.
Add a JPanel to the JFrame in the same way as you're doing now, but do it with your own subclass of JPanel.
class MyPanel extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.drawRect(100, 10, 30, 40);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400,400); // As suggested by camickr
}
}
您可以将其添加到位于JFrame内的JPanel中
You can add this to a JPanel which sits within the JFrame
public static void main(String[] args)
{
MyPanel mp = new MyPanel();
JPanel jp = new JPanel();
jp.add(mp);
JFrame f = new JFrame();
f.setTitle("");
f.setSize(400,400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(jp);
}
如果您将它们添加为子组件,则该方法适用于组件中的组件.关键是扩展组件并覆盖您想要更改的方法.
This can work for components within components, if you add them as children components. The key is to extend the component and override the methods you wish to change.
这篇关于如何在另一个JPanel内的JPanel上绘制形状?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!