[英]How do I implement zooming for a Jpanel?
我正在為女巫做學校項目我必須模擬一個蟻群並在圖形用戶界面中顯示它。
整個項目已基本完成,但我需要為我的jPanel實現縮放功能。
我在這個網站上發現了一個基本上我需要的線程。這是鏈接: 在面板中放大和縮小
Thanasis在該線程中所做的是我基本上需要的但我不知道如何在我的代碼中使用其他類來實現它。
我是圖形用戶界面的新手,我們基本上是通過這個項目來學習和理解它,所以請原諒我,如果答案是超級簡單的,我正在尋求答案。
我可以為Pannel和Window類提供代碼。
我已經嘗試啟動它而沒有任何想法它會直接在我的jpanel上工作,但它當然沒有。也試圖在我的主要調用它,但這也沒有用。 這是我面板中的paintComponent。 我基本上都是這樣做的(螞蟻,殖民地,食物)。
public void paintComponent(Graphics g){
int tailletab = this.gri.getTab().length;
//On récupère le tableau de la Grille
int[][] gril = this.gri.getTab();
int taillecarre;
int xcol = this.colo.getPos().getX();
int ycol = this.colo.getPos().getY();
int xsou = this.source.getPos().getX();
int ysou = this.source.getPos().getY();
if(tailletab<=50){
taillecarre = tailletab/4+2;
}else{
if(tailletab<60){
taillecarre = tailletab/5+1;
}else{
if(tailletab<70){
taillecarre = tailletab/7+1;
}else{
if(tailletab<80){
taillecarre = tailletab/8;
}else{
if(tailletab<90){
taillecarre = tailletab/10;
}else{
taillecarre = tailletab/13;
}
}
}
}
}
for(int i=0; i<tailletab; i++){
for(int j=0; j<tailletab; j++){
if(gril[j][i]==0){
if(j==xcol && i==ycol){
g.setColor(new Color(102, 51, 0));
g.fillRect(xcol*taillecarre, ycol*taillecarre,taillecarre,taillecarre);
g.setColor(Color.BLACK);
g.drawRect(xcol*taillecarre, ycol*taillecarre,taillecarre,taillecarre);
}else{
if(j==xsou && i==ysou){
g.setColor(Color.RED);
g.fillRect(xsou*taillecarre, ysou*taillecarre,taillecarre,taillecarre);
g.setColor(Color.BLACK);
g.drawRect(xsou*taillecarre, ysou*taillecarre,taillecarre,taillecarre);
}else{
g.setColor(Color.BLACK);
g.drawRect(j*taillecarre, i*taillecarre, taillecarre, taillecarre);
}
}
}else{
g.setColor(Color.BLACK);
g.drawRect(j*taillecarre, i*taillecarre, taillecarre, taillecarre);
g.fillRect(j*taillecarre, i*taillecarre, taillecarre, taillecarre);
}
}
}
}
Andreas Holstenson在你提供的鏈接中的答案比Thanasis更好,因為你不應該像正確的那樣覆蓋paint
而不是paintComponent
,並且Thanasis不會覆蓋轉換但是試圖愚蠢地關於不逐步更新轉換。 如果你失去了我,那就完全忘掉那個答案吧。
否則,選擇是否使用AffineTransform
無關緊要,因為結果是相同的。 可以說, AffineTransform
更易於使用。
要回答您的問題,請將額外的比例/翻譯代碼放在該方法的頂部,之后繪制的所有圖形都應縮放(即使您使用g
而不是g2
)。
@Override
protected void paintComponent(Graphics g) { // No need to widen it to public
Graphics2D g2 = (Graphics2D)g;
AffineTransform oldTransform = g2.getTransform();
try {
float zoom = 0.5f; // shrink
// Note that transforms are in reverse order
// because of how matrix multiplications work.
AffineTransform newTransform = new AffineTransform();
// 2nd transform: re-center
newTransform.translate(getWidth() * (1 - zoom) / 2,
getHeight() * (1 - zoom) / 2);
// 1st transform: zoom (relative to upper-left corner)
newTransform.scale(zoom, zoom);
g2.transform(newTransform);
// Draw here
} finally {
// Try-finally is probably not required, but ensures that the transform
// gets restored even if an exception is thrown during drawing.
g2.setTransform(oldTransform);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.