【问题标题】:Graphics not working in Java图形在 Java 中不起作用
【发布时间】:2014-07-01 23:57:32
【问题描述】:

我试图在 java 中处理一些图形,但是我无法让它工作。 JFrame 带有我创建的按钮,但 JFrame 只是灰色的,没有我想要它绘制的红线。

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;


public class Shapes extends JFrame implements ActionListener{

JButton button = new JButton("click");
public Shapes() {
    setVisible(true);
    setSize(500, 500);
    button.addActionListener(this);
    button.setSize(20, 20);
    setLayout(new FlowLayout());
    add(button);
    repaint();
}
public static void main(String[] args){
    Shapes s = new Shapes();   
}


public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.red);
    g2.drawLine(5, 10, 10, 20);
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == button){
        repaint();
    }
 }
}

【问题讨论】:

  • 不要直接在JFrame 上绘画,而是使用JPanel
  • 如果我将其更改为 JPanel,当我启动程序时,程序会在 1-2 秒后自行结束,而不会显示 JPanel。另外,我不能将 repaint() 与 JPanel 一起使用。能详细点吗?
  • 我发布了一个更详细的答案
  • 1) 正如@BitNinja 所说,您在 JPanel 中绘画,然后将 JPanel 添加到 JFrame 中,然后显示。 2) 在您尝试覆盖的方法之前,您应该始终使用 @Override 注释。如果你这样做了,你会发现 JFrame 没有 paintComponent(...) 方法。
  • 感谢您帮助我 :) 我开始明白了。

标签: java swing jframe paintcomponent repaint


【解决方案1】:

两件事:

1)。您真的不想在诸如JFrame 之类的顶级容器上进行自定义绘制。相反,您想使用JPanel

class Panel extends JPanel
{
    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.red);
        g2.drawLine(5, 10, 10, 20);
    }
}

并将其添加到您的JFrame:add(new Panel());(或者如果您愿意,可以创建一个对象)。

2)。 setVisible(true); 应该是您在设置窗口时做的最后一件事。所以改变你的构造函数:

public Shapes() {
setSize(500, 500);
button.addActionListener(this);
button.setSize(20, 20);
setLayout(new FlowLayout());
add(button);
add(new Panel()) // added from part 1
repaint();
setVisible(true);
}

更多信息请通过"performing custom painting tutorials."

【讨论】:

  • 1+,但不要忘记建议在您的覆盖范围内调用 super.paintComponent(g) 方法。
  • 感谢大家抽出宝贵时间帮助我 :)
  • @user3795758 如果此答案解决了您的问题,请单击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
猜你喜欢
  • 2014-05-03
  • 2016-07-02
  • 2018-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多