import javax.swing.*;
import java.awt.*;public class Edge extends JFrame {
public Edge() { super("Drawing");
setSize(600, 600); JPanel pane = new JPanel() {
public void paintComponent(Graphics g) {
g.drawRect(100, 100, 300, 300);
}
}; getContentPane().add(pane);
} public static void main(String[] args) {
Edge frame = new Edge();
frame.show();
}
}
import java.awt.*;public class Edge extends JFrame {
public Edge() { super("Drawing");
setSize(600, 600); JPanel pane = new JPanel() {
public void paintComponent(Graphics g) {
g.drawRect(100, 100, 300, 300);
}
}; getContentPane().add(pane);
} public static void main(String[] args) {
Edge frame = new Edge();
frame.show();
}
}
g.drawRect(100, 100, 300, 300);
}
用传进来的这个 g draw
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Graphics2D;
public class TestPanel extends JFrame {
JPanel panel = new JPanel();
JPanel pnlCtl = new JPanel();
JButton button = new JButton("Draw line");
JButton button2 = new JButton("Clear all");
public TestPanel() {
Container cp = this.getContentPane();
cp.add(panel,BorderLayout.CENTER);
button.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent me)
{
Graphics2D g2 = (Graphics2D) panel.getGraphics();
g2.drawRect(20,20,100,300);
}
});
button2.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent me)
{
panel.getGraphics().clearRect(0,0,700,400);
}
});
pnlCtl.add(button);
pnlCtl.add(button2);
cp.add(pnlCtl,BorderLayout.NORTH);
setSize(800,600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.show();
}
public static void main(String[] args) {
TestPanel testPanel = new TestPanel();
}
}
请各位看清楚题目,请继续回答,谢谢!!!
只要 repaint() 一被调用你上面画的东西就没了
所以要想画最好的办法就是 override paint 系列函数
如果不相信可以到 sun 的技术论坛问一下
还有测试也没有你这样测试的,给的代码自己都没有运行过,全是错误import javax.swing.*;
import java.awt.*;public class Edge extends JFrame {
public Edge() {
super("Drawing"); JPanel pane = new JPanel() {
public void paint(Graphics g) {
//添加绘图代码;
}
};
pane.setPreferredSize(new Dimension(600, 600));
setContentPane(pane); //**********************
pack();
//********************** Graphics g = this.getGraphics();
if (g == null) {
System.out.println("null");
} else {
g.drawRect(100, 100, 300, 300);
}
} public static void main(String[] args) {
Edge frame = new Edge();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.show();
}
}这是你想要的结果吗?
你贴出的这段代码让我深受启发,也解决了我想要解决的问题,getGraphics()一般要
写在一些响应事件函数中比如鼠标事件中才有效。受你启发也帮我解决了另外一个困惑我
很久的问题,再次表示感谢! to registered(已注册)
这段代码是从我的测试程序里截出来的,当然不能保证其完成正确(但是测试程序是运行正确的),一些很明显的错误就不用管了吧,我相信问题问的很清楚啊