所以,我试图在JPanel(矩形)上绘制一个矩形,然后将其添加到我的主JFrame中。矩形应该在窗口的中间,但是在窗口的外面。
我尝试过的事情:
null
,矩形消失无处可见。相关代码:
Main.java
package sudoku_solver;
public class Main
{
public static void main(String[] args)
{
int[][] board = Board.getBoard();
Solver solver = new Solver(board);
Interface gui = new Interface();
gui.createFrame();
gui.drawGrid(board);
solver.solve();
solver.print();
}
}
Interface.java
package sudoku_solver;
import java.awt.*;
import javax.swing.*;
public class Interface
{
private static class Rect extends JPanel
{
private static final long serialVersionUID = 1L;
int x;
int y;
int rectWidth;
int rectHeight;
Color color;
public Rect(int _x, int _y, int _rectWidth, int _rectHeight, Color _color)
{
x = _x;
y = _y;
rectWidth = _rectWidth;
rectHeight = _rectHeight;
color = _color;
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawRect(x, y, rectWidth, rectHeight);
g2d.setColor(color);
}
}
static JFrame frame;
static int windowWidth = 580;
static int windowHeight = 580;
static int cellSize = windowWidth / 9;
public void createFrame()
{
frame = new JFrame("Sudoku");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(windowWidth, windowHeight);
frame.setVisible(true);
}
public void drawGrid(int[][] bo)
{
drawBorder();
}
private static void drawBorder()
{
Rect rect = new Rect(20, 20, windowWidth - 20, windowHeight - 20, Color.black);
frame.add(rect);
}
}
输出:
试图找到其他人遇到同样的问题,但找不到任何人。谢谢!
您编写:new Rect(20,20,windowWidth-20,windowHeight-20,Color.black);因为它应该是新的Rect(20,20,windowWidth-40,windowHeight-40,Color.black),因为,第一个点表示开始位置,第三个和第四个表示您的矩形应该多长时间。因此,既然您拿走了20,但应该是40,因为您只从左侧拿走了,却忘记了框架的右侧。