在Java中设置按钮的位置

Mil*_*ime -2 java swing layout-manager null-layout-manager

我正在尝试向我的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);
    }
Run Code Online (Sandbox Code Playgroud)

Mad*_*mer 5

JPanel默认情况下,默认情况下使用a FlowLayout.这将在一个水平流中布置组件(通常),默认情况下,从顶部中心开始,彼此相邻.

问题是,为什么需要绝对定位

  • 将布局管理器设置为null,不仅要求您定位组件,还要提供大小.在Swing中通常不鼓励绝对定位,因为很好的理由(对不起,我在我的膝盖上睡了10个月,所以我不能在mo上做一个例子) (3认同)