将JButton放置在图像上

时间:2014-11-20 16:13:48

标签: java swing user-interface

目标:将JButton放在从不同类加载的图像的顶部。 问题:只能显示JButton或图像

//main class
JPanel mPanel.add(new JButton("ddd") );
mPanel.add(drawbg);


class DrawBg extends JPanel {   

    public Dimension getPreferredSize() {
            return new Dimension(1280, 720);
        }

        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            // background
            Image img = new ImageIcon(getClass().getResource("/images/test_bg.jpg")).getImage();
            int imgX = img.getWidth(null);
            int imgY = img.getHeight(null);
            g.drawImage(img, (getWidth() - imgX), (getHeight() - imgY), imgX, imgY, null);

    }

1 个答案:

答案 0 :(得分:2)

编辑啊是的,正如ControlAltDel指出的那样,你没有将JButton添加到你的绘图JPanel实例中。就这样做,你的问题就解决了。


我没有看到代码中的错误,因此它可能位于未显示的代码中。我确实看到了一个问题,你正在读取paintComponent中的图像,这是永远不应该做的事情,因为它会减慢绘画速度,从而降低程序的感知响应速度。另外,为什么要用每种颜料重新读取图像。而是一次性阅读。

例如:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.*;

public class ButtonOnImg extends JPanel {
   public static final String IMG_PATH = "https://duke.kenai.com/gun/Gun.jpg";
   private BufferedImage img;

   public ButtonOnImg() throws IOException {
      URL url = new URL(IMG_PATH);
      img = ImageIO.read(url);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      if (img != null) {
         g.drawImage(img, 0, 0, null);
      }
   }

   @Override
   public Dimension getPreferredSize() {
      if (img == null) {
         return super.getPreferredSize();
      } else {
         int w = img.getWidth();
         int h = img.getHeight();
         return new Dimension(w, h);
      }
   }

   private static void createAndShowGui() {
      try {
         ButtonOnImg mainPanel = new ButtonOnImg();

         mainPanel.add(new JButton("Button!"));

         JFrame frame = new JFrame("ButtonOnImg");
         frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
         frame.getContentPane().add(mainPanel);
         frame.pack();
         frame.setLocationByPlatform(true);
         frame.setVisible(true);
      } catch (IOException e) {
         e.printStackTrace();
      }

   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

显示为:

enter image description here