我想使用Timer對象動態調整窗口大小,但沒有成功......我在構造函數中設置了面板的首選大小,它很好地設置了窗口的大小,儘管只有一次。程序初始化後,首選大小會發生變化,但窗口大小保持不變。爲什麼?由於構造函數僅初始化一次,因此不受大小更改的影響?如果是這樣,我怎麼能解決這個實時調整窗口?如何使用Timer動態調整框架大小?
我知道這不會解決在開始評論給出的行使問題,所以請忽略:-)
/*
* Exercise 18.15
*
* "(Enlarge and shrink an image) Write an applet that will display a sequence of
* image files in different sizes. Initially, the viewing area for this image has
* a width of 300 and a height of 300. Your program should continuously shrink the
* viewing area by 1 in width and 1 in height until it reaches a width of 50 and
* a height of 50. At that point, the viewing area should continuously enlarge by
* 1 in width and 1 in height until it reaches a width of 300 and a height of 300.
* The viewing area should shrink and enlarge (alternately) to create animation
* for the single image."
*
* Created: 2014.01.07
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Ex_18_15 extends JApplet {
// Main method
public static void main(String[] args) {
JFrame frame = new JFrame();
Ex_18_15 applet = new Ex_18_15();
applet.isStandalone = true;
frame.add(applet);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// Data fields
private boolean isStandalone = false;
private Image image = new ImageIcon("greenguy.png").getImage();
private int xCoordinate = 360;
private int yCoordinate = 300;
private Timer timer = new Timer(20, new TimerListener());
private DrawPanel panel = new DrawPanel();
// Constructor
public Ex_18_15() {
panel.setPreferredSize(new Dimension(xCoordinate, yCoordinate));
add(panel);
timer.start();
}
class DrawPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
class TimerListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if(yCoordinate <= 50) {
yCoordinate++;
xCoordinate++;
}
else if(yCoordinate >= 300) {
yCoordinate--;
xCoordinate--;
}
panel.setPreferredSize(new Dimension(xCoordinate, yCoordinate));
repaint();
}
}
}
難道它通常被延長JFrame的JPanel的不是?我將它填充到JFrame中,以允許它作爲應用程序以及applet運行。這就是'Java編程入門'告訴我如何去做:p 在actionPerformed方法的末尾添加你的代碼對我沒有任何幫助; – hatakeK
到目前爲止(第18章)所有的GUI類都有擴展的JFrame 。也就是說,我只做過非常小的GUI程序。感謝您的洞察! – hatakeK
@hatakeK:請參閱編輯回答。 –