简体   繁体   English

在 jframe 中设置按钮的位置不起作用

[英]Setting location of a button in a jframe not working

I have a method that is just adding a button to a JPanel.我有一种方法,它只是向 JPanel 添加一个按钮。 I have a problem however, where there are some properties of this button that I cannot modify.但是,我有一个问题,我无法修改此按钮的某些属性。

setBackground and setLocation method don't affect the button at all. setBackgroundsetLocation方法根本不影响按钮。 I'm trying to move the button to the bottom of the JPannel but nothing seems to happen when I try setting the horizontal alignment or location.我正在尝试将按钮移动到 JPanel 的底部,但是当我尝试设置水平JPannel或位置时似乎没有任何反应。

    public static void initButtons() {
        JButton purchaseButton = new JButton();
        purchaseButton.setText("Proceed to Checkout");
        purchaseButton.setPreferredSize(new Dimension(200,50));
        purchaseButton.setIcon(new ImageIcon("/Users/alecr/eclipse-workspace/MakingPurchases/src/shopping_cart_sprite.png"));
// set location method not working
        purchaseButton.setLocation(25, 600);

        JPanel firstPanel = new JPanel(); 
        firstPanel.setBounds(25, 40, 300, 700);
        firstPanel.setBackground(new java.awt.Color(90,90,100));
        firstPanel.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(3.0f), new Color(70,70,80)));
        frame.add(firstPanel);

        firstPanel.add(purchaseButton);
    }

Instead of using setLocation and setBounds for each component, you should use a proper LayoutManager and let it do the work for you.而不是为每个组件使用setLocationsetBounds ,您应该使用适当的 LayoutManager并让它为您完成工作。 Having hard coded sizes and locations will not allow your application be scalable for different screen sizes and your JFrame will not be able to be resizable, which is not so user-friendly.具有硬编码的大小和位置将不允许您的应用程序针对不同的屏幕大小进行缩放,并且您的JFrame将无法调整大小,这对用户不太友好。

However, if you insist of using absolute-hard coded values (coordinates and dimensions) you must remove the layout manager from the container (a JPanel uses FlowLayout by default), because like I mentioned, it takes care of such things.但是,如果您坚持使用绝对硬编码值(坐标和尺寸),则必须从容器中删除布局管理器( JPanel默认使用 FlowLayout ),因为就像我提到的那样,它会处理这些事情。 In order to do that:为了做到这一点:

JPanel panel = new JPanel(null); //null layout manager allows absolute values

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM