为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

梦里花落0921 2023-09-20 16:32:51
我有一个方法,就是向 JPanel 添加一个按钮。但是,我有一个问题,该按钮的某些属性我无法修改。setBackground和setLocation方法根本不影响按钮。我试图将按钮移动到底部,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);    }
查看完整描述

1 回答

?
撒科打诨

TA贡献1934条经验 获得超2个赞

您应该使用适当的 LayoutManager并让它为您完成工作,而不是为每个组件使用setLocation和。硬编码尺寸和位置将不允许您的应用程序针对不同的屏幕尺寸进行扩展,并且您将无法调整大小,这对用户来说不太友好。setBoundsJFrame

但是,如果您坚持使用绝对硬编码值(坐标和尺寸),则必须从容器中删除布局管理器(默认情况下JPanel 使用 FlowLayout),因为就像我提到的,它会处理这些事情。为了做到这一点:

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


查看完整回答
反对 回复 2023-09-20
  • 1 回答
  • 0 关注
  • 44 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信