代码之家  ›  专栏  ›  技术社区  ›  PeterLikesCode

在绘图组件上显示jbutton

  •  0
  • PeterLikesCode  · 技术社区  · 8 年前

    我在做一个游戏,我必须绘制组件绘制与游戏相关的一切。现在我想在绘图组件上添加一个“关闭”按钮。

    public class SimulationWindow extends JFrame 
    {
    private static final long serialVersionUID = 1L;
    
    public SimulationWindow()
    {
        super("Game");
        setUndecorated(true);
        setExtendedState(JFrame.MAXIMIZED_BOTH); 
    
    
        getContentPane().setBackground(Color.BLACK);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        JButton closeButton = new JButton();
        closeButton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                Game.close = true;
            }
        });
    
        add(new DrawingComponent());
        add(closeButton);
    
        setVisible(true);
    }
    

    }

    但这只是一个突然出现的灰色区域。基本上是游戏的绘图组件是不可见的。

    1 回复  |  直到 8 年前
        1
  •  0
  •   camickr    8 年前
    add(new DrawingComponent());
    add(closeButton);
    

    您只能将单个组件添加到borderlayout.center,这是未指定约束时的默认位置。

    如果要将按钮添加到绘图面板,基本代码为:

    DrawingComponent draw = new DrawingComponent();
    draw.setLayout(...); // set the appropriate layout manager
    draw.add( closeButton );
    add(draw, BorderLayout.CENTER); // explicitly see the location