簡體   English   中英

paintComponent 不在 JPanel 上繪制

[英]paintComponent doesn't draw on JPanel

我想在 JPanel(添加到 JScrollPane)上添加幾行帶有標簽(JLabel)的行。 早些時候,當我嘗試在框架上直接添加線條和 label 時,它可以正常工作(意味着線條和標簽可見),但在添加 JScrollPane 和 Jpanel 之后,線條不可見,但標簽可見。

知道這里有什么問題嗎?

public class gui {

static JFrame frame;
JPanel panel;

ArrayList<Line2D.Double> lines;

public gui() {
    panel = new JPanel();
    lines = new ArrayList<Line2D.Double>();
    
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            
            frame = new JFrame();
            
            addLine(10,10, 200,300);
            panel.repaint();
            
            panel.add(new test());
            
            panel.setPreferredSize(new Dimension(1200, 800));
        
            panel.setLayout(new BorderLayout());
            panel.setBackground(Color.WHITE);
            // Add scrollbar
            JScrollPane scrollBar=new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); 
            scrollBar.setPreferredSize(panel.getPreferredSize());
            
            frame.getContentPane().add(scrollBar);
            
            frame.getContentPane().validate();

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
            frame.pack();
            frame.setVisible(true);
        }
    });
}    


public void addLine(int x1, int x2, int x3, int x4) {
    lines.add(new Line2D.Double(x1, x2, x3, x4));
}

public class test extends JPanel {
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(1200, 800);
    }
    
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setColor(Color.BLACK);
        for (Line2D.Double line : lines) {
            drawArrow(g2d,
                (int)line.getX1(),
                (int)line.getY1(),
                (int)line.getX2(),
                (int)line.getY2()
                );
        }
    }
    
    void drawArrow(Graphics g1, int x1, int y1, int x2, int y2) {
        Graphics2D g = (Graphics2D) g1.create();
        System.out.println("here");
        double dx = x2 - x1, dy = y2 - y1;
        double angle = Math.atan2(dy, dx);
        int len = (int) Math.sqrt(dx*dx + dy*dy);
        AffineTransform at = AffineTransform.getTranslateInstance(x1, y1);
        at.concatenate(AffineTransform.getRotateInstance(angle));
        g.transform(at);

        // Draw horizontal arrow starting in (0, 0)
        g.drawLine(0, 0, len, 0);
        g.fillPolygon(new int[] {len, len-ARR_SIZE, len-ARR_SIZE, len},
                      new int[] {0, -ARR_SIZE, ARR_SIZE, 0}, 4);
    }
}

得到它的工作通過更換

panel = new JPanel();

panel = new test();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM