我正在创建一个程序,我希望能够“动态”设置它的大小(当程序运行时)。我尝试通过调用包含Canvas.setSize(width, height)
的{{1}}上的JFrame.pack()
和JFrame
来执行此操作。问题是在调用这些方法之后,JFrame会调整大小,以便只显示图标以及关闭和最小化按钮。如何在程序运行时更改大小?我还需要打电话吗?
提前致谢!
答案 0 :(得分:3)
您不应对添加到setSize()
的任何组件使用JFrame
方法。
Swing使用布局管理器。 pack()
方法将调用布局管理器,布局管理器通常会使用组件的首选大小来确定组件的大小/位置。
我猜您的Canvas
类正在进行自定义绘制,因此默认情况下首选大小为零,因此无需显示任何内容。
解决方案是覆盖getPreferredSize()
类中的Canvas
方法以返回适当的大小。
另外,请不要将您的课程称为Canvas
,因为该名称有一个AWT课程,因此会让人感到困惑。如果您使用的是AWT Canvas类,那么您应该使用JPanel
类来进行自定义绘制。
答案 1 :(得分:0)
首先,您应该添加一个侦听器来侦听来自JFrame
的resize-events。
调整JFrame
的大小时,将调用方法componentResized
。然后,您可以获取JFrame
的当前大小,并将其设置为Canvas
的大小。
JFrame component = new JFrame("My Frame");
component.addComponentListener(new ComponentAdapter()
{
public void componentResized(ComponentEvent evt) {
Component c = evt.getComponent();
Dimension dim = c.getSize();
// process the Dimension and set your Canvas size
}
});
答案 2 :(得分:0)
这是SSCCE(短,自包含,正确,兼容,示例):
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class Game extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
// The thread
private Thread thread;
// The Canvas
private Display display;
// Start the game and it's thread
public synchronized void start() {
// Create the thread
thread = new Thread(this, "Game");
// Start the thread
thread.start();
}
// The run method
public void run() {
// SETUP THE JFRAME
// Create the Display
display = new Display(700, 500);
// Set the title of the JFrame
setTitle("Game");
// Set the JFrame to not be resizable
setResizable(false);
// Add the Display to the frame
add(display);
// Pack the JFrame
pack();
// Set the location
setLocationRelativeTo(null);
// Add a window listener
addWindowListener(new WindowAdapter() {
// When the window is being closed
public void windowClosing(WindowEvent e) {
// Stop the game
stop();
}
});
// Show the JFrame
setVisible(true);
try {
// Make the thread wait for two seconds, so that the change is visible
Thread.sleep(2000);
} catch (InterruptedException e) {
// Print the error message
e.printStackTrace();
}
// CHANGE THE SIZE OF THE JFRAME
// Pretend that this is used for changing the size of the game window
// by the user, later in the game. I'm just testing it now, when I don't
// have extremely much code
// Change the size of the Display
display.setPreferredSize(new Dimension(800, 600));
// Pack the JFrame
pack();
}
// Stop the game and it's thread
public synchronized void stop() {
try {
// Join the thread
thread.join();
} catch (InterruptedException e) {
// Print the error message
e.printStackTrace();
}
// Exit the program
System.exit(0);
}
// The main method
public static void main(String[] args) {
// Create and start a new Game
new Game().start();
}
}
谢谢大家!