在JFrame上创建透明的JPanel

时间:2016-05-18 00:57:11

标签: java graphics jframe jpanel transparent

我是java新手,我正在开发一款游戏。基本上,有泡沫上升,用户必须通过将鼠标移到它们上来弹出它们。

我已经在JFrame上制作了一个动画,我需要在顶部为MouseMotionListener添加一个JPanel。但是,当我在JFrame顶部添加JPanel时(即使将setOpaque设置为false),它仍然不允许我在下面看到我的动画。你可以在下面看到我的代码。如果您发现编码错误,请告诉我。

我有两个解决方案,要么在JPanel中动画(我不知道该怎么做),要么让JPanel透明。

游戏类:

public class Game extends JPanel{

  public static final int WINDOW_WIDTH = 600;
  public static final int WINDOW_HEIGHT = 400;

  private boolean insideCircle = false;
  private static boolean ifPaused = false;
  private static JPanel mainPanel;
  private static JLabel statusbar;
  private static int clicks = 0;
  //Creates a Bubbles object Array
  Bubbles[] BubblesArray = new Bubbles[5];

  public Game() {

    //initializes bubble objects
     for (int i = 0; i < BubblesArray.length; i++)
       BubblesArray[i] = new Bubbles();
     }

public void paint(Graphics graphics) {

  //makes background white
   graphics.setColor(Color.WHITE);
   graphics.fillRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);

   //paints square objects to the screen
   for (Bubbles aBubblesArray : BubblesArray) {
     aBubblesArray.paint(graphics);
   }
}

public void update() {

 //calls the Square class update method on the square objects
 for (Bubbles aBubblesArray : BubblesArray) aBubblesArray.update();
}

    public static void main(String[] args) throws InterruptedException {
     statusbar = new JLabel("Default");
     mainPanel = new JPanel();
     mainPanel.setOpaque(false);
     mainPanel.setBackground(new Color(0,0,0,0));
     mainPanel.setVisible(true);
     mainPanel.addMouseMotionListener(new MouseAdapter() {
       @Override
        public void mouseMoved(MouseEvent e) {
          statusbar.setText(String.format("Your mouse is at %d, %d", e.getX(), e.getY()));
          }

       public void mouseExited(MouseEvent e){
         ifPaused = true;
        }   

        public void mouseEntered(MouseEvent e){
        ifPaused = false;
         }

     });

     Game game = new Game();
    JFrame frame = new JFrame();

    frame.add(game);
     frame.add(mainPanel);



   frame.add(statusbar, BorderLayout.SOUTH);
   frame.setVisible(true);
   frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
   frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
   frame.setTitle("Bubble Burst");
   frame.setResizable(false);
   frame.setLocationRelativeTo(null);

   while (true) {
      if (!ifPaused){
       game.update();
       game.repaint();
       Thread.sleep(5);
      }
   }
}    
}

1 个答案:

答案 0 :(得分:0)

您的game面板未显示,因为您要将两个组件添加到BorderLayout的同一位置(BorderLayout.CENTER)。因此,{&#34}没有添加{&#34}。 mainPanel,它正在取代它。话虽如此:

看起来你的game实际上正在做任何事情,除了听老鼠的动作。您是否可以将mainPanel添加到MouseAdapter对象,因为它扩展game,如下所示:

JPanel