基本上,我正在编写自己的数独应用程序,对于(MVC)的 View 部分,我有一个 JPanel,它覆盖 PaintComponent 并绘制数独单元格、网格和选定的单元格等。但我的问题是我需要两种不同的字体大小(例如,一种用于用户在单元格中添加注释时使用,一种用于单元格中的实际数字),并且每次我调用 setFont 时,任何单元格中已有的所有文本也会改变大小。 .
据我了解,setFont 将字体应用于单个组件中的所有文本,我猜?就我而言,我只有 Cell[][] 表来存储每个单元格的数字和注释。
class Cell {
private Point coords;
private boolean[] notes;
private int number;
// Constructor + Accessors + Getters
}
因此,在paintComponent中,我循环遍历所有单元格并相应地绘制数字,但是对setFont的任何调用都会更改网格中已有的所有文本。
class SudokuPanel extends JPanel {
private static final int SUDOKU_SIZE = 9;
private Cell[][] cells;
private static final Font BIG_FONT = new Font("Verdana", Font.BOLD, 50),
SMALL_FONT = new Font("Verdana", Font.PLAIN, 12);
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//drawGrid(g);
//drawSelected(g);
drawCells(g);
}
private void drawCells(Graphics g) {
for (int x=0; x<SUDOKU_SIZE; x++)
for (int y=0; y<SUDOKU_SIZE; y++)
drawCell(g, cells[x][y]);
}
private void drawCell(Graphics g, Cell cell) {
if (cell.number == 0 && cell.hasNotes())
drawNotes(g, cell);
else if (cell.number != 0)
writeNumber(g, cell.number, cell);
}
private void drawNotes(Graphics g, Cell cell) {
for (int i=0; I<cell.notes.length; i++)
if (cell.notes[i])
writeNote(g, i, cell);
}
private void writeNote(Graphics g, int i, Cell cell) {
setFont(SMALL_FONT); // for small size
writeStr(g, ""+i, cell.coords.x, cell.coords.y); // definitely wrong drawing coords but not the topic of this post
}
private void writeNumber(Graphics g, int i, Cell cell) {
setFont(BIG_FONT); // for big font size
writeStr(g, ""+i, cell.coords.x, cell.coords.y);
}
}
所以基本上 setFont 大小只考虑最后一次调用 setFont ,所以我应该让我的 Cell POJO 扩展 JComponent 吗?并让他们每个人都通过重写自己的paintComponent方法来绘制自己,其中每个人都会相应地设置不同的字体大小?就像这样:
class Cell extends JComponent {
private static final Font BIG_FONT = new Font("Verdana", Font.BOLD, 50),
SMALL_FONT = new Font("Verdana", Font.PLAIN, 12);
//cell code
@Override
public void paintComponent(Graphics g) {
if (hasNotes()) {
setFont(SMALL_FONT);
// write notes
} else {
setFont(BIG_FONT);
// write number
}
}
}
但是我不知道如何使用单元格作为组件并将它们与我的 JPanel 的 PaintComponent 合并..
总而言之,我基本上只希望一些单元格写入实际值的大数字,而其他单元格在单个单元格中包含多个小数字,显示该单元格的注释。感谢您提供的任何帮助
最佳答案
不要调用组件的setFont
,在绘制文本之前调用Graphics
'。
关于java - 如何在单个paintComponent覆盖中为drawString设置2种不同的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57765462/