[英]I can't set the size of an image on Java
正如我在標題上寫的,我無法在 java 上設置圖像的大小,我不知道為什么。 所以,這就是代碼:
package it.unimol.monopoli.gui;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import it.unimol.monopoli.app.Player;
public class GameBoard extends JPanel{
private List<Player> players;
private JLabel image;
public GameBoard(List<Player> players) {
this.boxes = new ArrayList<>();
this.players = players;
this.setBounds(0,0,500,500);
image = new JLabel(new ImageIcon("G:\\Il mio Drive\\Università\\Programmazione II\\21-22\\progetto\\Tabellone.jpg"));
this.add(image);
inizializeSquares();
}
}
class 不完整,但不起作用的是“setBuonds()”,因為圖像位於所有尺寸為 1000x1000 的框架上。 對於任何信息,所有面板都具有默認布局。
問任何問題,我會等你的答案。
調整面板或放置圖像的 label 的大小不起作用。 這樣想, ImageIcon
不是典型的 Swing 組件; 像面板或 label。 因此,它不會像正確的 Java Swing 組件那樣“遵守”調整大小的規則。 我認為主要原因是因為圖像圖標不是容器,並且這些規則(與布局和布局管理器相關)適用於容器而不是組件。 無論如何,這並不重要。 要調整ImageIcon
對象的大小,您需要做的是縮放圖像,然后將縮放后的圖像放在容器上(在本例中為JLabel
)。
我調整了代碼,以便可以在我的環境中運行它並用我自己的圖像對其進行測試。 為了在此處發布,我將其切換回您的圖像。
public class GameBoard extends JPanel{
private List<Player> players;
private List<?> boxes; // not sure what this is
private JLabel image;
public GameBoard(List<Player> players) {
this.boxes = new ArrayList<>();
this.players = players;
this.setBounds(0,0,500,500);
ImageIcon icon = new ImageIcon("G:\\Il mio Drive\\Università\\Programmazione II\\21-22\\progetto\\Tabellone.jpg");
// this is the magic sauce (image scaled to 100x100) - adjust to your needs
icon.setImage(icon.getImage().getScaledInstance(100, 100,Image.SCALE_DEFAULT));
image = new JLabel(icon);
this.add(image);
}
public static void main(String[] args) {
GameBoard board = new GameBoard(null);
JFrame frame = new JFrame();
frame.setBounds(100, 100, 1000, 1000);
frame.getContentPane().add(board);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
基本上,您正在獲取當前圖像並使用該實例,您將在其中設置其自身的縮放版本。 然后,您將縮放后的圖像放入 Swing 容器中,就像您在此處所做的JLabel
一樣。
如果你仔細想想,這真是太天才了。 您不希望您的圖像受到布局管理器效果的影響,這些效果會在根據布局規則調整組件大小時扭曲圖像。 通過不允許 Swing 容器調整圖像大小,您將可以自由使用您想要的任何布局管理器(甚至是絕對定位),而不必擔心應用程序中的圖像(或圖標)可能會受到何種影響。 這些最后的評論是我的意見,而不是一些行業共識,但這是有道理的; 不是嗎?
更新:
Image.SCALE_DEFAULT
是用於調整大小的選定算法。 我對這些算法了解不多,但這是 web 上用於進行縮放的最多示例之一。 如果你很好奇,你應該研究一下這個和 select(也許)一個更適合你的特定情況的算法。 我希望,即使是默認的縮放算法,也會有缺點。 否則,為什么有其他算法來做同樣的事情? 無論如何,我認為在這篇文章上添加這個最終評論是謹慎的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.