查看此代码以获取一些想法。它可以根据放置在组件本身工具栏中的操作或框架的菜单项来更改大小。
代码的要点是:
- 在相关组件上设置首选尺寸。
- 获取对顶级容器的引用。
- 最后
pack()
是顶级容器。

import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class GameSize {
// the GUI as seen by the user (without frame)
private JPanel gui = new JPanel(new GridBagLayout());
Action small = new AbstractAction("Small") {
@Override
public void actionPerformed(ActionEvent e) {
setSize(400, 100);
}
};
Action large = new AbstractAction("Large") {
@Override
public void actionPerformed(ActionEvent e) {
setSize(600, 200);
}
};
private final void setSize(int w, int h) {
gui.setPreferredSize(new Dimension(w, h));
Container c = gui.getTopLevelAncestor();
if (c instanceof JFrame) {
JFrame f = (JFrame) c;
f.pack();
}
}
GameSize() {
JToolBar tb = new JToolBar("Size");
for (Action action : getActions()) {
tb.add(action);
}
gui.add(tb);
gui.setPreferredSize(new Dimension(200, 100));
gui.setBackground(Color.RED);
}
/*
* @return the Actions
*/
public Action[] getActions() {
Action[] actions = {small, large};
return actions;
}
/**
* @return the gui
*/
public JPanel getGui() {
return gui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
GameSize gs = new GameSize();
JFrame f = new JFrame("Demo");
f.add(gs.getGui());
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
JMenuBar menuBar = new JMenuBar();
f.setJMenuBar(menuBar);
JMenu size = new JMenu("Size");
menuBar.add(size);
for (Action action : gs.getActions()) {
size.add(action);
}
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}