JLabel 上的 setText 在按键方法中不起作用



每当我试图在KeyPressed方法中使用setText时,它都不起作用,尽管当我在同一类中的不同方法(initComponents)中使用它时,它在那里起作用。

如果有必要,可以随意询问任何其他代码!

这是KeyPressed方法,它不起作用:

@Override
public void keyTyped(KeyEvent e) {
char typed = e.getKeyChar();
if (Character.isLetter(typed) && r.getHuidigeKolom() < r.getAantalLetters()) {
typed = Character.toUpperCase(typed);
r.getLetters()[r.positie(r.getHuidigeRij(), r.getHuidigeKolom())].setText(typed + "");
r.getLetters()[r.positie(r.getHuidigeRij(), r.getHuidigeKolom())].setBackground(Color.blue);
if (r.getHuidigeKolom() == 0) {
for (int i = 1; i < r.getAantalLetters(); i++) {
r.getLetters()[r.positie(r.getHuidigeRij(), i)].setText(".");
r.getLetters()[r.positie(r.getHuidigeRij(), i)].setBackground(Color.blue);
}
r.volgendeKolom(true);
if (r.getHuidigeKolom() < r.getAantalLetters()) {
r.getLetters()[r.positie(r.getHuidigeRij(), r.getHuidigeKolom())].setBackground(hoverKleur);
}
if (typed == 10 && r.getHuidigeKolom() >= r.getAantalLetters()) {   //typed 10 is ENTER
this.controle();
}
if (typed == 8 && r.getHuidigeKolom() > 0) {    //typed 8 is BACKSPACE
this.eentjeTerug();
}
}
}
}

setText方法在以下方法中有效:

private void initComponents(String woord) {
this.setLayout(new GridLayout(r.getAantalPogingen(), r.getAantalLetters(), 2, 2));
for (int i = 0; i < r.getAantalPogingen() * r.getAantalLetters(); i++) {
r.getLetters()[i] = new Label();
r.getLetters()[i].setBackground(Color.white);
r.getLetters()[i].setForeground(Color.black);
r.getLetters()[i].setAlignment(Label.CENTER);
r.getLetters()[i].setFont(new Font("Groot", Font.BOLD, 48));
this.add(r.getLetters()[i]);
}
for (int i = 0; i < 5; i++) {
r.getLetters()[i].setText(woord.charAt(i) + "");
r.getLetters()[i].setBackground(Color.blue);
}
r.setHuidigeKolom(0);
r.setHuidigeRij(0);
}

我真的很感激你能提供的任何帮助。

如果没有MCTRE,要确定问题的确切原因会有点困难,但我猜问题的根源是您使用的是密钥监听器而不是密钥绑定。

KeyListener对关注哪个组件非常挑剔,这很可能是您遇到的问题。除非添加到其中的组件具有应用程序的焦点,否则它不会启动(因此与容器一起使用并不理想)。以下是如何使用密钥绑定的快速示例:

import java.awt.event.*;
import javax.swing.*;
public class KeyBindings extends Box{
public KeyBindings(){
super(BoxLayout.Y_AXIS);
final JTextPane textArea = new JTextPane();
textArea.insertComponent(new JLabel("Text"));
add(textArea);
Action action = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
textArea.setText("New Text");
}};
String keyStrokeAndKey = "control SPACE";
KeyStroke keyStroke = KeyStroke.getKeyStroke(keyStrokeAndKey);
textArea.getInputMap().put(keyStroke, keyStrokeAndKey);
textArea.getActionMap().put(keyStrokeAndKey, action);
}

public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new KeyBindings());
frame.pack();
frame.setVisible(true);
}
}

最新更新