import java.awt.Color;
import java.awt.Graphics;import javax.swing.JFrame;public class TestLine extends JFrame{
TestLine(){
setBounds(100, 100, 500, 375);
setVisible(true);
Graphics xx = this.getGraphics();
xx.setColor(Color.RED);
xx.drawLine(100, 100, 200, 200);
}
public static void main(String[] args) {
new TestLine();
}
}
想画一条直线上去,怎么会这么难呢????
import java.awt.Graphics;import javax.swing.JFrame;public class TestLine extends JFrame{
TestLine(){
setBounds(100, 100, 500, 375);
setVisible(true);
Graphics xx = this.getGraphics();
xx.setColor(Color.RED);
xx.drawLine(100, 100, 200, 200);
}
public static void main(String[] args) {
new TestLine();
}
}
想画一条直线上去,怎么会这么难呢????
import java.awt.Graphics;import javax.swing.JFrame;public class TestLine extends JFrame {
TestLine() {
setBounds(100, 100, 500, 375);
setVisible(true);
} public void paint(Graphics g) {
g.setColor(Color.RED);
g.drawLine(100, 100, 200, 200);
} public static void main(String[] args) {
new TestLine();
}
}
Graphics xx = this.getGraphics();
xx.setColor(Color.RED);
xx.drawLine(100, 100, 200, 200);
setBounds(100, 100, 500, 375);
setVisible(true);
}
这样也是可以的,2楼写的去看下paint 在哪里调用的就晓得 看看源代码
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class TextPaneDraw extends JFrame{
private JTextPane textPane = new JTextPane(){
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawLine(20, 20, 80, 20);
}
};
public TextPaneDraw(){
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.add(textPane, "Center");
}
public static void main(String[] args){
TextPaneDraw ppd = new TextPaneDraw();
ppd.setSize(400, 400);
ppd.setVisible(true);
}
}
我不瞒你说哇 我学艺不精的 我也是跟你差不多的时候开始学Java的
我就知道应该这样 至于为什么 我不是很清楚
setVisible(true);
Graphics xx = this.getGraphics();
xx.setColor(Color.RED);
xx.drawLine(100, 100, 200, 200);也就是说,先setVisible(true);然后再drawLine(),就是说你先让它显示出来了再再它上面画,从现实中好象逻辑是这样的,但其实它已经输出到屏幕上, 就不能再变化,所以你再在上面画线也是没用的。有的人会说了,那我把屏幕刷新(就是调用repaint方法)就可以了啊,但这样想大错特错。
repaint方法实际上最后是调用paint方法的,只要你没修改过paint方法(因为你在构造方法里做的this.getGraphics().drawLine(100,100,200,200)是不可能没修改到paint方法的),那么它就会按照原来的样子显示,原来当然就是一张白纸了,什么都没有。又有的人说了,那么我先画线再显示怎么样啊。
请看下面:
首先getGraphics这个方法,你可以看API,是这样解释的:
public Graphics getGraphics()
Creates a graphics context for this component.This method will return null if this component is currently not displayable.
为组件创建一个图形上下文。如果组件当前是不可显示的,则此方法返回 null。
所以说你拿到的Graphics是一个null值,你是不可能用它来做什么事的。那么难道就没有解决办法了吗?当然不是,既然我们都已经知道了它是根据paint方法来画的,那我们为什么不修改paint方法呢?所以就有了2楼的答案。
还有。2楼的paint方法最好改成这样
Color c = g.getColor();
g.setColor(Color.RED);
g.drawLine(100, 100, 200, 200);
g.setColor(c);
维持现场也是比较重要的,切记。
具体还是看书吧,因为我对awt不熟,只是当年看书的时候留下的一点记忆,呵呵