Java - 将 JButton 数组添加到 JFrame

标签 java arrays swing jbutton

我正在尝试将 2D JButton 数组添加到 JFrame,但没有收到任何错误,只是 JButton 没有显示。

创建 JButton:

public class TTTGrid {
private static JFrame frame;
private static int[][] coords;
private static int width, height;
public TTTGrid(JFrame frame,int[][] coords, int width, int height){
    this.frame = frame;
    this.coords = coords;
    this.width = width;
    this.height = height;
}
static JButton map[][] = new JButton[3][3];

public void Draw(){
    for(int i = 0; i<coords.length; i++){
        for(int j = 0; j<coords[i].length; j++){
            map[i][j] = new JButton();
            map[i][j].setBounds(i*100, j*100, width, height);
            frame.add(map[i][j]);

        }
    }
}

}

调用draw方法的地方:

public class TTTthread extends TTT implements Runnable {
int[][] map = new int[3][3];
TTTGrid grid = new TTTGrid(frame, map, 100, 100);

@Override
public void run() {
    try {
        while (true) {
            grid.Draw();

            Thread.sleep(20);

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

最佳答案

如果您的代码像我想象的那样运行,那么您似乎每秒 50 次尝试向 GUI 添加 9 个 JButton!按钮太多了——你确定这就是你想要做的吗?通过从 Swing 事件线程中进行 Swing 调用(大量 Swing 调用!),您的代码还严重违反了 Swing 线程规则。

您的主要解决方案可能是

  • 将 9 个 JButton 添加到使用 GridLayout(3, 3) 的 JPanel
  • 仅执行此操作一次,而不是每秒执行 50 次
  • 然后将该 JPanel 添加到您的 GUI BorderLayout.CENTER 中,并确保不使用 null 布局。
  • 不要尝试设置这些 JButton 的边界、大小或位置,而是让布局管理器来工作
  • 摆脱 while 循环,而是使用 Swing 的事件驱动模型将代码更改为更加事件驱动。
  • 尽量使用非静态变量和方法,使您的类成为真正的 OOPS 兼容类,从而使它们能够利用 OOPS 编程的优势,包括降低程序复杂性和互连性(减少耦合)。
<小时/>

例如

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;

public class MyTttFoo extends JPanel {
   // it's OK for constants to be static
   private static final long serialVersionUID = 1L;
   private static final int ROWS = 3;

   // use a larger Font to make buttons larger
   private static final Font BTN_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 60);
   private static final String BLANK = "   ";
   private static final String X = "X";
   private static final String O = "O";

   // but not most variables
   private JButton[][] buttonGrid = new JButton[ROWS][ROWS];

   public MyTttFoo() {
      setBackground(Color.black);

      // use layout managers to help you create your GUI
      setLayout(new GridLayout(ROWS, ROWS, 1, 1));
      ActionListener btnListener = new ButtonListener();
      // create your buttons and add them only **once**
      for (int row = 0; row < buttonGrid.length; row++) {
         for (int col = 0; col < buttonGrid[row].length; col++) {
            JButton button = new JButton(BLANK);
            button.setFont(BTN_FONT);
            button.addActionListener(btnListener);
            add(button);  // add button to a gridlayout using component
            buttonGrid[row][col] = button; // and assign into the array
         }
      }
   }

   private class ButtonListener implements ActionListener {
      private boolean xTurn = true;

      @Override
      public void actionPerformed(ActionEvent e) {
         AbstractButton btn = (AbstractButton) e.getSource();
         String txt = btn.getText();
         if (txt.equals(BLANK)) {
            if (xTurn) {
               btn.setText(X);
            } else {
               btn.setText(O);               
            }
            xTurn = !xTurn;
         } 
      }
   }

   private static void createAndShowGui() {
      MyTttFoo mainPanel = new MyTttFoo();

      JFrame frame = new JFrame("MyTttFoo");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

关于Java - 将 JButton 数组添加到 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28258721/

相关文章:

java - 如何同时启动部署在tomcat中的所有应用

java - 在 intellij 中运行参数化 junit 测试的单个场景

java - JFrame 上绘制的点的总距离

arrays - ruby 中将对象数组转换为整数数组

c# - 数组问题 c# "cannot apply indexing"

java - 如何构造 JTextfield,以及如何使用 selectAll() 方法

java - 如何访问我的代码中的数据? -变量可能尚未初始化

java - CXF 和 Spring-WS 哪个框架更好?

Java - IsAssignableFrom 悖论?

java - 当数组充满了 get 方法中的数字时,如何对数组进行排序