gpt4 book ai didi

java - 如何使用 keyTyped() 方法删除我的图 block 类?

转载 作者:行者123 更新时间:2023-12-01 10:52:43 26 4
gpt4 key购买 nike

这是我的图 block 类:

public class Tile extends JLabel {

public static Font font = new Font("Serif", Font.BOLD, 39);

private static char _c;

public Tile(char c, Color background) {
setBackground(background);
setOpaque(true);
_c = c;
setText(convert());
setFont(font);
}

public static char randomLetter() {
Random r = new Random();
char randomChar = (char) (97 + r.nextInt(26));
return randomChar;
}

public static Color randomColor() {
Random rand = new Random();
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();

Color randomColor = new Color(r, g, b);
return randomColor;
}

public static char getChar() {
return _c;
}

public String convert() {
return String.valueOf(getChar());
}
}
<小时/>

我的 GUI 类

public class Game implements KeyListener {

public static Game game;

private Model model;

public Game() {
model = new Model();

for (int i = 0; i < 4; i++) {
model.add(new Tile(Tile.randomLetter(), Tile.randomColor()));
}

JFrame frame = new JFrame();
frame.getContentPane().setLayout(new GridLayout(4, 1));
frame.setSize(500, 800);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

for (Tile tile : model.getTiles()) {
frame.add(tile);
}

frame.getContentPane().addKeyListener(this);
frame.getContentPane().setFocusable(true);
frame.getContentPane().requestFocusInWindow();

}

@Override
public void keyPressed(KeyEvent arg0) {
}

@Override
public void keyReleased(KeyEvent e) {
}

@Override
public void keyTyped(KeyEvent e) {
if (model.getTiles(0).Tile.getChar == e.getKeyChar()) {
System.out.println("YOU REMOVED A TILE!!!");
}
// model.removeByChar(e.getKeyChar());
}

public static void main(String[] args) {

new Game();

}
}
<小时/>

和我的模型类

public class Model {

private ArrayList<Tile> list = new ArrayList<Tile>();

public Model() {
}

public void add(Tile tile) {
list.add(tile);
}

public ArrayList<Tile> getTiles() {
return list;
}
}

我试图在按下相对于图 block 字母的按键时删除图 block ,但我不知道如何实现这一点。

最佳答案

@Override
public void keyTyped(KeyEvent e) {
for (Tile t : model.getTiles()) {
if (t.getChar() == e.getKeyChar()) {
System.out.println("YOU REMOVED A TILE!!!");
frame.remove(t);
frame.repaint();
}
}
// model.removeByChar(e.getKeyChar());
}

关于java - 如何使用 keyTyped() 方法删除我的图 block 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33748581/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com