簡體   English   中英

如何在 Java GUI Swing 中制作更多按鈕

[英]how to make more buttons in java GUI swing

我想使用java swing制作兩個按鈕,一個將+25加到100,初始值,另一個將+10加到100,始終是初始值:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class GUI implements ActionListener {
    private int button1 = 100;
    private int button2 = 100;
    private JLabel label;
    private JFrame frame;
    private JPanel panel;
    
    
    public GUI() {
        
        JFrame frame = new JFrame();
        JPanel panel1 = new JPanel();
        JPanel panel2 = new JPanel();
        // Bottone & etichetta per il player 1
        JButton button = new JButton("add 25");
        panel1.add(button);
        button.addActionListener(this);
        label = new JLabel("initial value: 100");
        panel1.add(label);
        // Bottone & etichetta per il player 1
        JButton button1 = new JButton("add 10");
        panel2.add(button1);
        button1.addActionListener(this);
        label = new JLabel("initial value: 100");
        panel1.add(label);
        
        
        // Impostazioni della finestra
        panel1.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
        panel1.setLayout(new GridLayout(0, 1));
    
        frame.add(panel1, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("GUI");
        frame.pack();
        frame.setVisible(true);
        // Impostazioni della finestra
     }  
        public static void main(String args[]) {
            new GUI();
       
        
    }
        @Override
        public void actionPerformed(ActionEvent e) {
            button1 = button1 + 25;
             label.setText("Value: " + button1);
        }
        public void actionPerformed2(ActionEvent e) {
            button2 = button2 + 10;
            label.setText("Value: " + button2);
        }
    
}

正如您所看到的,它應該創建兩個按鈕,這是我最初收到的輸出:

(button) add 25
(label) initial value: 100
(label) initial value: 100

https://i.stack.imgur.com/1MSHz.png

在我點擊它之后,它只會在第一個增加 25:

(button) add 25
(label) initial value: 125
(label) initial value: 100

創建 Swing GUI 時,最好將數據模型與 GUI 視圖分開。 這種分離使得對模型進行編碼和對視圖進行編碼變得更加容易。 控制器更新模型,進而更新視圖。

這是我為說明這個模型/視圖/控制器模式而制作的 GUI。

增量圖形用戶界面

我做的第一件事是定義一些字段和一個數組。

private int[] values;

private int startValue;
private int currentValue;

startValue是起始值(100), currentValue是當前值(圖中為 205), values是一個int數組,其中包含值 10 和 25。

這是設置這些值的代碼。 我在類的構造函數中設置了這些值,因此它們會在其他任何事情發生之前設置。

public IncrementGUI() {
    this.startValue = 100;
    this.currentValue = startValue;
    this.values = new int[] { 10, 25 };
}

由於我將值放在一個int數組中,如果我想添加另一個值,我所要做的就是將值添加到values數組中。

現在我們已經建立了模型,讓我們從視圖開始。 這是我的主要方法。

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            IncrementGUI inc = new IncrementGUI();
            inc.createJFrame();
        }
    });
}

我調用SwingUtilities invokeLater方法來確保我創建和執行的 Swing 組件是在Event Dispatch Thread上創建和執行的。 這可以防止我們在 GUI 上遇到線程問題。

當我實例化類時,模型字段在構造函數中設置,然后創建 GUI。

這是我編寫的用於創建 JFrame 的方法。

private void createJFrame() {
    JFrame frame = new JFrame("Increment Value");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    frame.add(createValuePanel(), 
            BorderLayout.BEFORE_FIRST_LINE);
    frame.add(createButtonPanel(), BorderLayout.CENTER);
    
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);
}

JFrame 方法必須按特定順序調用。 這是我用於大多數 Swing 應用程序的順序。

setDefaultCloseOperation方法允許我在左鍵單擊右上角的 X 按鈕時關閉應用程序。 pack方法將 Swing 組件“打包”到與 Swing 組件大小一致的盡可能小的JFrame setLocationByPlatform方法設置JFrame在屏幕上的位置與平台操作系統一致。 最后, setVisible方法使JFrame可見。

我們創建了兩個JPanels ,一個用於保存“Value” JLabelJTextField ,另一個用於保存JButtons 我們這樣做是因為我想使用兩個不同的Swing 布局管理器來布局 Swing 組件。

JFrame默認有一個BorderLayout 我將值JPanel放在第一行(頂部)之前,並將按鈕JPanel放在中間。

接下來,我在createValuePanel方法中對值JPanel的詳細信息進行了編碼。

