我是Java的初学者。这是我的第一个项目。每次我运行代码时,代码的GUI都会不断变化。有时输出甚至没有完全加载。这是仅初始化国际象棋棋盘8X8 jbutton的代码。
我放下图像来检查下面的超链接。
每次执行代码时,有没有解决方案可以显示相同的输出?
package chess;
import game.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;
public class board{
static JButton [][] spots =new JButton [8][8];
public static void main(String[] args){
board b =new board();
b.initializeboard(spots);
}
public void initializeboard(JButton [][] spots){
JFrame f = new JFrame("CHESS");
f.setVisible(true);
f.setSize(800,800);
GridLayout layout =new GridLayout(8,8,1,1);
f.setLayout(layout);
for(int ver=0;ver<8;ver++){
for(int hor=0;hor<8;hor++){
JButton button = new JButton();
if((ver+hor)%2==0){
button.setBackground(Color.WHITE); }
else{
button.setBackground(new Color(255,205,51)); }
pieces p =new pieces();
spots[ver][hor] = button;
p.setButton(button);
f.add(button);
}
}
} //initialize board
} // close board
我是Java的初学者。
首先,类名应以大写字母开头。您甚至看到JDK中的类都不以大写字母开头吗?通过示例从教科书或教程中的代码中学习。
每次执行代码时,有没有解决方案可以显示相同的输出?
在使框架可见之前,应将所有组件添加到框架中。
当使框架可见时,将调用布局管理器,并为组件指定大小/位置。必须承认,我不确定您为什么会得到这种随机行为。一些组件正在获取大小/位置,而其他组件则没有。
我建议您重组代码,例如:
JPanel chessboard = new JPanel( new GridLayout(8, 8, 1, 1) );
// add buttons to the panel
JFrame frame = new JFrame("CHESS")
frame.add(chessboard, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
f.setSize(800,800);