gpt4 book ai didi

Java - 调用的paintComponent将在运行时被读取但不被实现

转载 作者:行者123 更新时间:2023-12-02 02:55:08 25 4
gpt4 key购买 nike

本质上,我正在尝试向 JPanel 网格矩阵添加一个圆圈(这是我的主要问题所在)。运行下面的代码时,一旦调用新的 OvalComponent 类将圆添加到网格中的 (1,1) 位置,就会读取该类,但会跳过绘制组件函数。

package Exercises;

import javax.swing.*;
import java.awt.*;
import java.io.FileNotFoundException;

/**
* Created by user on 4/1/2017.
*/
public class Mazes extends JPanel {

public static void main(String[] args) throws FileNotFoundException {
Mazes maze = new Mazes();
}

public Mazes() throws FileNotFoundException{
Boolean[][] maze = Exercise4.readMaze();
int row = maze.length;

JFrame f = new JFrame("Maze");
f.setLayout(new GridLayout(row, row));

JPanel[][] grid = new JPanel[row][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < row; j++) {
grid[i][j] = new JPanel();
grid[i][j].setOpaque(true);
if ((i==1&&j==1) || (i==row-1 && j==row-1))
grid[i][j].add(new OvalComponent());

if (maze[i][j].equals(false)){
grid[i][j].setBackground(Color.BLACK);}
else grid[i][j].setBackground(Color.WHITE);
f.add(grid[i][j]);
}
}

//f.add(new JButton("Reset"), BorderLayout.SOUTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
class OvalComponent extends JComponent {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval(4, 4, 10, 10);
}
}

最佳答案

OvalComponent 没有可定义的大小(默认为 0x0),因此在添加组件时,它的添加大小为 0x0 Swing 足够聪明,知道它不需要绘制它。

重写组件的 getPreferredSize 方法并返回适当的大小

@Override
public Dimension getPreferredSize() {
return new Dimension(18, 18);
}

举个例子

关于Java - 调用的paintComponent将在运行时被读取但不被实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43221709/

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