private JPanel createValuePanel() {
    JPanel panel = new JPanel(new FlowLayout());
    
    JLabel label = new JLabel("Value: ");
    panel.add(label);
    
    valueField = new JTextField(10);
    valueField.setEditable(false);
    setValueField(currentValue);
    panel.add(valueField);
    
    return panel;
}

public void setValueField(int value) {
    valueField.setText(NF.format(value));
}

我使用JTextField來保存當前值。 我使它不可編輯,因此用戶無法更改該值。

我將setValueField方法編寫為一個單獨的方法,因為我們將在ActionListeneractionPerformed方法中使用此方法。

我們使用FlowLayout是因為我希望 Swing 組件從左到右流動。

接下來,我在createButtonPanel方法中編寫了按鈕JPanel的詳細信息。

private JPanel createButtonPanel() {
    JPanel panel = new JPanel(new GridLayout(0, 1, 5, 5));
    panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    
    for (int index = 0; index < values.length; index++) {
        JButton button = new JButton("Add " + values[index]);
        button.addActionListener(this);
        button.setActionCommand(Integer.toString(values[index]));
        panel.add(button);
    }
    
    return panel;
}

我用了一個GridLayout保持的單個列JButtons 我在帶有空邊框的JButtons周圍放置了一些空白空間,以使 GUI 更具視覺吸引力。

因為我在 for 循環中創建JButtons ,所以我創建了與values數組中的values一樣多的JButtons 這樣,當您向values數組添加一個值時,將創建一個新的 JButton。

JButton可以保存操作命令String以及顯示文本。 我們使用此操作命令String actionPerformed量值傳遞給actionPerformed方法。

最后,我編寫了actionPerformed方法。 這很簡單。 我從JButton獲取增量值,增加當前值,並在JTextField顯示當前值。

@Override
public void actionPerformed(ActionEvent event) {
    int value = Integer.valueOf(event.getActionCommand());
    currentValue += value;
    setValueField(currentValue);
}

這是整個可運行示例。 我希望這個解釋可以幫助您創建更復雜的 Swing GUI。

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class IncrementGUI implements ActionListener {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                IncrementGUI inc = new IncrementGUI();
                inc.createJFrame();
            }
        });
    }
    
    private static NumberFormat NF = 
            NumberFormat.getIntegerInstance();
    
    private int[] values;
    
    private int startValue;
    private int currentValue;
    
    private JTextField valueField;
    
    public IncrementGUI() {
        this.startValue = 100;
        this.currentValue = startValue;
        this.values = new int[] { 10, 25 };
    }
    
    private void createJFrame() {
        JFrame frame = new JFrame("Increment Value");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        frame.add(createValuePanel(), 
                BorderLayout.BEFORE_FIRST_LINE);
        frame.add(createButtonPanel(), BorderLayout.CENTER);
        
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
    
    private JPanel createValuePanel() {
        JPanel panel = new JPanel(new FlowLayout());
        
        JLabel label = new JLabel("Value: ");
        panel.add(label);
        
        valueField = new JTextField(10);
        valueField.setEditable(false);
        setValueField(currentValue);
        panel.add(valueField);
        
        return panel;
    }
    
    public void setValueField(int value) {
        valueField.setText(NF.format(value));
    }
    
    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new GridLayout(0, 1, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        for (int index = 0; index < values.length; index++) {
            JButton button = new JButton("Add " + values[index]);
            button.addActionListener(this);
            button.setActionCommand(Integer.toString(values[index]));
            panel.add(button);
        }
        
        return panel;
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        int value = Integer.valueOf(event.getActionCommand());
        currentValue += value;
        setValueField(currentValue);
    }

}

您沒有將 panel2 添加到 JFrame 中,盡管我建議將兩個按鈕都放在一個 JPanel 上。

private int button1 = 100;
...

public GUI() 
{
    ...
    JButton button1 = new JButton("add 10");

不要在類中使用相同的變量名。 具有相同名稱的局部變量和實例變量非常令人困惑。 變量名應該是描述性的。 所以也許你有這樣的變量:

private int value10 = 100;
...

public GUI() 
{
    ...
    JButton button10 = new JButton("add 10");

表示 button10 按鈕用於增加 value10 的值。

但它應該在第二個上加 10

public void actionPerformed2(ActionEvent e) {

您不能僅僅通過在方法名稱的末尾添加“2”來組成方法。 該代碼永遠不會被調用。 如果您有兩個按鈕,那么您需要兩個 ActionListener。

最簡單的方法是使用 lamda:

button25.addActionListener((e) ->
{
    value25 += 25;
    label.setText("Value: " + value25);
}

button10.addActionListener((e) ->
{
    value10 += 10;
    label.setText("Value: " + value10);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM