如何使用JTextField和JButton创建一个带有名称填充功能的菜单?

huangapple go评论79阅读模式
英文:

How to make with JTextField and JButton a menu with name filling functions?

问题

以下是您要求的代码部分的翻译:

private void setLocalPanel() {
    GridBagConstraints c = new GridBagConstraints();
    
    // localButtonsPanel 配置
    localButtonsPanel = new JPanel(new GridLayout(0, 1, 0, 10));
    localButtonsPanel.setOpaque(false);
    
    // nameBox1 配置
    nameBox1 = new JTextField("玩家姓名");
    nameBox1.setBackground(new Color(255, 255, 255));
    nameBox1.setEditable(true);
    c.ipady = 10;
    localButtonsPanel.add(nameBox1, c);

    // nameBox2 配置
    nameBox2 = new JTextField("玩家姓名");
    nameBox2.setBackground(new Color(255, 255, 255));
    nameBox2.setEditable(true);
    localButtonsPanel.add(nameBox2, c);
    
    // + 配置
    extraBtn = new JButton("+");
    extraBtn.setForeground(new Color(255, 255, 255));
    extraBtn.setFont(new Font("Segoe Script", Font.BOLD, 40));
    extraBtn.setOpaque(false);
    extraBtn.setContentAreaFilled(false);
    extraBtn.setBorderPainted(false);
    extraBtn.setFocusPainted(false);
    localButtonsPanel.add(extraBtn, new GridBagConstraints());
    
    c.gridy = 0;
    localPanel.add(localButtonsPanel, c);
    
    // startBtn 配置
    startBtn = new JButton("开始");
    startBtn.setForeground(new Color(255, 255, 255));
    startBtn.setFont(new Font("Segoe Script", Font.BOLD, 40));
    startBtn.setOpaque(false);
    startBtn.setContentAreaFilled(false);
    startBtn.setBorderPainted(false);
    startBtn.setFocusPainted(false);
    c.gridy = 1;
    localPanel.add(startBtn, c);
    
    // localBackBtn 配置
    localBackBtn = new JButton("返回");
    localBackBtn.setForeground(new Color(255, 255, 255));
    localBackBtn.setFont(new Font("Segoe Script", Font.BOLD, 40));
    localBackBtn.setOpaque(false);
    localBackBtn.setContentAreaFilled(false);
    localBackBtn.setBorderPainted(false);
    localBackBtn.setFocusPainted(false);
    c.gridy = 2;
    localPanel.add(localBackBtn, c);
    
    setLocalActions();
}

private void setLocalActions() {
    
    // startBtn 配置
    startBtn.addMouseListener(new MouseAdapter() {
        public void mouseEntered(MouseEvent e) {
            startBtn.setForeground(new Color(200, 210, 10));
            startBtn.setText("> 开始 <");
        }
        
        public void mouseExited(MouseEvent e) {
            startBtn.setForeground(new Color(255, 255, 255));
            startBtn.setText("开始");
        }
        
        public void mouseClicked(MouseEvent e) {
            // nameBox1.getText()
            // nameBox2.getText()
            localPanel.setVisible(false);
            gamePanel.setVisible(true);
        }
    });
    
    // localBackBtn 配置
    localBackBtn.addMouseListener(new MouseAdapter() {
        public void mouseEntered(MouseEvent e) {
            localBackBtn.setForeground(new Color(200, 210, 10));
            localBackBtn.setText("> 返回 <");
        }
        
        public void mouseExited(MouseEvent e) {
            localBackBtn.setForeground(new Color(255, 255, 255));
            localBackBtn.setText("返回");
        }
        
        public void mouseClicked(MouseEvent e) {
            localPanel.setVisible(false);
            playPanel.setVisible(true);
        }
    });
}

请注意,由于我无法在此环境中运行代码,因此无法保证翻译的代码是否完全正确。如果您在使用中遇到任何问题,请随时进行调试和修改。

英文:

So i am trying to make a Panel where the player configures the names of the players in a local board game.
I want them to be able to add players between 2 and 6 so by default i have made the panel show up 2 JTextField boxes for them to add names and under the second one there is a "+" button to add an extra player. But i dont know how to do that and how to perform such action, when the user presses the "+" button a new JTextField pops up for the player to add a new player name.

I am providing the code i am using for this particular panel but it is necessary i can provide the whole code for my window. Any help is appreciated and thanks in advance.

