我从一些基本的Java2D示例-特别是在AWT下开始,在“计算机图形学Java2D / Java3D简介”一书的第一个示例之后,我编写了以下两个类,一个作为“主”类:
package com.example.test;
public class Test {
public static void main( String[] args ) {
MyChart terminal = new MyChart();
terminal.setTitle("The first Java 2D program");
terminal.setSize(350,80);
terminal.setVisible(true);
}
}
另外一个扩展了AWT框架的
package com.example.test;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyChart extends Frame {
public void MyChart() {
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawString("Hello world!", 30, 50);
};
}
这将在屏幕上生成预期的“ Hello World”窗口,但是当我单击关闭按钮(Windows 10)时,什么也没有发生。我试图找出添加成功的监听器时我做错了什么。
欢迎提供进一步调试的任何提示或建议。
如上所述,我使用Java:1.8.0_191和Windows 10。
答案 0 :(得分:1)
您没有在主类中调用MyChart
函数。
下面的代码工作正常。
public class Test {
public static void main( String[] args ) {
System.out.println("Terminal Group");
MyChart terminal = new MyChart();
terminal.MyChart();//I added this.
terminal.setTitle("The first Java 2D program");
terminal.setSize(350,80);
terminal.setVisible(true);
}
}
public class MyChart extends Frame {
public void MyChart() {
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawString("Hello world!", 30, 50);
};
}
答案 1 :(得分:1)
构造函数定义错误,void
存在,必须将其删除。
原始代码(WRONG构造函数,使用void):
public void MyChart() {
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
更正后的代码(无无效):
public MyChart() {
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
dispose();
}
});
}