我问了一个有关自定义小部件的问题,但对我是否需要它以及应该如何进行感到困惑。
我目前有这门课
public class GUIEdge {
public Node node1;
public Node node2;
public int weight;
public Color color;
public GUIEdge(Node node1, Node node2 , int cost) {
this.node1 = node1;
this.node2 = node2;
this.weight = cost;
this.color = Color.darkGray;
}
public void draw(Graphics g) {
Point p1 = node1.getLocation();
Point p2 = node2.getLocation();
g.setColor(this.color);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g.drawLine(p1.x, p1.y, p2.x, p2.y);
}
}
目前,这在两点之间绘制了一条边,但现在我希望成本标签也随之创建。
我已经添加了用于拖动节点和边缘的处理,那么创建标签的最佳方法是什么
我需要为此制作一个自定义小部件吗?谁能解释一下,假设通过从 JComponent 扩展来创建一个组件,然后我将通过 g.mixed() 来调用它,其中 mixed 是新的小部件......?
工具提示当然值得一看。其他选择包括drawString(), translate(), or TextLayout。有许多examples可用的。
附录:下面的示例显示了两者drawString()
and setToolTipText()
,正如@Catalina Island 所建议的。为了简单,端点相对于组件的大小,因此您可以看到调整窗口大小的结果。
附录:使用setToolTipText()
仅演示该方法。正如@camickr 所说here,你应该覆盖getToolTipText(MouseEvent)
并在鼠标悬停在线上或选择该线时更新提示。
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JComponent;
import javax.swing.JFrame;
/** @see https://stackoverflow.com/questions/5394364 */
public class LabeledEdge extends JComponent {
private static final int N = 20;
private Point n1, n2;
public LabeledEdge(int w, int h) {
this.setPreferredSize(new Dimension(w, h));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
this.n1 = new Point(N, N);
this.n2 = new Point(getWidth() - N, getHeight() - N);
g.drawLine(n1.x, n1.y, n2.x, n2.y);
double d = n1.distance(n2);
this.setToolTipText(String.valueOf(d));
g.drawString(String.valueOf((int) d),
(n1.x + n2.x) / 2, (n1.y + n2.y) / 2);
}
private static void display() {
JFrame f = new JFrame("EdgeLabel");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new LabeledEdge(320, 240));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
display();
}
});
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)