从 JPanel 创建自定义对话框
create a custom dialog from a JPanel
我想从 JPanel 创建一个对话框,我遇到的问题是 Dialog class 和 JOptionPane class 是我阅读的主要对话框 classes关于使用模板(例如您的“文本”,然后是取消和确认按钮)。我想创建一个包含我的 JPanel 的自定义对话框。我基本上想在屏幕上显示整个 JPanel,而无需创建新的 JFrame 或重新使用现有的 JFrame。
谢谢!
在大多数情况下 JOptionPane
非常灵活,例如,从像...这样简单的东西开始
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
setBorder(new EmptyBorder(32, 32, 32, 32));
JLabel label = new JLabel("Hello world");
label.setFont(label.getFont().deriveFont(32f));
add(label);
}
}
我能做到...
JOptionPane.showMessageDialog(null, new TestPane());
啊,等等,你可能不想要图标,所以你可以做类似...
JOptionPane.showMessageDialog(null, new TestPane(), "Hello", JOptionPane.PLAIN_MESSAGE);
...你是什么意思,你想要自定义选项?!好吧,好吧,JOptionPane
也能搞定...
String[] options = new String[]{
"options",
"your",
"are",
"These"
};
int result = JOptionPane.showOptionDialog(null, new TestPane(), "Hello", JOptionPane.NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[3]);
if (result >= 0) {
System.out.println(options[result]);
}
现在,稍加思考和努力,您还可以:
- Close a
JOptionPane
automatically after a specified timeout (and another example)
- Control the button state, based in input from the dialog (and a slightly improved example)
JOptionPane
是一个不错的选择,但它不是您唯一的选择。您可以推出自己的“工厂”(如 JOptionPane
)来完成构建 JDialog
、生成 buttons/options 和处理用户输入(在这些操作上)[=25] 的所有繁重工作=]
我想从 JPanel 创建一个对话框,我遇到的问题是 Dialog class 和 JOptionPane class 是我阅读的主要对话框 classes关于使用模板(例如您的“文本”,然后是取消和确认按钮)。我想创建一个包含我的 JPanel 的自定义对话框。我基本上想在屏幕上显示整个 JPanel,而无需创建新的 JFrame 或重新使用现有的 JFrame。
谢谢!
在大多数情况下 JOptionPane
非常灵活,例如,从像...这样简单的东西开始
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
setBorder(new EmptyBorder(32, 32, 32, 32));
JLabel label = new JLabel("Hello world");
label.setFont(label.getFont().deriveFont(32f));
add(label);
}
}
我能做到...
JOptionPane.showMessageDialog(null, new TestPane());
啊,等等,你可能不想要图标,所以你可以做类似...
JOptionPane.showMessageDialog(null, new TestPane(), "Hello", JOptionPane.PLAIN_MESSAGE);
...你是什么意思,你想要自定义选项?!好吧,好吧,JOptionPane
也能搞定...
String[] options = new String[]{
"options",
"your",
"are",
"These"
};
int result = JOptionPane.showOptionDialog(null, new TestPane(), "Hello", JOptionPane.NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[3]);
if (result >= 0) {
System.out.println(options[result]);
}
现在,稍加思考和努力,您还可以:
- Close a
JOptionPane
automatically after a specified timeout (and another example) - Control the button state, based in input from the dialog (and a slightly improved example)
JOptionPane
是一个不错的选择,但它不是您唯一的选择。您可以推出自己的“工厂”(如 JOptionPane
)来完成构建 JDialog
、生成 buttons/options 和处理用户输入(在这些操作上)[=25] 的所有繁重工作=]