swing在Java中设置按钮的位置
我正在尝试向我的JPanel添加一个按钮并设置位置。我有
buttonOptions.setLocation(1150, 700);
但它将它添加到我的JPanel中间,大约600,20。我试着加上
buttonOptions.setLocation(1150, 700);
在将按钮添加到面板后,但这也无法修复它。我还设置了动作来设置位置,并且可以工作
public class StartScreen extends JPanel implements ActionListener{
ImageIcon imageButtonOptions = new ImageIcon(imageButtonOptionsPath);
ImageIcon imageButtonOptionsHovered = new ImageIcon(imageButtonOptionsHoveredPath);
JButton buttonOptions = new JButton(imageButtonOptions);
public StartScreen() {
buttonOptions.setBorderPainted(false);
buttonOptions.setFocusPainted(false);
buttonOptions.setContentAreaFilled(false);
buttonOptions.addActionListener(this);
buttonOptions.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
buttonOptions.setIcon(imageButtonOptionsHovered);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
buttonOptions.setIcon(imageButtonOptions);
}
});
buttonOptions.setLocation(1150, 700);
add(buttonOptions);
}
# 1 楼答案
您当前的问题是,上面的代码不尊重默认使用的布局管理器
最好的解决方案是使用布局管理器为您进行组件布局,包括嵌套JPanel,每个组件都使用自己的布局。有些人可能建议您使用空布局,在大多数情况下,这样做是错误的,因为它使您的程序很难维护,几乎不可能升级
顺便问一下,你想把按钮放在哪里?在GUI的右下角
另外,与其在JButton中使用鼠标侦听器(这通常是个坏主意),不如在JButton的模型中添加一个ChangeListener。然后你可以很容易地看到鼠标是否在按钮上方
编辑
你说:
然后一种方法是使用GridBagLayout并通过在GridBagConstraints参数中使用适当的常量将按钮放置在右下角
编辑1
例如:
编辑2
现在,图标可以在悬停或“翻滚”时更改。我错了,没有必要听ButtonModel的状态。只需设置按钮图标及其滚动图标,按钮即可为您交换:
# 2 楼答案
JPanel
默认情况下使用FlowLayout
。这将(通常)在水平流中布局组件,默认情况下,从顶部中心开始,一个挨着一个问题是,为什么需要绝对定位