下面是一个简单的摇摆应用程序,我在其中试验了某些自定义技术。代码如下:-
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);
}
}
现在我有以下问题:-
setLayout(null)
1)当我在我的主类中将布局设置为 null时,ThemeComponents
为什么只有标题栏的框架大小会缩小为 null ?我希望它采用CustomPanel
我用于pack()
框架的大小。(使用诸如 flowlayout、borderlayout 之类的布局但是产生正确的输出)
2)getPreferredSize()
更好地用于设置组件的大小而不是。setPreferredSize()
实际上我没有发现它们之间有任何区别。