我尝试查看许多文档和教程,但它们似乎都不能一起工作。我只是想为我和我的 friend 正在尝试制作的“游戏”制作一个简单的“主菜单”。当没有背景图像时,我能够移动按钮,并且我只能获取背景图像,但无法移动按钮。 所以我的问题是如何定位 JButton?
这是我的代码和屏幕截图: What my frame looks like
package game;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MainMenu extends JFrame{
private JButton singPlay = new JButton("Single Player");
private JButton twoPlay = new JButton("Two Player");
public MainMenu()
{
JFrame frame = new JFrame("TestTEST");
JPanel panel = new JPanel();
frame.setSize(400,500);
frame.setLocation(700,300);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new JLabel(new ImageIcon("C:\\Users\\Austin\\Pictures\\Landscape.jpg")));
frame.setLayout(new FlowLayout());
frame.add(singPlay);
frame.add(twoPlay);
frame.setSize(399,499);
frame.setSize(400, 500);
}
public static void main(String[] args)
{
new MainMenu();
}
}
最佳答案
So my question is how can I position JButtons?
使用适当的布局管理器。
您将布局管理器设置为 FlowLayout,以便按钮显示在框架的顶部。
也许您希望将按钮置于框架的中心。如果是这样,那么您可以使用 GridbagLayout。
另外,不要使用 setSize()。使用 pack() 方法。最后,将组件添加到框架后,框架应该可见。
所以你的代码可能看起来像这样:
public MainMenu()
{
JPanel panel = new JPanel();
panel.setOpaque(false);
panel.add(singPlay);
panel.add(twoPlay);
JFrame frame = new JFrame("TestTEST");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setContentPane(new JLabel(new ImageIcon("yourfilename.jpg")));
frame.setLayout(new GridBagLayout());
frame.add(panel, new GridBagConstraints());
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
或者您可能希望按钮垂直居中。然后您可以使用垂直的 BoxLayout
。
阅读 Layout Managers 上的 Swing 教程并自己决定什么是合适的。
关于java - 如何在屏幕周围放置 JButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33485220/