【发布时间】:2013-10-07 10:41:07
【问题描述】:
我想用Java 中的hline 和vline 绘制矩形。我在绘制它时遇到了一些问题,我不太清楚,但我认为它在 hline1 和 vline1 方法上。
没有错误,只是参数内部算法有问题。
这里是代码..
package hw1;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
public class main extends Frame {
Graphics2D g2d;
main()
{
addWindowListener(new hw1.main.MyFinishWindow());
}
public class MyFinishWindow extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
public void paint (Graphics g)
{
g2d=(Graphics2D)g;
hline(0,40,250,40);
vline(250,40 , 250 , 80);
hline1(250,80,0,80);
vline1(0,80 , 0 , 40);
}
public void hline(int x1,int y1 , int x2 , int y2)
{
for(int x=x1 ; x<=x2 ; x++)
putpixel(x,y1,Color.blue);
}
public void vline(int x1 ,int y1 , int x2 , int y2 )
{
for(int y=y1;y<=y2;y++)
putpixel(x1,y,Color.blue);
}
public void hline1(int x1,int y1 , int x2 , int y2)
{
for(int x=x1 ; x<=x2 ; x++)
putpixel(x,x1,Color.blue);
}
public void vline1(int x1 ,int y1 , int x2 , int y2 )
{
for(int y=y1;y<=y2;y++)
putpixel(x1,y,Color.blue);
}
public void putpixel(int x , int y , Color c)
{
g2d.setColor(c);
g2d.drawLine(x, y, x, y);
}
public void putpixel(int x , int y , Color c , int rad)
{
g2d.setColor(c);
if(rad>4) rad=4;
if(rad<=0) rad=1;
g2d.drawOval(x-rad/2, y-rad/2, rad, rad);
}
public static void main(String[] args) {
// TODO code application logic here
main f=new main();
f.setTitle("Computer Graphics:Java 2D prpgram");
Dimension screenSize=
Toolkit.getDefaultToolkit().getScreenSize();
int width=(int) screenSize.getWidth();
int height=(int) screenSize.getHeight();
f.setSize(width, height);
f.setVisible(true);
}
}
【问题讨论】:
-
为什么选择 AWT 而不是 Swing?请参阅Swing extras over AWT 上的此答案,因为有很多放弃使用 AWT 组件的充分理由。如果您需要支持较旧的基于 AWT 的 API,请参阅 Mixing Heavyweight and Lightweight Components。
-
“我想用 Java 中的
hline和vline绘制矩形。” 顺便说一句 - 为什么特别是这样,而不是(现在是 2)其他好的画盒子的方法?如果是“老师指定的”,最好说清楚。程序员在编程时倾向于“使用最简单的工具”,而你的方法不是最简单的方法。
标签: java user-interface awt java-2d