我有一個方法,就是向 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
和。硬編碼尺寸和位置將不允許您的應用程序針對不同的屏幕尺寸進行擴展,并且您將無法調整大小,這對用戶來說不太友好。setBounds
JFrame
但是,如果您堅持使用絕對硬編碼值(坐標和尺寸),則必須從容器中刪除布局管理器(默認情況下JPanel
?使用 FlowLayout),因為就像我提到的,它會處理這些事情。為了做到這一點:
JPanel panel = new JPanel(null); //null layout manager allows absolute values
添加回答
舉報
0/150
提交
取消