Java setBounds不能与JPanel一起使用 [英] Java setBounds not working with JPanel

查看:385
本文介绍了Java setBounds不能与JPanel一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java中做一个小Gui。我正在使用setBounds方法在我的JFrame上设置按钮等的位置,但问题是,当我使用它与JPanel按钮在JFrame上不可见,并且没有JPanel它相当好,看到这两个代码,请帮助我作为我是初学者,面对这些愚蠢的问题。

i am doing a small Gui in java. i am using setBounds methods to set the position of buttons etc on my JFrame , but problem is that when i use it with JPanel button is not visible on JFrame , and without JPanel its quite ok ,, see both the codes and please help me as i am beginner and facing these foolish problems .

这个工作正常

  JFrame jframe = new JFrame("Working Fine");  
  jframe.setLayout(null);  
  JButton jbutton = new JButton("Position Test");  
  jbutton.setBounds(0, 0, 100, 100);  
  jframe.add(jbutton);  
  jframe.setSize(300,300);
  jframe.setVisible(true);

当我向Jpanel添加Button时相同的代码然后它不起作用所以什么不对,请指导我

Same code when i add Button to Jpanel then it does not work so whats wrong , please guide me

  JFrame jframe = new JFrame("causing problem ");
  jframe.setSize(300,300);
  JPanel p = new JPanel();
  jframe.setLayout(null);  
  JButton jbutton = new JButton("Position Test");  
  jbutton.setBounds(0, 0, 100, 100);
  jframe.add(p);
  p.add(jbutton);
  p.setVisible(true);
 //jframe.add(jbutton);  
  jframe.setVisible(true);

请帮我解决这个小问题

推荐答案

问题在于,当您使用绝对定位时, JPanel 组件没有默认大小,因此不会出现。为了让它出现你可以做

The problem is that when you use absolute positioning, the JPanel component has no default size so does not appear. To get it to appear you could do

JFrame frame = new JFrame("No Problem");
JPanel panel = new JPanel() {
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(300, 300);
    };
};
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
JButton button = new JButton("Position Test");
panel.add(button);
frame.add(panel);
frame.pack();
frame.setVisible(true);

来自没有布局管理器


虽然可以做如果没有布局管理器,您应该尽可能使用布局管理器。布局管理器可以更轻松地调整依赖于外观的组件外观,不同的字体大小,容器的大小变化以及不同的区域设置。

Although it is possible to do without a layout manager, you should use a layout manager if at all possible. A layout manager makes it easier to adjust to look-and-feel-dependent component appearances, to different font sizes, to a container's changing size, and to different locales.

布局管理器的选择取决于您希望如何布置组件。

The choice of layout manager will depend on how you wish to lay out the components.

请参阅 A布局管理员视觉指南

这篇关于Java setBounds不能与JPanel一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