我有這個基本的Java應用程序在女巫dim_x
和dim_y
表示窗口和其中的畫布的尺寸。如何讓這些值隨用戶更改窗口大小而更改,以便畫布上繪製的內容相應地縮小/展開?如何偵聽此Java應用程序的大小?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MLM extends Canvas {
static int dim_x = 720;
static int dim_y = 480;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Canvas canvas = new MLM();
canvas.setSize(dim_x, dim_y);
frame.getContentPane().add(canvas);
frame.pack();
frame.setVisible(true);
}
public void paint(Graphics g) {
// some stuff is drawn here using dim_x and dim_y
}
}
編輯: 以下本雅明的答案我已經嘗試添加這裏面工作,但有沒有更好的辦法做到這一點?如在,不使canvas
靜態,也許?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MLM extends Canvas {
static int dim_x = 720;
static int dim_y = 480;
static Canvas canvas;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canvas = new MLM();
canvas.setSize(dim_x, dim_y);
frame.getContentPane().add(canvas);
frame.pack();
frame.setVisible(true);
frame.addComponentListener(new ComponentListener(){
public void componentResized(ComponentEvent e) {
Dimension d = canvas.getSize();
dim_x = d.width;
dim_y = d.height;
}
public void componentHidden(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {}
public void componentShown(ComponentEvent e) {}
});
}
public void paint(Graphics g) {
// some stuff is drawn here using dim_x and dim_y
}
}
+1但該方法被稱爲'componentResized()' – AlexR 2012-02-13 20:36:29
是的,你說得對,也適用於Android約定:) – MByD 2012-02-13 20:37:23
這太好了。謝謝@Binyamin Sharet!如果您的建議與我的其他代碼一起工作(請參閱上面的編輯),但有沒有更好的方法來實現這一點?如在,不使「畫布」靜態,也許? – 2012-02-13 20:57:05