How do I display a line in a Java GUI?

前端 未结 2 372
感动是毒
感动是毒 2021-01-27 06:48

I would like to draw a line between 2 images in Java swing.

I have found different ways of drawing lines but none the way that I want to which makes me think maybe I jus

相关标签:
2条回答
  • 2021-01-27 07:04

    As I pointed out in my comment, you could just just draw a line, then draw the images over the line at set increment points

    enter image description here

    import java.awt.*;
    import javax.swing.*;
    
    public class Test {
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    final Image image = new ImageIcon(Test.class
                            .getResource("/resources/images/stackoverflow.png"))
                            .getImage();
                    final BasicStroke stroke = new BasicStroke(5f);
                    JPanel panel = new JPanel() {
                        @Override
                        protected void paintComponent(Graphics g) {
                            super.paintComponent(g);
                            Graphics2D g2 = (Graphics2D) g;
                            g2.setStroke(stroke);
                            g2.drawLine(10, 75, 290, 75);
                            for (int x = 10; x < 300; x += 50) {
                                g2.drawImage(image, x, 59, this);
                            }
                        }
    
                        @Override
                        public Dimension getPreferredSize() {
                            return new Dimension(300, 150);
                        }
                    };
    
                    JOptionPane.showMessageDialog(null, panel, "Line With Images",
                            JOptionPane.PLAIN_MESSAGE);
                }
            });
        }
    }
    
    0 讨论(0)
  • 2021-01-27 07:07

    just invoke the method drawLine() and insert the parameters for the position :)

    0 讨论(0)
提交回复
热议问题