我有这个基本的Java应用程序,巫婆dim_x
和dim_y
代表窗口的尺寸和它内部的画布。如何在用户更改窗口大小时更改这些值,以便画布上绘制的内容相应缩小/扩展?
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
}
}
编辑:
按照Binyamin的回答我尝试添加这个有效,但是有更好的方法吗?如同,没有让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
}
}
答案 0 :(得分:7)
添加组件侦听器,并实现componentResized
。 Look here
frame.addComponentListener(new ComponentListener(){
@Override
public void componentResized(ComponentEvent e) {
//Get size of frame and do cool stuff with it
}
}
答案 1 :(得分:4)
Canvas
或JComponent
代替JPanel
。paint()
或paintComponent()
,您只需getWidth()
/ getHeight()
即可发现呈现区域的大小答案 2 :(得分:1)
根据我的经验,当AWT Canvas嵌套在JPanel中时,Canvas的paint()方法在窗口展开时调用,而不是在缩小窗口时调用。因此,Canvas可以成长但不会缩减。我用JComponent的子类化重构了子类化的Canvas。