小弟想通过调用类的方法画个多边形
在程序中加入了事件监听,由用户输入参数
原程序如下:
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.event.*;
public class Dda extends JFrame //主类
{
JButton refresh=new JButton("refresh");
PanelControl panelControl;
Draw draws;
public Dda( )
{
super("DDA");
setSize(400,350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
BorderLayout grid = new BorderLayout();
pane.setLayout(grid);
String[] coordinate={"x0","y0","x1","y1"};
panelControl = new PanelControl(this,coordinate);
draws = new Draw();
pane.add(panelControl,"North");
ane.add(draws,"Center");
setContentPane(pane);
setVisible(true);
}
public static void main(String[] arguments)
{
Dda frame=new Dda();
}
//
public static int x0,y0,x1,y1;
void draw (PanelControl control)//传入的参数
{
int[] value = new int[4];
for (int i=0;i<4;i++)
value[i] = Integer.parseInt(control.setting[i].getText());
x0=value[0];y0=value[1];x1=value[2];y1=value[3];
draws.repaint();
}
}
//class PanelControl从文本框输入参数
class PanelControl extends JPanel implements ActionListener,FocusListener
{
Dda frame;
JTextField[] setting = new JTextField[4];
PanelControl(Dda parent,String[] label)
{
Dda frame=parent;
GridLayout cGrid = new GridLayout(4,2,10,10);
setLayout(cGrid);
for(int i=0;i<4;i++)
{
setting[i] = new JTextField("1");
setting[i].addFocusListener(this);
setting[i].addActionListener(this);
JLabel settingLabel = new JLabel(label[i]);
add(settingLabel);
add(setting[i]);
}
setVisible(true);
}
public void actionPerformed(ActionEvent evt)//事件处理
{
if (evt.getSource() instanceof JTextField)
frame.draw(this);
}
public void focusLost(FocusEvent evt)
{
frame.draw(this);
}
public void focusGained(FocusEvent evt) { }
}
class Draw extends JPanel //画图类
{
public void paintComponent(Graphics comp)
{
Graphics2D comp2D=(Graphics2D)comp;
comp2D.setColor(Color.white);
Rectangle2D.Float background=new Rectangle2D.Float(0F,0F,50F,50F);//以矩形为底版
comp2D.fill(background);
comp2D.setColor(Color.black);
GeneralPath line=new GeneralPath();//多边形类
line.moveTo(Dda.x0,Dda.y0);
int k=(Dda.y1-Dda.x1)/(Dda.y0-Dda.x0),y=Dda.y0;
for(int x=Dda.x0;x<=Dda.x1;x+=1)
{
line.lineTo((int)x,(int)(y+0.5));
y=y+k;
}
comp2D.draw(line);
}
}
编译通过,但文本框显示的很乱,图形没有显示
请各位大虾帮忙,小弟再此谢过了!!!