亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何安排 Java GUI 按鈕?

如何安排 Java GUI 按鈕?

小怪獸愛吃肉 2023-02-23 16:51:25
我需要按特定順序排列我的按鈕,但無論我做什么修改,它只會改變按鈕的大小而不是位置。對不起,如果這是一個簡單的問題,這是我的第一個 Java 類,我無法理解如何安排內容和事件處理。public class SwingCalculator extends JFrame {    private JButton jbtReset;    private JButton jbtAdd;    private JButton jbtSubtract;    private double TEMP;    private double SolveTEMP;    private JTextField jtfResult;    Boolean addBool = false;    Boolean subBool = false;    String display = "";    public SwingCalculator()     {        JPanel p1 = new JPanel();        p1.setLayout(new GridLayout(4, 3));        p1.add(jbtReset = new JButton("Reset"));        JPanel p2 = new JPanel();        p2.setLayout(new FlowLayout());        p2.add(jtfResult = new JTextField(10));        jtfResult.setEditable(true);        JPanel p3 = new JPanel();        p3.setLayout(new GridLayout(5, 1));        p3.add(jbtAdd = new JButton("+"));        p3.add(jbtSubtract = new JButton("-"));        JPanel p = new JPanel();        p.setLayout(new GridLayout());        p.add(p2);        p.add(p1);        p.add(p3);        add(p);        jbtAdd.addActionListener(new ListenToAdd());        jbtSubtract.addActionListener(new ListenToSubtract());        jbtReset.addActionListener(new ListenToReset());    } //JavaCaluclator()    class ListenToReset implements ActionListener {        public void actionPerformed(ActionEvent e) {            //display = jtfResult.getText();            jtfResult.setText("");            addBool = false;            subBool = false;            TEMP = 0;            SolveTEMP = 0;        }    }    class ListenToAdd implements ActionListener {        public void actionPerformed(ActionEvent e) {            TEMP = Double.parseDouble(jtfResult.getText());            jtfResult.setText("");            addBool = true;            SolveTEMP = SolveTEMP + TEMP;            jtfResult.setText(  Double.toString(SolveTEMP));            addBool = false;            subBool = false;        }    }我的結果:預期結果:
查看完整描述

1 回答

?
滄海一幻覺

TA貢獻1824條經驗 獲得超5個贊

您可以使用GridBagLayout各種選項。


例如:


GridBagLayout grid = new GridBagLayout();  

GridBagConstraints gbc = new GridBagConstraints();  

setLayout(grid); 

//add TF

gbc.gridx=1;

gbc.gridy=0;

this.add(new JTextField(10),gbc);

gbc.gridx=0;

gbc.gridy=1;

this.add(new JButton("+"),gbc);

gbc.gridx=1;

this.add(new JButton("-"),gbc);

gbc.gridx=2;

this.add(new JButton("Reset"),gbc);


//also for another display (first TF will be on the same x as - Button) 

//(and maybe you want TF to cover the space for all 3 Button +,-,Reset)

//you could add 2 panels one over other (x=0 : y=0,y=1), place TF on P1 and all Buttons on P2



查看完整回答
反對 回復 2023-02-23
  • 1 回答
  • 0 關注
  • 98 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號