设置JButton的位置永远不会有效?

时间:2014-11-24 18:47:57

标签: java location jbutton

我试图创建一个按钮并将其放在某个位置,但由于某种原因它永远不会进入该特定位置。我尝试使用setBounds将它放在面板上,使用setLocation ......但它似乎没有工作......

我在另一个文件中运行此文件。

public class Inventory extends JPanel
{
   private final static int frameWidth = 200;
   private final static int frameHeight = 500;
   private final static int screenLocationX = 100;
   private final static int screenLocationY = 50;
   private Panel panel;
   private JFrame frame;
   private JPanel jpanel;

public Inventory()
{   
   panel = new Panel();
   frame = new JFrame();

   JButton button = new JButton("Add Gem");
   button.addActionListener(new Listener());
   button.setPreferredSize(new Dimension(frameWidth,50));
   // button.setLocation(0,400);
   // button.setBounds(0,400,frameWidth,50);

   panel.setVisible(true);

   frame.setContentPane(panel);
   frame.add(button);

   frame.setVisible(true);
   frame.setSize(frameWidth, frameHeight);
   frame.setLocation(screenLocationX, screenLocationY);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setResizable(false);
}
private class Listener implements ActionListener
{
   public void actionPerformed(ActionEvent e)
   {

      panel.addImage(new Gems());

   }
}
}

3 个答案:

答案 0 :(得分:1)

在将面板添加到框架之前使用: panel.setLayout(NULL); //将panel的默认设置设置为null 然后使用: button.setBounds(300,300,300,300); //在特定位置绑定按钮

这可行..

答案 1 :(得分:0)

您需要关闭LayoutManager

panel.setLayout(null);

答案 2 :(得分:0)

JFrame默认使用BorderLayout,默认情况下,组件会添加到BorderLayout.CENTER位置,除非另有说明

在此设置中,组件将放置在框架的中心并调整大小以填充它

请记住,每个平台/操作系统都会以不同的方式呈现内容,这些差异将改变显示组件所需的空间量,所有这些都将有效地解决所有其他组件之间的关系......

您考虑更改布局管理器并使用EmptyBorders和insets / padding的组合来影响组件的位置/大小。尝试使用GridBagLayout或冒险,查看MigLayout

使用GUI程序(几乎在任何平台上)需要学习的第一课是像素完美布局是一种幻觉,有太多变量会影响内容的呈现方式以及这些变量如何改变空间量需要单独的组件才能正确显示...