简体   繁体   English

如何按首选顺序设置Jbutton?

[英]How can I set the Jbuttons in a preferred order?

I have a grid of 30 buttons, and I want to have it from left to right then goes down, right to left, down again left to right. 我有一个由30个按钮组成的网格,我想从左到右依次放下,然后从右到左向下,再从左到右向下。 Basically the numbering would be as follow: 基本上编号如下:

1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10

20 19 18 17 16 15 14 13 12 11 20 19 18 17 16 15 14 13 12 11

21 22 23 24 25 26 27 28 29 30 21 22 23 24 25 26 27 28 29 30

So if I have a piece on the button 10 and I instruct it to move up 2 bits it would land on 12 not 19. 因此,如果我在按钮10上放了一块,并指示它向上移动2位,它将落在12而不是19上。

Below is my Code: 以下是我的代码:

//Creates the button using the loop, adds it into the panel and frame.
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(3,10));
        JButton [] buttons = new JButton[30];
        for(int i=0;i<30;i++){
            buttons[i] = new JButton("label" + i);
            buttons[i].setBackground(Color.white);

        //Puts the player 1 piece on button 1,3,5,7,9 and player 2 piece on button 2,4,6,8,10
           if (i < 10) {
           if (i%2 == 0) {
             buttons[i].setIcon(piece1);
           } else {
             buttons[i].setIcon(piece2);
           }
        }
        panel.add(buttons[i]);
                    }

        frame.add(panel, BorderLayout.CENTER);

For example, 例如,

  for (int i = 1; i <= buttons.length; i++) { // avoid magic numbers

     int btnNumber = (i > 10 && i <= 20) ? (31 - i) : i;

     System.out.printf("i = %d, btnNumber = %d%n", i, btnNumber);
     buttons[btnNumber - 1] = new JButton("label " + btnNumber);
     buttons[btnNumber - 1].setBackground(Color.white);
     panel.add(buttons[btnNumber - 1]);
  }

Or the logic part can be written, 或者可以写逻辑部分,

     if (i > 10 && i <= 20) {
        btnNumber = 31 - i;
     } else {
        btnNumber = i;
     }

But again, you should have been able to figure this out yourself, or at least shown us an attempt. 但同样,您应该能够自己弄清楚这一点,或者至少向我们展示了一次尝试。

Or more generally: 或更笼统地说:

  int rows = 5;
  int cols = 10;
  int textNumber = 0;
  for (int i = 0; i < rows * cols; i++) {
     if ((i / cols ) % 2 == 0) {
        textNumber = i;
     } else {
        textNumber = ((i / cols) + 1) * cols - (i % cols) - 1;
     }
     textNumber++;
     System.out.printf("[%02d, %02d] ", i, textNumber);
     if ((i + 1) % cols == 0) {
        System.out.println();
     }
  }

use netbeans' spring layouts to solve your problems 使用Netbeans的Spring布局解决您的问题
just design a couple of buttons in the design tab then replicate them in a loop with your desired counts. 只需在“设计”选项卡中设计几个按钮,然后以所需的计数循环复制它们即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM