目前,我用這個代碼:如何強制將ImageIcon設爲特定尺寸?
public class Test extends JFrame {
static Test t = null;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
t = new Test();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static void addComponentsToPane(Container pane) {
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
ImageIcon icon;
icon = new ImageIcon(System.getProperty("user.dir") + "/res/background.png");
Image img = icon.getImage() ;
Image newimg = getScaledImage(img, frame.getWidth(), frame.getHeight()) ;
icon = new ImageIcon(newimg);
JLabel background=new JLabel(icon);
//frame.getContentPane().add(background);
background.setLayout(new FlowLayout());
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = frame.getHeight() * 10;
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
pane.add(background, c);
}
private static Image getScaledImage(Image srcImg, int w, int h){
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, 0, 0, w, h, null);
g2.dispose();
return resizedImg;
}
private void createAndShowGUI() {
frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
static JFrame frame = null;
public Test() {
createAndShowGUI();
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
}
}
這工作正常的按鈕,但由於某種原因未與圖像工作的JLabel。 我該如何讓這個JLabel/Image適合我想要的尺寸?
圖像被此刻真的很小, 時候,確實,與一個JButton相同的代碼佔用面積更是這樣的: 此外,它可以讓我得到的ImageIcon比按鈕4還要大,這也是我想避免的。
那麼,我該如何拉伸/收縮圖像以適合我希望它具有的區域?
1)爲了更好地提供幫助,請發佈[MCVE](http://stackoverflow.com/help/mcve)(最小,完整,可驗證示例)。 2)獲取圖像的一種方法是熱點鏈接到[本問答](http://stackoverflow.com/q/19209650/418556)中列出的圖像。 – 2014-09-11 11:51:56
@AndrewThompson要麼有人知道答案,要麼他們不知道。由於這是唯一相關的代碼,因此我不理解將代碼放入IDE中的問題。 不知道你的第二個鏈接正在進行什麼:/。 – Joehot200 2014-09-11 11:54:49
*「因爲這是唯一的代碼相關..」*着名的遺言。但是,如果通過「相關」,你的意思是代碼I或其他人可以複製/粘貼,編譯和測試(這與我有關,作爲潛在的幫手),然後,不,它不是所有相關的代碼.. – 2014-09-11 11:57:21