我在 Netbeans 中使用 Java 来绘制加权二叉树。在 mouseClick 事件上,绘制一个节点,在窗格上的不同点按下和释放鼠标会创建一条边,之后我需要立即弹出一个输入对话框并要求用户输入边的权重。这是我的代码。不过,不要费心浏览整个代码。
public class panel1 extends JPanel implements MouseListener,ActionListener
{
nodeClass[] nodes = new nodeClass[20];
int nodeRadius = 10;
int ctr = 0;
int[] x=new int[100];
int[] y=new int[100];
int[] oldx=new int[100];
int[] oldy=new int[100];
int[] newx=new int[100];
int[] newy=new int[100];
int edges=0;
int[] edgeWeight = new int[100];
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.GREEN);
if(x[ctr]!=0&&y[ctr]!=0)
{
for(int i=0;i<=ctr;i++){
g.setColor(Color.GREEN);
g.fillOval(x[i]-25, y[i]-45, 40, 40);
g.setColor(Color.BLACK);
g.drawString(String.valueOf(i+1),x[i]-10,y[i]-25);
}
for(int i=0;i<edges;i++){
g.setColor(Color.GREEN);
g.drawLine(oldx[i]-10,oldy[i]-30,newx[i]-10,newy[i]-30);
g.drawString(String.valueOf(edgeWeight[i]), (oldx[i]+newx[i])/2, (oldy[i]+newy[i])/2);
}
ctr++;
}
if(oldx[edges]!=0&&oldy[edges]!=0&&newx[edges]!=0&&newy[edges]!=0&&(newx[edges]!=oldx[edges] && newy[edges]!=oldy[edges]))
{
edgeWeight[edges] = Integer.ParseInt(JOptionPane.showInputDialog("Enter Weight Of Edge : "));
for(int i=0;i<ctr;i++){
g.setColor(Color.GREEN);
g.fillOval(x[i]-25, y[i]-45, 40, 40);
g.setColor(Color.BLACK);
g.drawString(String.valueOf(i+1),x[i]-10,y[i]-25);
}
for(int i=0;i<=edges;i++){
g.setColor(Color.GREEN);
g.drawLine(oldx[i]-10,oldy[i]-30,newx[i]-10,newy[i]-30);
g.drawString(String.valueOf(edgeWeight[i]), (oldx[i]+newx[i])/2, (oldy[i]+newy[i])/2);
}
edges++;
}
}
@Override
public void mouseClicked(MouseEvent me) {
x[ctr]=me.getX();
y[ctr]=me.getY();
repaint();
}
@Override
public void mousePressed(MouseEvent me) {
oldx[edges]=me.getX();
oldy[edges]=me.getY();
}
@Override
public void mouseReleased(MouseEvent me) {
newx[edges]=me.getX();
newy[edges]=me.getY();
repaint();
}
@Override
public void mouseEntered(MouseEvent me) {;
}
@Override
public void mouseExited(MouseEvent me) {;
}
@Override
public void actionPerformed(ActionEvent ae) {
String str=ae.getActionCommand();
System.out.println(str);
}
}
问题出现了,每次单击或拖动时,都会弹出无数个 JOptionPane 输入对话框,我别无选择,只能终止程序。
我没有把那段代码放在任何循环下。但也许是因为它在paintComponent 方法中。有什么办法可以根除这个问题?或者我可以使用其他方式让用户输入边缘的权重吗?