我正在尝试创建一个按钮并将其放置在某个位置,但由于某种原因,它永远不会进入该特定位置。我尝试将其放在一个面板上,使用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());
}
}
}
在将面板添加到框架之前,请使用:panel.setLayout(null); 将面板的默认设置设置为 null然后使用:button.setBounds(300, 300, 300, 300); 将按钮绑定在特定位置
这将起作用..
您需要关闭布局管理器
panel.setLayout(null);
JFrame
默认使用BorderLayout
,默认情况下,除非另有说明,否则组件将添加到BorderLayout.CENTER
位置
在此设置中,组件将被放置在框架的中心并调整其大小以填充它
请记住,每个平台/操作系统呈现的内容都不同,这些差异将更改显示组件所需的空间量,所有这些都将有效处理所有其他组件之间的关系......
您可以考虑更改布局管理器并使用EmptyBorders
和插图/填充的组合来影响组件的位置/大小。 尝试像GridBagLayout
这样的东西,或者如果你喜欢冒险,请查看MigLayout
您需要使用 GUI 程序(几乎在任何平台上)学习的第一课是像素完美布局是一种错觉,有太多的变量会影响内容的呈现方式以及这些变量如何改变各个组件为了正确显示所需的空间量......