private void setLocalPanel() {
GridBagConstraints c = new GridBagConstraints();
// localButtonsPanel config
localButtonsPanel = new JPanel(new GridLayout(0, 1, 0, 10));
localButtonsPanel.setOpaque(false);
// nameBox1 config
nameBox1 = new JTextField(&quot;Player name&quot;);
nameBox1.setBackground(new Color(255, 255, 255));
nameBox1.setEditable(true);
c.ipady = 10;
localButtonsPanel.add(nameBox1, c);
// nameBox2 config
nameBox2 = new JTextField(&quot;Player name&quot;);
nameBox2.setBackground(new Color(255, 255, 255));
nameBox2.setEditable(true);
localButtonsPanel.add(nameBox2, c);
// + config
extraBtn = new JButton(&quot;+&quot;);
extraBtn.setForeground(new Color(255, 255, 255));
extraBtn.setFont(new Font(&quot;Segoe Script&quot;, Font.BOLD,40));
extraBtn.setOpaque(false);
extraBtn.setContentAreaFilled(false);
extraBtn.setBorderPainted(false);
extraBtn.setFocusPainted(false);
localButtonsPanel.add(extraBtn, new GridBagConstraints());
c.gridy = 0;
localPanel.add(localButtonsPanel, c);
// startBtn config
startBtn = new JButton(&quot;Start&quot;);
startBtn.setForeground(new Color(255, 255, 255));
startBtn.setFont(new Font(&quot;Segoe Script&quot;, Font.BOLD,40));
startBtn.setOpaque(false);
startBtn.setContentAreaFilled(false);
startBtn.setBorderPainted(false);
startBtn.setFocusPainted(false);
c.gridy = 1;
localPanel.add(startBtn, c);
// localBackBtn config
localBackBtn = new JButton(&quot;Back&quot;);
localBackBtn.setForeground(new Color(255, 255, 255));
localBackBtn.setFont(new Font(&quot;Segoe Script&quot;, Font.BOLD,40));
localBackBtn.setOpaque(false);
localBackBtn.setContentAreaFilled(false);
localBackBtn.setBorderPainted(false);
localBackBtn.setFocusPainted(false);
c.gridy = 2;
localPanel.add(localBackBtn, c);
setLocalActions();
}
private void setLocalActions() {
// startBtn config
startBtn.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
startBtn.setForeground(new Color(200, 210, 10));
startBtn.setText(&quot;&gt; Start &lt;&quot;);
}
public void mouseExited(MouseEvent e) {
startBtn.setForeground(new Color(255, 255, 255));
startBtn.setText(&quot;Start&quot;);
}
public void mouseClicked(MouseEvent e) {
// nameBox1.getText()
// nameBox2.getText()
localPanel.setVisible(false);
gamePanel.setVisible(true);
}
});
// localBackBtn config
localBackBtn.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
localBackBtn.setForeground(new Color(200, 210, 10));
localBackBtn.setText(&quot;&gt; Back &lt;&quot;);
}
public void mouseExited(MouseEvent e) {
localBackBtn.setForeground(new Color(255, 255, 255));
localBackBtn.setText(&quot;Back&quot;);
}
public void mouseClicked(MouseEvent e) {
localPanel.setVisible(false);
playPanel.setVisible(true);
}
});
}

PS. the localPanel has a GridBagLayout.

如何使用JTextField和JButton创建一个带有名称填充功能的菜单?

答案1

得分: 1

你需要在 JButton 上添加一个 ActionListener,而不是 MouseListener。请参考如何使用按钮

当点击 + 按钮时,您想要向包含允许用户输入玩家姓名的字段的 JPanel 添加一个新的 JTextField

下面是从您的问题中调整的代码,它在用户点击 + 按钮时添加一个 JTextField。代码后面有关于代码的注释。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;

public class PlayGame implements ActionListener, Runnable {
    // ...(其他代码)

    @Override // java.awt.event.ActionListener
    public void actionPerformed(ActionEvent event) {
        String actionCommand = event.getActionCommand();
        switch (actionCommand) {
            case BACK:
                // 当用户点击“Back”按钮时执行的代码。
                break;
            case PLUS:
                addPlayerNameTextField();
                localButtonsPanel.revalidate();
                localButtonsPanel.repaint();
                if (playerNameTextFields.size() >= MAX_PLAYERS) {
                    ((JButton) event.getSource()).setEnabled(false);
                }
                break;
            case START:
                // 当用户点击“Start”按钮时执行的代码。
                break;
            default:
                System.out.println("Not implemented: " + actionCommand);
        }
    }

    // ...(其他代码)
}

添加 ActionListenerJButton,在用户点击 + 按钮时添加一个新的 JTextField,代码中的注释提供了更多信息。

记住,当在 JButton 上调用 setContentAreaFilled(false) 时,不需要再调用 setOpaque(false)

您可以在 java.awt.Color 类中使用常量 WHITE 来代替 new java.awt.Color(255, 255, 255)

GridLayoutGridBagLayout 并不相同,请参考在容器中布置组件

