gpt4 book ai didi

Java布局问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:37:26 25 4
gpt4 key购买 nike

我的程序中有 3 个类。

public class Field extends JLabel{

private int x, y;

public Field(int x, int y){
this.x = x;
this.y = y;
setOpaque(true);
setMinimumSize(new Dimension(50,50));
setPreferredSize(new Dimension(75,75));
if((x + y) % 2 == 0)
setBackground(Color.GREEN);
else
setBackground(Color.YELLOW);
}


public class Board extends JPanel{

public Field[][] fields = new Field[8][8];

public Board(){
setLayout(new GridLayout(8,8));
setMinimumSize(new Dimension(500,500));
setPreferredSize(new Dimension(550,550));
setBackground(Color.RED);
fillBoard();
}

private void fillBoard(){
for(int i = 0; i < 8; ++i){
for(int j = 0; j < 8; ++j){
fields[i][j] = new Field(i, j);
add(fields[i][j]);
}
}
}

public class GUI extends JFrame{

public Board board;

private GUI(){
board = new Board();
setLayout(new FlowLayout());
add(board);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
pack();
}

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

}

每当我运行程序时,this出现而不是黄绿色板。有人可以帮忙吗?

最佳答案

您发布的代码无法编译。如图所示,重构为嵌套类使其 正确 工作,所以我猜您遇到了项目级别的问题。

enter image description here

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class GUI extends JFrame {

private Board board;

private GUI() {
board = new Board();
setLayout(new FlowLayout());
add(board);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
pack();
}

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

@Override
public void run() {
new GUI();
}
});
}

class Board extends JPanel {

public Field[][] fields = new Field[8][8];

public Board() {
setLayout(new GridLayout(8, 8));
setMinimumSize(new Dimension(500, 500));
setPreferredSize(new Dimension(550, 550));
setBackground(Color.RED);
fillBoard();
}

private void fillBoard() {
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
fields[i][j] = new Field(i, j);
add(fields[i][j]);
}
}
}
}

class Field extends JLabel {

private int x, y;

public Field(int x, int y) {
this.x = x;
this.y = y;
setOpaque(true);
setMinimumSize(new Dimension(50, 50));
setPreferredSize(new Dimension(75, 75));
if ((x + y) % 2 == 0) {
setBackground(Color.GREEN);
} else {
setBackground(Color.YELLOW);
}
}
}
}

关于Java布局问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6500402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com