java的绘图问题,我为什么点击按钮没反应
importjava.awt.*;importjava.awt.event.*;importjava.util.*;publicclassDrawTest{private...
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class DrawTest {
private final String RECT_SHAPE ="矩形";
private final String CIR_SHAPE ="圆形";
private String shape ="";
public static void main(String[] args) {
new DrawTest().init();
}
class MyCanvas extends Canvas {
public void paint(Graphics g) {
if(shape.equals(RECT_SHAPE)) {
g.setColor(Color.GREEN);
g.drawRect(100,100,40,60);
}
if(shape.equals(CIR_SHAPE)) {
g.setColor(Color.RED);
g.fillOval(100,100,40,40);
}
}
}
void init() {
Frame f =new Frame("绘图工具");
Button RecB =new Button("绘制矩形");
Button CirB =new Button("绘制圆形");
Panel p =new Panel();
MyCanvas c =new MyCanvas();
p.add(RecB);
p.add(CirB);
f.add(p,BorderLayout.SOUTH);
f.add(c,BorderLayout.NORTH);
f.setSize(400,350);
p.setSize(400,300);
f.setVisible(true);
RecB.addActionListener(e -> {
shape =RECT_SHAPE;
c.repaint();
});
CirB.addActionListener(e -> {
shape =CIR_SHAPE;
c.repaint();
});
}
} 展开
import java.awt.event.*;
import java.util.*;
public class DrawTest {
private final String RECT_SHAPE ="矩形";
private final String CIR_SHAPE ="圆形";
private String shape ="";
public static void main(String[] args) {
new DrawTest().init();
}
class MyCanvas extends Canvas {
public void paint(Graphics g) {
if(shape.equals(RECT_SHAPE)) {
g.setColor(Color.GREEN);
g.drawRect(100,100,40,60);
}
if(shape.equals(CIR_SHAPE)) {
g.setColor(Color.RED);
g.fillOval(100,100,40,40);
}
}
}
void init() {
Frame f =new Frame("绘图工具");
Button RecB =new Button("绘制矩形");
Button CirB =new Button("绘制圆形");
Panel p =new Panel();
MyCanvas c =new MyCanvas();
p.add(RecB);
p.add(CirB);
f.add(p,BorderLayout.SOUTH);
f.add(c,BorderLayout.NORTH);
f.setSize(400,350);
p.setSize(400,300);
f.setVisible(true);
RecB.addActionListener(e -> {
shape =RECT_SHAPE;
c.repaint();
});
CirB.addActionListener(e -> {
shape =CIR_SHAPE;
c.repaint();
});
}
} 展开
2个回答
展开全部
你的程序没有大问题,只是把画布Canvas放在了边界布局的北面,而图形画在了x=100,y=100的位置,因为y=100纵坐标数值太大,所以画出来也看不见,解决办法把画布Canvas放在边界布局的中间就可以显示出来了.
也就是说把f.add(c,BorderLayout.NORTH);这一句改成f.add(c,BorderLayout.CENTER);就可以显示出来了.
也就是说把f.add(c,BorderLayout.NORTH);这一句改成f.add(c,BorderLayout.CENTER);就可以显示出来了.
更多追问追答
追问
这个x,y不是代表像素啊??那xy的大小到底多大呢?
追答
g.drawRect(100,100,40,60);代表在屏幕x=100,y=100处画一个宽40高60的矩形
Canvas中图形不管x,y等于多少,放在边界布局的北部,图形都显示不出来.
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询