Creating labels along with drawlines

前端 未结 2 936
执念已碎
执念已碎 2021-01-23 09:26

I have asked a question regarding custom widget but confused to whether I need it and how should proceed.

I have currently this class

public class GUIEdg         


        
相关标签:
2条回答
  • 2021-01-23 09:52

    I think you can use GUIEdge extends JComponent. That way you'd get tool tip labels automatically.

    0 讨论(0)
  • 2021-01-23 10:02

    Tool tips are certainly worth a look. Other choices include drawString(), translate(), or TextLayout. There are many examples available.

    Addendum: The example below shows both drawString() and setToolTipText(), as suggested by @Catalina Island. For simplicity, the endpoints are relative to the component's size, so you can see the result of resizing the window.

    Addendum: This use of setToolTipText() merely demonstrates the approach. As @camickr notes here, you should override getToolTipText(MouseEvent) and update the tip when the mouse is over the line or when the line is selected.

    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();
                }
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题