问题描述
我有两个Swing组件:
JDialog - > JPanel
I have two Swing components:JDialog -> JPanel
我想用JPanel填充JDialog中的所有空间。默认设置正常。
我可以更改对话框的大小,并正确更改JPanel的大小。
I want to fill all space in the JDialog with the JPanel. Default settings work fine.I can change size of the dialog and size of JPanel is changed correctly.
但是当我点击最大化图标时,内部JPanel会被冻结,直到窗口最大化。
But when I click "maximize" icon then inner JPanel is freezed until window will be maximized.
OS X版本10;
Java版本1.7。
OS X version 10;
Java version 1.7.
代码示例:
final JDialog dialog = new JDialog(mainFrame, true);
dialog.setSize(new Dimension(800, 600));
dialog.setLocationRelativeTo(null);
final JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 14));
dialog.add(panel);
dialog.show();
是否存在解决此问题的方法?
Does exist a way to fix this behavior?
推荐答案
在调整对话框大小或最大化时,以下完整示例不会冻结。以下是一些需要注意的事项:
The following complete example does not freeze when the dialog is resized or maximized. Here are a few things to note:
-
JPanel的默认布局
;为了比较,我将框架的布局设置为相同。
The default layout of a
JPanel
isFlowLayout
; for comparison, I've set the frame's layout the same.
调用 pack()
原因这个窗口
的大小应该适合其子组件的首选大小和布局。由于对话框只包含一个空的 Jpanel
,我已经覆盖了以显示效果。
Invoking pack()
"Causes this Window
to be sized to fit the preferred size and layouts of its subcomponents." Since the dialog contains only an empty Jpanel
, I've overridden getPreferredSize()
to show the effect.
应构建和操作Swing GUI对象仅限 。
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* @see https://stackoverflow.com/a/22450263/230513
*/
public class Test {
private void display() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(new JLabel("Frame"));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
JDialog dialog = new JDialog(frame, true);
final JPanel panel = new JPanel(){
@Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
};
panel.add(new JLabel("Dialog"));
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 14));
dialog.add(panel);
dialog.pack();
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Test().display();
}
});
}
}
这篇关于在OS X上调整JPanel的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!