需要帮助清除我的摇摆应用中的某些疑虑

时间:2013-01-02 13:24:44

标签: java swing graphics graphics2d

下面是一个简单的摇摆应用程序,其中我正在尝试某些自定义技术。代码如下: -

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class ThemeComponents extends JFrame{
  public static void main(String args[])
  {
    SwingUtilities.invokeLater(new Runnable(){public void run(){new    ThemeComponents();}});
  }

  public ThemeComponents()
  {
    super("HACK 1:Creating Image Themed Components ");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new FlowLayout());
    CustomPanel p1=new CustomPanel();
    p1.add(new CustomLabel());
    add(p1);
    pack();
    setVisible(true);
  }
}

class CustomPanel extends JPanel
{
  BufferedImage img;
  CustomPanel()
  {
    try
    {
      img=ImageIO.read(new File("src/background.jpg"));
    } catch(IOException e){
      System.out.println("Error in loading background image "+e);
    }
  }
  public void paintComponent(Graphics g)
  {
    g.drawImage(img,0,0,getWidth(),getHeight(),null);
  }
  public Dimension getPreferredSize()
  {
    return new Dimension(img.getWidth(),img.getHeight());
  }
}

class CustomLabel extends JLabel
{
  ImageIcon img;
  CustomLabel ()
  {
    img=new ImageIcon("src/tornado.gif");


    setSize(img.getIconWidth(),getHeight());
    setIcon((Icon) img);
    //setOpaque(false);
    //setIconTextGap(0);
    setLocation(10,10);
  }
}

现在我有以下问题: -

1)当我在我的主类setLayout(null)中将布局设置为空ThemeComponents时,为什么帧大小仅缩小为null而只有标题栏?我希望它的大小为{{1因为我已经使用CustomPanel作为框架。(使用诸如flowlayout之类的布局,但是borderlayout会产生正确的输出)

2)使用pack()更好地设置组件的大小而不是getPreferredSize()。实际上我发现它们之间没有任何区别。

2 个答案:

答案 0 :(得分:2)

  1. 如果您使用null - 布局,首选尺寸将返回(0,0),因此您只会看到标题栏。 pack()验证您的JFrame,然后将JFrame的大小设置为内容窗格的首选大小(即0,0),并为标题栏,菜单添加所需的空间等等......

  2. 您很可能应该避免调用setPreferredSize()而是覆盖getPreferredSize()。调用setPreferredSize()会让其他人修改该值。在这种情况下,它可能意味着首选大小不是组件的固有部分,因此您不需要调用setPreferredSize()。覆盖getPreferredSize()可以完全控制并导致首选大小成为组件的固有部分。

  3. 您还应该在CustomPanel中调用super.paintComponent(g);

  4. CustomLabel中,调用setLocation没有任何意义(无论如何,父布局会改变这种情况)

  5. CustomLabel中,这也没有任何意义:setSize(img.getIconWidth(),getHeight());,因为父布局无论如何都会更改这些值(而btw,getHeight()在这种情况下返回0 )

答案 1 :(得分:0)

setLayout()用于设置窗口的布局,用于布局click here 默认情况下,内容窗格使用BorderLayout,只需将布局设置为null即可 没有布局,你看到的只是标题栏。

getPreferred()用于获取您为组件提供的首选大小 用于设置首选大小:p

相关问题