事實證明,這比我想象的要困難得多。我只是在進行一些學習,並利用繪圖功能。我想要的是程序啓動一個包含矩形的窗口。該矩形的大小將根據窗口的大小進行縮放(即,如果窗口爲1000px,並且矩形設置爲按90%縮放,則矩形將爲900px)。我有數學計算出如何居中並確定它的大小,但通過使用存根,我發現使用object.getWidth()和高度等,每次都返回0,完全算數漿紗。試圖讓它在加載時自己畫一個窗口
想了一會兒之後,我假設它是因爲它試圖從一個仍在構建的對象中獲取寬度和高度。按照我自己的邏輯,只要你在構造函數的構建部分之後做數學,它應該沒問題,但是可惜 - 我看起來是錯的。
我試着創建獨立的類,創建一個框架和一個使繪圖。繪圖對象接受一個JFrame作爲構造函數的一部分,並嘗試繪製它。我分別實例化每一個,先框架,然後繪製對象(發送幀對象),但似乎也沒有工作。
有什麼建議嗎?
編輯:
安德魯的建議。這裏將被添加到窗口
package scaling_test;
import java.awt.*;
import javax.swing.*;
public class MyDrawing extends JPanel
{
public MyDrawing() throws HeadlessException
{
this.setVisible(true);
}
public void paintComponent(Graphics g)
{
super.paintComponents(g);
//set scaling
int usrScale = 90;
int scaleRef = (100 - usrScale)/2;
int xStart = this.getWidth() * (scaleRef/100);
int yStart = this.getHeight() * (scaleRef/100);
int width = (usrScale/100) * this.getWidth();
int height = (usrScale/100) * this.getHeight();
//draw square outline
g.setColor(Color.green);
g.fillRect(xStart, yStart, width, height);
}
}
我的面板對象這是並稱的JPanel對象的窗口:
package scaling_test;
import java.awt.*;
import javax.swing.*;
public class DrawThis extends JFrame
{
MyDrawing drawing;
public DrawThis() throws HeadlessException
{
drawing = new MyDrawing();
this.add(drawing);
}
}
而且啓動
package scaling_test;
public class ScaleTest
{
public static void main(String[] args)
{
DrawThis program = new DrawThis();
program.setBounds(250, 250, 800, 600);
program.setVisible(true);
}
}
更新面板(仍犯規工作):
package scaling_test;
import java.awt.*;
import javax.swing.*;
public class MyDrawing extends JPanel
{
public MyDrawing() throws HeadlessException
{
}
public void paintComponent(Graphics g)
{
super.paintComponents(g);
//set scaling
int usrScale = 90;
int scaleRef = (100 - usrScale)/2;
int xStart = this.getWidth() * scaleRef/100;
int yStart = this.getHeight() * scaleRef/100;
int width = usrScale * this.getWidth()/100;
int height = usrScale * this.getHeight()/100;
//draw square outline
g.setColor(Color.green);
g.fillRect(xStart, yStart, width, height);
}
}
編輯過的版本可以正常工作,並且完全按照程序進行編程(繪製一個居中的綠色填充矩形,按照組件尺寸的90%縮放) - 那麼您的期望究竟是什麼? – kleopatra 2011-04-12 08:25:18