(Java)如何绘制单个char

时间:2014-10-29 09:31:07

标签: java eclipse swing user-interface awt

我有一个问题。我已宣布这个字符,但我找不到有效的函数....

如何在GUI中绘制单个字符? :) drawString似乎无法正常工作,drawChars需要一个数组:S

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MyFrame extends JFrame implements ActionListener {
private JPanel p;
private JTextField tf;
private JLabel lb;
private JButton b, bstart;
private String woord = "woord";
private int x = 0; 
private int y = 0;
private Font f = new Font("Courier", Font.PLAIN,60); 
private int count;
private int y = 60;

public MyFrame() {
    setLayout(new FlowLayout());

    p = new JPanel();
    p.setPreferredSize(new Dimension(500, 600));
    add(p);
    p.setOpaque(true);
    p.setBackground(Color.BLUE);

    bstart = new JButton("start");
    add(bstart);
    bstart.addActionListener(this);
    lb = new JLabel("Voer uw woord in: ");
    add(lb);
    tf = new JTextField(8);
    add(tf);
    b = new JButton("Kraken");
    add(b);
    b.addActionListener(this);

    setSize(150, 150);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
}

public void actionPerformed(ActionEvent event) {
    Graphics g = p.getGraphics();
    if (event.getSource() == bstart) {
        g.setColor(Color.WHITE);
    //  g.drawRect(25, 25, 500, 500);
    //  g.drawLine(500, 425, 25, 425);
    //  g.drawLine(500, 325, 25, 325);
    //  g.drawLine(500, 225, 25, 225);
    //  g.drawLine(500, 125, 25, 125);

        for (int i = 0; i < 5; i++) {
            for (int z = 0; z < 5; z++) {
                g.drawRect(x,y,100,100);
                x = x + 100;
            }
            x = 0; y = y+100;
        }
        g.setFont(f);
        g.drawString("W", 30, 60);

    }
    if(event.getSource() == b){
        count++;
        String gok = tf.getText();
        g.setColor(Color.RED);
        g.fillRect(0,0,100,100);
        g.setColor(Color.white);
        g.setFont(f);
        g.drawString("W", 30, 60);
        char secondLetter = gok.charAt(1);
        char thirdLetter = gok.charAt(2);   
        char fourthLetter = gok.charAt(3);
        char lastLetter = gok.charAt(4);
        g.drawString(secondLetter,130, y);

    }

    String input = tf.getText();
    if (input.toLowerCase() == "woord")
        ;
}
}

1 个答案:

答案 0 :(得分:3)

为什么不直接转换为String:

char c = '#';
g.drawString(String.valueOf(c), x, y);