gpt4 book ai didi

java - 按键后调用方法的问题

转载 作者:行者123 更新时间:2023-12-01 17:46:40 25 4
gpt4 key购买 nike

我想实现 KeyListiner,以便当按下空格键时程序将生成 Function 类的新对象并绘制代表该函数的新图像。目前程序正在运行,但按空格键不允许生成新图像。我们将不胜感激每一条建议:)

主类:

public class Main  {

public static void main(String[] args) {
JFrame window = new JFrame(SOFTWARE_TITLE);
MainView mainView = new MainView();
Key key = new Key();
Controller controller = new Controller(mainView);
key.setController(controller);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(790, 580);
window.setLocationRelativeTo(null);
window.setResizable(false);
window.add(mainView);
window.setVisible(true);

}
}

主视图类:

public class MainView extends JPanel {

private Function function;

public MainView(){
super();
setBackground(Color.GRAY);
setLayout(null);
setSize(200, 200);
function = new Function();

DrawBoard drawBoard = new DrawBoard(function);
drawBoard.setSize(500, 500);
drawBoard.setBackground(Color.lightGray);
drawBoard.setLocation(250, 20);
add(drawBoard);

setVisible(true);

}
}

DrawBoard 类:

public class DrawBoard extends Canvas {

short CUSTOM_WIDTH = 5 * 100;
private Function function;

public DrawBoard(Function function) {
this.function = function;
}

public void paint(Graphics g) {

double difference = function.getzMax() - function.getzMin();

for (int indexX = 0; indexX < 100; indexX++) {
for (int indexY = 0; indexY < 100; indexY++) {
double value = function.getPoints()[indexX][indexY].getZ() - function.getzMin();
double corrected = setFloatInRGBRange(difference, value);
g.setColor(intToColor((int) corrected));
g.fillRect(indexX * 5, CUSTOM_WIDTH - ((indexY+1) * 5), 5, 5);
}
}
}

public Color intToColor(int colNum){
return new Color(colNum, colNum, colNum);
}

private int setFloatInRGBRange(double difference, double value){
return (int) ((255 * value)/difference);
}

}

关键类:

public class Key implements KeyListener {

Controller controller;

public void setController(Controller controller) {
this.controller = controller;
}

@Override
public void keyTyped(KeyEvent e) {

}

@Override
public void keyPressed(KeyEvent e) {

}

@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_SPACE){
controller.generateFormula();
}
}
}

Controller 类:

public class Controller {

MainView mainView;

public Controller(MainView mainView) {
this.mainView = mainView;
}

public void generateFormula() {
this.mainView = new MainView();
}
}

最佳答案

您发布的代码中还有一些其他内容需要检查。但对于您主要关心的问题,我猜您没有正确检查击键。

我会使用 e.getKeyCode() 而不是 e.getKeyChar() 来检查事件。

所以你的条件是:e.getKeyCode() == KeyEvent.VK_SPACE

这不是主题,但是:

  1. 您没有必要在多个类中使用Function。它只能在 DrawBoard
  2. 中使用
  3. 不要按照其他建议混合使用 Swing 和 AWT 组件

关于java - 按键后调用方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60856351/

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