有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing在Java中使用矩阵和JButton设计扑克UI

我必须用Java设计一个用户界面,在这个界面上,texas hold'em的所有可能的手的组合都显示在屏幕上,因此: Something Like this

我知道我基本上需要169个正方形(Jbuttons)或13x13“表”。所以我遇到了两个问题,我可以设计一个界面,我有这169个单独的按钮,但我如何分配它们?我知道我需要两个for循环(一个在另一个内部)来生成列表,但我无法掌握如何生成。 我的一个朋友建议我使用矩阵,而不是使用for循环创建按钮

这是我的基本想法,但我想改变颜色的按钮,当我按下他们,并发送任何写在他们的JText

非常感谢您抽出时间阅读本文

package modelo;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class RangoImpreso implements ActionListener{

    JButton []ArrayButton = new JButton[169];//Buttons
    JPanel jp1;
    JLabel jl1, jl2;

    private RangoImpreso ()
    {

        JFrame frMain = new JFrame("Rango Pre-Flop");
        frMain.setLayout(new BorderLayout(10, 20));

        jl1 = new JLabel();    //jlabel that outputs number pressed    
        jl1.setText("Aquí ira el numero que se pulse");

        mostrarBot();

        frMain.add(jl1, BorderLayout.NORTH);
        frMain.add(jp1, BorderLayout.SOUTH);

        frMain.setSize(600, 600);
        frMain.setLocation(700, 300);
        frMain.setVisible(true);
        frMain.setResizable(false);
        frMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        
    }

    public void mostrarBot() //method where the Jpanel is
    {
        jp1 = new JPanel(new GridLayout(13, 13, 0, 0));

        for(int i=ArrayButton.length-1; i>=0; i--) //create buttons, add properties
        {
            ArrayButton[i] = new JButton(""+(i+1));
            jp1.add(ArrayButton[i]);
            ArrayButton[i].setMargin(new Insets(0, 0, 0, 0));
            ArrayButton[i].addActionListener(this);
        }
    }

    public static void main(String[] args) 
    {        
        RangoImpreso trin = new RangoImpreso();       
    }

    @Override
    public void actionPerformed(ActionEvent e) //Use jlabel to show button pressed
    {        
        jl1.setText(e.getActionCommand());
    }
}

共 (1) 个答案

  1. # 1 楼答案

    以下是创建按钮所需的两个for循环

    • o=外环的索引
    • i=内环的索引

    这两个按钮的计数范围都是从0到12,因此它将创建13*13个按钮

    for(int o = 0; o < 13; o++) {
        for(int i = 0; i < 13; i++) {
            //Create you buttons
            JButton btn = new JButton();
            //Add Handlers to change color and send text to textfield here...
        }
    }