在 JLabel 中绘图

Drawing in JLabel

我在 JFrame 应用程序中绘图时遇到问题。我有这两个功能:

我对 Java 中的此类图形还很陌生,我想知道是否有人愿意帮助我。我需要在 JLabel 上添加名为 areaImage 的行。我尝试使用我在此处找到的一些已完成代码,但 none 对我有用。我的代码是否可用于某些错误?还是完全不好?

请不要只 post 一个 link 一些代码,我不够熟练,无法理解它然后更改它以使其适合我的应用程序...

这个只是制作 window,添加组件:

public void game (int difficulty)
{
    getContentPane().removeAll();

    areaImage = new JLabel ();
    areaImage.setBounds (50,100,650,500);
    areaImage.setForeground(Color.WHITE);   
    areaImage.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.BLACK));
    add(areaImage);

    paint (100,120,500,500, null);

    info = new JLabel ("  Write your answer into the text field");
    info.setBounds(730,180,250,50);
    info.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.BLACK));
    info.setFont(new Font ("Arial", Font.PLAIN, 15));
    areaImage.setForeground(Color.red);
    add(info);

    inputField = new JTextField("");
    inputField.setBounds(810, 240, 80, 50);
    add(inputField);

    checkAnswer = new JButton ("Check");
    checkAnswer.setBounds(750, 330, 200, 50);
    checkAnswer.setContentAreaFilled(false);
    checkAnswer.setOpaque(false);
    checkAnswer.addActionListener(this);
    checkAnswer.setFont (new Font("Arial",Font.PLAIN, 30));
    add(checkAnswer);

    next = new JButton ("Next");
    next.setBounds(750,440,200,50);
    next.setContentAreaFilled(false);
    next.setOpaque(false);
    next.addActionListener(this);
    next.setFont (new Font("Arial",Font.PLAIN, 30));
    add(next);

    end= new JButton ("Exit");
    end.setBounds (750,550,200,50);
    end.setFont(new Font("Arial", Font.PLAIN, 30));
    end.addActionListener(this);
    end.setOpaque(false);
    end.setContentAreaFilled(false);
    add(end);

    revalidate();
    repaint();
}

这个是绘图函数:

private void paint (int x, int xx, int y, int yy, Graphics g)
{
   super.paint(g);
   Graphics2D g2 = (Graphics2D) g;
   g.drawLine(x,y,xx,yy);
   Line2D lin = new Line2D.Float(100, 100, 250, 260);
   g2.draw(lin);
}

Please dont just post a link with some code, Im not skilled enough to understand it

嗯,这就是你学习的方式。你不能指望我们每次遇到一点问题就调试你的代码并重写它。如果您不愿意通过实​​际示例来学习,那么我不确定我们能如何帮助您。

I need to add the line on the JLabel

然后您需要覆盖 JLabel 的绘制代码。永远不要直接调用绘画方法,因为下一次 Swing 确定组件需要重新绘画时,绘画将会丢失。

所以从学习如何正确地绘画开始吧。 Custom Painting 上的 Swing 教程中有一个工作示例。第一个示例只是在面板上绘制一个字符串,但它很简单,您只需在标签上绘制一条线即可。这是您添加到 paintComponent() 方法的单个语句。

真正的问题是你为什么要在标签上画这条线?如果我们了解真正的需求,我相信会有更好的解决方案。您不应该对行的 location/size 进行硬编码,因为您不知道标签有多大。