gpt4 book ai didi

Java KeyListener 不起作用

转载 作者:行者123 更新时间:2023-12-01 18:33:17 24 4
gpt4 key购买 nike

我尝试使用 JFreeChart 编写简单的代码,当我按下“缩放”按钮时,我想通过键盘“退出”来取消缩放,但 KeyListener 不起作用。哪里有问题?我还尝试将 KeyListener 添加到 chartPanelpanel,但它也不起作用。

package test1;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.plot.*;
import org.jfree.chart.renderer.xy.*;
import org.jfree.data.xy.*;

public class Test1 {

public static final String Title = "JGrapher";
static JFrame frame;
static double minX = -0.1, maxX = 1.1, minY, maxY;
static XYSeriesCollection dataset;
static ChartPanel chartPanel;
static XYPlot xyplot;

private static void display(){
XYSeries serie = new XYSeries("1");
serie.add(1, 1);
serie.add(8, 8);
dataset = new XYSeriesCollection();
dataset.addSeries(serie);
NumberAxis domain = new NumberAxis("\u03C1");
NumberAxis range = new NumberAxis("g(\u03C1)");
XYSplineRenderer r = new XYSplineRenderer(20);
xyplot = new XYPlot(dataset, domain, range, r);

final JFreeChart chart = new JFreeChart(xyplot);

ValueAxis xAxis = xyplot.getDomainAxis();
xAxis.setRange(-10, 10);
ValueAxis yAxis = xyplot.getRangeAxis();
yAxis.setRange(-10, 10);

chartPanel = new ChartPanel(chart){
@Override
public Dimension getPreferredSize() {
return new Dimension(640, 480);
}
};

chartPanel.setDomainZoomable(false);
chartPanel.setRangeZoomable(false);
frame = new JFrame(Title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(chartPanel);

frame.addKeyListener(new KeyListener() { // KEYLISTENER NOW WORKS :(
@Override
public void keyTyped(KeyEvent ke) {}

@Override
public void keyPressed(KeyEvent ke) {
System.out.println("You pressed " + ke.getKeyChar());
}

@Override
public void keyReleased(KeyEvent ke) {}
});

JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER)); //buttons
final JButton zoomFree = new JButton("Zoom");
panel.add(zoomFree);

zoomFree.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
chartPanel.setDomainZoomable(true);
chartPanel.setRangeZoomable(true);
zoomFree.setEnabled(false);
}
});

frame.add(panel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
display();
}
});
}
}

是的,我尝试了简单的系统输出来检测按键监听器的工作

最佳答案

I want to cancel zoom with "escape" from keyboard,

然后使用按键绑定(bind),而不是 KeyListener。 Swing 被设计为与键绑定(bind)一起使用。

阅读 Swing 教程中关于 How to Use Key Bindings 的部分了解更多信息。

关于Java KeyListener 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23174840/

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