繁体   English   中英

Java在网格布局中得到了错误数量的jbutton

[英]Java getting the wrong number of jbuttons in grid layout

所以我是Java的新手,而我肯定是Swing的新手。

我有一个将由迷宫使用的80 X 80阵列。 我需要我的GUI具有80 X 80按钮,以便它们可以绑定到数组中的值。

我不知道为什么我从这段代码中只能得到五个或六个大按钮。 如果有人可以告诉我如何使它工作,那么请先谢谢您,因为我很沮丧。

只需运行它,您就会明白我的意思……而且我想我还没有弄清楚如何更改按钮的颜色,而是更改了背景颜色。

这是我的代码:

public static void draw() {

    JFrame f = new JFrame();
    f.setTitle("Maze");
    f.setSize(800, 800);
    f.setVisible(true);
    f.setDefaultCloseOperation(EXIT_ON_CLOSE);

    JPanel c = (JPanel)f.getContentPane();
    GridLayout gridLayout = new GridLayout();
    c.setLayout(gridLayout);
    for(int i =0;i<80;i++){
        for(int j =0;j<80;j++){
            JButton b = new JButton();
            c.add(b, i,j);
            b.setSize(10, 10);
            b.setOpaque(true);
            b.setBackground(Color.red);
        }
    }


}

}
  1. 80 * 10 > f.setSize(800, 800); 并且您的代码无法适合FullHd监视器

    1. 使用f.pack()代替f.setSize(800, 800);
  2. f.pack()f.setVisible(true); (可能是一个主要问题)应该是非静态的最后代码行,并重命名为! public void DrawMe() { !,因为draw()是Java API中的保留字

  3. c.add(b, i,j); 应该也是最后一个代码行(逻辑顺序),

  4. c.add(b, i,j); 为GridLayout设置行和列,而不是将JButton注入GridLayout虚拟网格


  • 使我有所了解(从元素数量开始)

在此处输入图片说明

import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class DrawMe {

    private JFrame frame = new JFrame();
    private JPanel c = new JPanel();
    private static final int column = 10;
    private static final int row = 10;

    public DrawMe() {
        c.setLayout(new GridLayout(row, column));
        for (int i = 0; i < column; i++) {
            for (int j = 0; j < row; j++) {
                JButton b = new JButton((i + 1) + " " + (j + 1));
                c.add(b);
            }
        }
        frame.add(c);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocation(150, 150);
        frame.setVisible(true);
    }

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

暂无
暂无

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

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