有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在一个组件覆盖中为drawString设置两种不同的字体

基本上,我正在编写自己的数独应用程序,对于视图部分(MVC),我有一个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合并

总而言之,我基本上只希望一些单元格中写入实际值的大数字,而另一些单元格中有多个小数字,显示该单元格的注释。谢谢你的帮助


共 (0) 个答案