【问题标题】:JPanel with a background image带有背景图像的 JPanel
【发布时间】:2010-11-25 21:10:04
【问题描述】:

我有以下代码:

class ImagePanel extends JPanel {

          private Image img;

          public ImagePanel(String img) {
            this(new ImageIcon(img).getImage());
          }

          public ImagePanel(Image img) {
            this.img = img;
            Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
            setPreferredSize(size);
            setMinimumSize(size);
            setMaximumSize(size);
            setSize(size);
            setLayout(null);
          }

          public void paintComponent(Graphics g) {
            g.drawImage(img, 0, 0, null);
          }
        }

以及以下内容:

public GUIVenDetails() throws MalformedURLException, IOException{

        mapPanel = new ImagePanel("http://www.netstate.com/states/symb/gamebirds/images/wild_turkey.jpg");
        mapPanel.setPreferredSize(new Dimension(200,200));
        mapPanel.setMinimumSize(mapPanel.getPreferredSize());
        mapPanel.setMaximumSize(mapPanel.getPreferredSize());


        add(mapPanel);
    }

public static void main(String[] args) throws MalformedURLException, IOException, XPathExpressionException, SAXException, ParserConfigurationException {


        GUIVenDetails gui = new GUIVenDetails();

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension windowSize = gui.getSize();

        int windowX = Math.max(0, (screenSize.width  - windowSize.width ) / 2);
        int windowY = Math.max(0, (screenSize.height - windowSize.height) / 2);

        JFrame f=new JFrame();
        f.setSize(new Dimension(400,800));
        f.setLocation(windowX, windowY); 

        f.add(gui);
        f.setVisible(true);
    }

当我运行代码时,我只看到白色...这是为什么呢?

【问题讨论】:

    标签: java swing jpanel


    【解决方案1】:

    这不是您从互联网上读取文件的方式。尝试类似:

    String imagePath = "http://duke.kenai.com/misc/Bullfight.jpg";
    Image image = null;
    
    try 
    {
        URL url = new URL(imagePath);
        image = ImageIO.read(url);
    } 
    catch (IOException e) 
    {
         System.out.println(e);
    }
    

    或者你仍然可以使用

    new ImageIcon(new URL(...));
    

    但是String不会仅仅因为它以“http”开头就成为URL。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多