【问题标题】:Why is this code not showing any oval为什么这段代码没有显示任何椭圆
【发布时间】:2013-10-31 08:47:46
【问题描述】:

我正在尝试在框架中添加一个椭圆形,并且在执行程序后显示框架,其中没有任何显示。背景颜色甚至来了。只有椭圆是不可见的。请提出建议。

   import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;

@SuppressWarnings("serial")
public class Example1 extends JFrame{


    Example1()
    {
        JFrame jp=new JFrame("spot");

         jp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        jp.setVisible(true);
        jp.setSize(400,400);

    }

  public void paint(Graphics g)
  {
      super.paint(g);
      g.setColor(Color.BLACK);

      g.fillOval(100,50,40,50);

  }

  public static void main(String...args)
{

    @SuppressWarnings("unused")
    Example1 obj = new Example1();


}
}

【问题讨论】:

  • 尝试先设置颜色g.setColor(Color.RED);再填充椭圆g.fillOval(100,50,40,50);,椭圆不用画,填充就行了。
  • 首先看你的问题的标题,纠正拼写错误
  • 对了,你是不是忘了把组件加到frame里(jp)?也许 jp.add(this) 在构造函数中!?
  • @user2511414...我没有使用任何组件..!!请看代码。

标签: java swing


【解决方案1】:

因为您在扩展的 JComponent 中绘制椭圆,而您没有在任何地方使用它。

您只是在使用 JFrame,设置它的背景颜色并显示它。您应该在 JFrame 的内容窗格中添加了扩展的 JComponent。

编辑

您正在扩展 JFrame 以覆盖 paint() 方法,没关系(但这不是正确的方法)。但是您没有使用它来显示 GUI。您正在 Example1 的构造函数中创建一些不同的 JFrame 并用它显示 GUI。

您应该显示您的扩展 JFrame。像这样:

    Example1 obj = new Example1();
    // Example1 extends JFrame, and overrides paint() method to display oval.
    // so display this Example1 frame, not creating some different JFrame.
    obj.setSize(400,400);
    obj.setVisible(true);

【讨论】:

  • 我现在只是扩展 JFrame。但仍然没有积极的结果。
  • 帮助很大!谢谢..!!
  • @user2935743, Or you should draw oval in overridden protected void paintComponent(Graphics g){} method of JFrame - JFrame 中没有 paintComponent() 方法,您也不应该覆盖 JFrame 中的 paint()。 You should have added extended JComponent in content pane of JFrame. - 这是正确的方法。阅读 Custom Painting 上的 Swing 教程部分以获取更多信息和示例。
【解决方案2】:

您先绘制,然后将颜色设置为红色。你认为这会改变你之前画的椭圆的颜色吗?

绘画步骤:

  1. 设置颜色
  2. 画

【讨论】:

  • 是的,因为您正在创建和显示一个新的 JFrame 而不是您的 Example1 类。使 Example1 扩展 JPanel 并将 jp.setContentPane(this) 放入构造函数中。然后阅读 Swing 教程,以便您学会正确地编写 Swing。
  • 如果我想向框架添加任何内容,我可以简单地使用 getContentPane() 而不是扩展 JPanel。为什么不必要地扩展 JPanel??
  • 如果您扩展 JPanel,您可以将您的类设置为内容窗格。现在您正在创建 2 个 JFrame 并做各种不必要的废话。为什么不先阅读教程?
  • 感谢所有骂人的人..!!但只是阅读对我也没有帮助。但是thanx,会再经历一遍。
猜你喜欢
  • 1970-01-01
  • 2011-01-31
  • 2016-05-10
  • 2021-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多