我似乎无法将按钮的自定义位置设置为 JPanel . 它总是在左上角添加按钮,然后继续向右 . 我也有一个背景图像,这使事情变得更加困难 . 框架如下所示:imageshack.com/a/img838/3240/ez6l.png我的代码是:
private JFrame mainframe = new JFrame();
public void main()
{
mainframe.setLocation(400, 150);
mainframe.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
mainframe.setVisible(true);
mainframe.setSize(800, 600);
JPanel menupanel2 = new JPanel();
JPanel MusicPanel = new JPanel();
mainframe.setResizable(false);
mainframe.setContentPane(new JLabel(new ImageIcon("src/res/LED0.png")));
mainframe.setLayout(new FlowLayout());
menupanel2.setBackground(Color.black);
JButton PlayButton = new JButton("Play");
PlayButton.setBackground(Color.green);
JButton highscores = new JButton("Highscores");
highscores.setBackground(Color.MAGENTA);
JButton CustomButton = new JButton("Custom Shapes");
CustomButton.setBackground(Color.orange);
JButton HelpButton = new JButton("Help");
HelpButton.setBackground(Color.red);
JButton AboutButton = new JButton("About");
AboutButton.setBackground(Color.yellow);
final JButton MusicButton = new JButton("music");
MusicButton.setPreferredSize(new Dimension(50, 50));
CustomButton.setPreferredSize(new Dimension(140, 40));
PlayButton.setPreferredSize(new Dimension(140, 40));
HelpButton.setPreferredSize(new Dimension(140, 40));
AboutButton.setPreferredSize(new Dimension(140, 40));
highscores.setPreferredSize(new Dimension(140, 40));
mainframe.add(menupanel2, BorderLayout.NORTH);
mainframe.add(MusicPanel, BorderLayout.SOUTH);
menupanel2.add(PlayButton, BorderLayout.NORTH);
menupanel2.add(CustomButton, BorderLayout.NORTH);
menupanel2.add(HelpButton, BorderLayout.NORTH);
menupanel2.add(highscores, BorderLayout.NORTH);
menupanel2.add(AboutButton, BorderLayout.NORTH);
MusicPanel.add(MusicButton, BorderLayout.SOUTH);
我想将按钮"MusicButton "添加到右下角/中间/或左侧 . 如果您有自定义方式可以在 JPanel 中订购JButton,请分享 . 谢谢
3 回答
如果我错了,不要开始扔西红柿,但....
您的主机布局是FlowLayout
您指定将MusicPanel设置为为FlowLayout设置的JFrame上的BorderLayout位置 .
通过这样做,您无法真正预测GUI在编译时的外观 . 这可能是您的问题的根源 .
另外,在旁注中,指南针参考不再是在BorderLayout中设置位置的首选方法 . http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html
我会尝试将您的JFrame布局设置为BorderLayout,将您的MusicPanel设置为JFrame的PAGE_END(SOUTH)位置 . 然后,使用MusicPanel上的GridBag布局并将JButton定位到LAST_LINE_END位置 .
让我知道这是如何工作的!
该MCVE使用标准的JSE布局,插图和边框来创建上面提到的GUI . GUI中空白区域的技巧在源代码中被注释为
// 1
,这可以通过简单(但更长)的指令// Adjust numbers as required
来解释 .将它拖得更宽更高,看看:
UI的额外宽度在每个按钮之间大致相等 . 'black'按钮坚持UI的RHS .
在顶行按钮和底部按钮之间显示额外高度 .
我想你应该对java中的布局做一些研究 . 在你的代码的最后一部分制作
frame.setVisible(true);
是一个好习惯 . 这是我的解决方案,希望它可以帮到你 .这是操作效果 .