与您的做法不同,我只是将背景颜色设置为深灰色,而不是使用背景图像。

英文:

You need to add an ActionListener to a JButton and not a MouseListener. Refer to How to Use Buttons.

When the + button is clicked, you want to add a new JTextField to the JPanel that contains the fields that allow the user to enter a player's name.

Here is code, adapted from the code in your question, that adds a JTextField when the user clicks the + button. Notes about the code appear after it.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;

public class PlayGame implements ActionListener, Runnable {
    private static final int  MAX_PLAYERS = 6;
    private static final String  BACK = &quot;Back&quot;;
    private static final String  PLUS = &quot;+&quot;;
    private static final String  START = &quot;Start&quot;;

    private ArrayList&lt;JTextField&gt;  playerNameTextFields;
    private GridBagConstraints  gbc;
    private JFrame  frame;
    private JPanel  localButtonsPanel;

    public PlayGame() {
        playerNameTextFields = new ArrayList&lt;&gt;();
    }

    @Override // java.lang.Runnable
    public void run() {
        showGui();
    }

    @Override // java.awt.event.ActionListener
    public void actionPerformed(ActionEvent event) {
        String actionCommand = event.getActionCommand();
        switch (actionCommand) {
            case BACK:
                // Add code to execute when user clicks &#39;Back&#39; button.
                break;
            case PLUS:
                addPlayerNameTextField();
                localButtonsPanel.revalidate();
                localButtonsPanel.repaint();
                if (playerNameTextFields.size() &gt;= MAX_PLAYERS) {
                    ((JButton) event.getSource()).setEnabled(false);
                }
                break;
            case START:
                // Add code to execute when user clicks &#39;Start&#39; button.
                break;
            default:
                System.out.println(&quot;Not implemented: &quot; + actionCommand);
        }
    }

    private void addPlayerNameTextField() {
        JTextField playerNameTextField = new JTextField(10);
        playerNameTextField.setName(&quot;player&quot; + playerNameTextFields.size());
        playerNameTextFields.add(playerNameTextField);
        gbc.gridy++;
        localButtonsPanel.add(playerNameTextField, gbc);
    }

    private JPanel createLocalPanel() {
        JPanel localPanel = new JPanel(new GridBagLayout());
        localPanel.setOpaque(false);
        GridBagConstraints c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        c.insets.top = 10;
        localButtonsPanel = new JPanel(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = -1;
        gbc.insets.top = 10;
        localButtonsPanel.setPreferredSize(new Dimension(120, 200));
        localButtonsPanel.setOpaque(false);
        addPlayerNameTextField();
        addPlayerNameTextField();
        localPanel.add(localButtonsPanel, c);
        c.gridy = 1;
        JButton extraBtn = new JButton(PLUS);
        extraBtn.setFont(new Font(&quot;Segoe Script&quot;, Font.BOLD,40));
        extraBtn.setForeground(Color.WHITE);
        extraBtn.setContentAreaFilled(false);
        extraBtn.setBorderPainted(false);
        extraBtn.setFocusPainted(false);
        extraBtn.addActionListener(this);
        extraBtn.setToolTipText(&quot;Add another player&quot;);
        localPanel.add(extraBtn, c);
        c.gridy = 2;
        JButton startBtn = new JButton(START);
        startBtn.setForeground(Color.WHITE);
        startBtn.setFont(new Font(&quot;Segoe Script&quot;, Font.BOLD,40));
        startBtn.setContentAreaFilled(false);
        startBtn.setBorderPainted(false);
        startBtn.setFocusPainted(false);
        startBtn.addActionListener(this);
        localPanel.add(startBtn, c);
        JButton localBackBtn = new JButton(BACK);
        localBackBtn.setForeground(Color.WHITE);
        localBackBtn.setFont(new Font(&quot;Segoe Script&quot;, Font.BOLD,40));
        localBackBtn.setContentAreaFilled(false);
        localBackBtn.setBorderPainted(false);
        localBackBtn.setFocusPainted(false);
        localBackBtn.addActionListener(this);
        c.gridy = 3;
        localPanel.add(localBackBtn, c);
        return localPanel;
    }

    private void showGui() {
        frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().setBackground(Color.DARK_GRAY);
        frame.add(createLocalPanel(), BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    /**
     * Start here.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new PlayGame());
    }
}

Note that when you call setContentAreaFilled(false) on a JButton, there is no need to also call setOpaque(false).

Instead of new java.awt.Color(255, 255, 255) you can use the constant WHITE in class java.awt.Color.

GridLayout and GridBagLayout are not the same. Refer to Laying Out Components Within a Container

Rather than use a background image like you have done, I simply set the background color to dark gray.

huangapple
  • 本文由 发表于 2020年8月22日 19:30:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63535652.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定