【问题标题】:Adding component to window向窗口添加组件
【发布时间】:2014-11-01 03:11:14
【问题描述】:

GraphicsWindow 类:

import java.awt.*;
import java.awt.geom.*;
public class GraphicsWindow extends BlankWindow
{
    public void paintComponent(Graphics g)
    {
        Graphics2D g2d = (Graphics2D) g;
        this.setBackground(Color.ORANGE);
    }
}

BlankWindow 类(主):

import java.awt.*;
import javax.swing.*;
import java.awt.Container;
public class BlankWindow extends JFrame
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Picture");
        JPanel pane = new JPanel();
        frame.setSize(400,500);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setVisible(true);

        GraphicsWindow component = new GraphicsWindow();
        frame.add(pane);
        pane.add(component);
    }
}

我在 pane.add(component) 上遇到错误;每当我尝试运行它时。

【问题讨论】:

  • GraphicsWindow 应该扩展 JPanel 而不是 BlankWindow
  • 您正在将 JFrame 添加到 JFrame 中——您不能这样做,并且您正在尝试在 JFrame 的 paintComponent 方法中进行绘制,这是该类所没有的方法。最重要的是,您的所有代码都只是猜测,这是行不通的。阅读 Swing 图形教程,这样您就不必猜测了。更多信息请查看this Swing info link

标签: java swing class jframe components


【解决方案1】:

在您的GraphicsWindow 中,您必须扩展javax.swing.JComponent 而不是BlankWindow

来源:http://docs.oracle.com/javase/tutorial/uiswing/painting/closer.html

【讨论】:

    猜你喜欢
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 2014-04-22
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多