显示了窗口没画图。
package com.bjsxt;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyganesFarms extends Frame {
public void win(){
this.setTitle("无");
this.setSize(5000,5000);
this.setVisible(true);
this.setLocation(300,400);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
@Override
public void paint(Graphics g) {
g.drawLine(100,500,4000,4000);
}
public static void main(String[] args) {
MyganesFarms frame=new MyganesFarms();
frame.win();
}
}
没报错,就画不了图。
我没尝试。
我就想画个正常的图。
在窗口对象上覆写 paint 方法是没用的,因为你看到的窗口内容实际上是其 contentPane 展示的内容,你要覆写的是 contentPane 对象的 paint 方法。下面是一个例子:
public class ComponentPaintSample {
public static void main(String[] args) {
JFrame mainWindow = new JFrame();
mainWindow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainWindow.setSize(400, 300);
mainWindow.setLocation(200, 200);
mainWindow.setTitle("Draw a line");
mainWindow.setContentPane(new LinePanel());
mainWindow.setVisible(true);
}
static class LinePanel extends JPanel {
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.black);
g.drawLine(10, 10, 100, 100);
}
}
}
结果如图:
你没给窗体添加paint事件,所以代码根本没执行