【发布时间】:2014-12-01 19:08:02
【问题描述】:
我有一个包含按钮的 JDesktopPane。当我点击它时,我希望出现一个自定义的 JOptionPane,我在其中添加了一个 JLabel 和一个 JTable。
问题是我在 JOptionPane 中没有得到任何东西
这是我的代码:
class Viewer extends JPanel{
public Viewer(){
JLabel l = new JLabel("Hi");
JTable t = new JTable(2,2);
JPanel p = new JPanel();
p.add(l,BorderLayout.NORTH);
p.add(t,BorderLayout.CENTER);
}
}
public class JOptionPanesWithJPanel extends JFrame{
JPanel desktoppane;
public JOptionPanesWithJPanel(){
desktoppane = new JPanel();
int inset = 50;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(inset, inset, screenSize.width - inset*2, screenSize.height - inset*2);
JPanel butPanel = new JPanel();
JButton but = new JButton("click");
butPanel.setVisible(true);
butPanel.add(but);
desktoppane.add(butPanel);
getContentPane().add(desktoppane, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
but.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
Viewer v = new Viewer();
//make JOptionPane resisable
UIManager.put("OptionPane.minimumSize",new Dimension(150,150));
JOptionPane.showMessageDialog(null, v, null, JOptionPane.PLAIN_MESSAGE);
}
});
}
public static void main(String[] args) {
for(javax.swing.UIManager.LookAndFeelInfo lookAndFeelInfo : javax.swing.UIManager.getInstalledLookAndFeels()){
if("Windows".equals(lookAndFeelInfo.getName())){
try {
javax.swing.UIManager.setLookAndFeel(lookAndFeelInfo.getClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
System.out.println(ex);
}
break;
}
}
JOptionPanesWithJPanel j = new JOptionPanesWithJPanel();
}
}
我应该怎么做才能在 JOptionPane 中显示面板?提前谢谢你。
PS: 我使用 JoptionPane 的原因是禁止用户单击 JDesktopPane 中的其他任何位置(以及按钮),除非他关闭当前窗口。
【问题讨论】:
-
您从未在查看器构造函数中添加
p。p也没有 BorderLayout。您的约束没有影响 -
真的!我忘了添加它!我可以用什么来代替 BorderLayout...?
-
把
p的布局设置为BorderLayout怎么样? -
p.setLayout(new BorderLayout())
-
我不会搞砸 UIManager 和最小尺寸属性,因为这也会影响所有未来的 JOptionPanes...
标签: java swing jpanel joptionpane