在Swing中创建多个JButton - 使用此代码

时间:2015-03-11 23:33:07

标签: java swing jbutton

我正在使用Swing开发一个应用程序。我的程序涉及我为字母表中的每个字母都有一个单独的按钮。 当我创建所有这些按钮时,我的代码看起来在程序开始时非常混乱。有没有办法来消除(和缩短)这个?也许有一系列字符和一个for循环?我不太确定怎么样......

final JButton btnA = new JButton("a");
final JButton btnB = new JButton("b");
final JButton btnC = new JButton("c");
final JButton btnD = new JButton("d");
final JButton btnE = new JButton("e");
final JButton btnF = new JButton("f");
final JButton btnG = new JButton("g");
final JButton btnH = new JButton("h");
final JButton btnI = new JButton("i");
final JButton btnJ = new JButton("j");
final JButton btnK = new JButton("k");
final JButton btnL = new JButton("l");
final JButton btnM = new JButton("m");
final JButton btnN = new JButton("n");
final JButton btnO = new JButton("o");
final JButton btnP = new JButton("p");
final JButton btnQ = new JButton("q");
final JButton btnR = new JButton("r");
final JButton btnS = new JButton("u");
final JButton btnT = new JButton("t");
final JButton btnU = new JButton("u");
final JButton btnV = new JButton("v");
final JButton btnW = new JButton("w");
final JButton btnX = new JButton("x");
final JButton btnY = new JButton("y");
final JButton btnZ = new JButton("z");

1 个答案:

答案 0 :(得分:0)

很容易将所有按钮存储在某种数组中并循环显示字母

ArrayList<JButton> btns = new ArrayList<JButton>();

    for(char alpha = 'a'; alpha <= 'z';++alpha)
    {
        btns.add(new JButton(String.valueOf(alpha)));
    }