0

Java コードでは解決できないような問題があります。

マップを表示するプログラムを作成しました。マップをクリックすると、マップ上にエッジ/ノードが点線で表示されます.2つのノードを互いに接続すると、接続された点の間に線が表示されます.

ここまではよかった、と思ったのですx1,y1x2,y2...

私を怖がらせているのはsetBoundsであることがわかりました...しかし、私は自分の問題を解決する方法がわかりません。また、どこにも似たような問題を見つけることができないようです...誰かがこの種の問題に遭遇しましたか? 、もしそうなら、どのようにこれを解決しましたか?

import java.awt.*;
import javax.swing.*;

public class DrawMyLine extends JComponent{
    private int fx, fy, tx, ty;
    private int h,w;
    private int m;
    private double k;
    private Destinations from;
    private Destinations to;

public DrawMyLine(Destinations from, Destinations to){
    this.from=from;
    this.to=to;
    setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

    fx = from.getX();
    fy = from.getY();
    tx = to.getX();
    ty = to.getY();


    //w = Math.abs(tx - fx);
    //h = Math.abs(ty - fy);
    w = tx - fx;
    h = ty - fy;

    int x,y;

    if(ty>fy){ //This is my, not so great solution so far...
        x = fx;
        y = fy;
    }
    else{
        x = tx;
        y = ty;
    }

    setBounds(x+5,y+5, w, h); //How do I reverse the boundary?
    setPreferredSize(new Dimension(w, h));
    setMinimumSize(new Dimension(w, h));
    setMaximumSize(new Dimension(w, h));
    }

//@Override
protected void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        g.drawLine(0,0,w,h);
}

//Method to reduce the clickable area to 5 pixels from the line
public boolean contains(int x, int y){

    k = ((ty-fy)/(tx-fx));
    if(k >= 0){
        m = 0;
    }
    else{
        m = ty - fy;
    }
    return Math.abs(y - k * x - m) < 5;
}//contains 

public Destinations getFrom(){
    return from;
}
public Destinations getTo(){
    return to;
}

}

そして主に(2つのノードが接続されている場合):

DrawMyLine dml = new DrawMyLine(from,to);
panel.add(dml);
panel.repaint();
dml.addMouseListener(lineListener);

誰でも私を助けることができますか?お願いします!

4

2 に答える 2

1

境界を逆にしないで、レンダリングを逆にします。

これについて考えます...

ここに画像の説明を入力 ここに画像の説明を入力

上の画像で変更されているのは、始点と終点だけです。長方形のサイズは変更されていません。

すべての境界は正の値で機能する必要があります。Swing では、負のサイズの四角形は存在しません。

私の例は を使用してレンダリングされましたjava.awt.Pointが、基本的な概念はそのままです...

// Find the smallest point between the two
int x = Math.min(p1.x, p2.x);
int y = Math.min(p1.y, p2.y);
// Size is based on the maximum value of the two points differences...
int width = Math.max(p1.x - p2.x, p2.x - p1.x);
int height = Math.max(p1.y - p2.y, p2.y - p1.y);

これで、効果領域のサイズが得られます。線を引くことは、2 点間に線を引くこと0, 0, width, heightです (使用した点ではなく)。

于 2013-04-12T00:48:11.180 に答える