Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 向JFrame添加图像时出现的问题_Java_Eclipse_Swing_Jframe - Fatal编程技术网

Java 向JFrame添加图像时出现的问题

Java 向JFrame添加图像时出现的问题,java,eclipse,swing,jframe,Java,Eclipse,Swing,Jframe,我在向JFrame添加图片时遇到问题,可能缺少一些内容或写错了。 以下是课程: 主要类别: public class Tester { public static void main(String args[]) { BorderLayoutFrame borderLayoutFrame = new BorderLayoutFrame(); borderLayoutFrame.setDefaultClose

我在向JFrame添加图片时遇到问题,可能缺少一些内容或写错了。 以下是课程:

主要类别:

public class Tester

    {
        public static void main(String args[])
        {
            BorderLayoutFrame borderLayoutFrame = new BorderLayoutFrame();
            borderLayoutFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            borderLayoutFrame.setSize(600,600);
            borderLayoutFrame.setVisible(true);
        }
    }

public class BorderLayoutFrame extends JFrame implements ActionListener 
 {
     private JButton buttons[]; // array of buttons to hide portions
     private final String names[] = { "North", "South", "East", "West", "Center" };
     private BorderLayout layout; // borderlayout object
     private PicPanel picture = new PicPanel();

     // set up GUI and event handling

     public BorderLayoutFrame()
     {
         super( "Philosofic Problem" );
         layout = new BorderLayout( 5, 5 ); // 5 pixel gaps
         setLayout( layout ); // set frame layout
         buttons = new JButton[ names.length ]; // set size of array

         // create JButtons and register listeners for them

         for ( int count = 0; count < names.length; count++ ) 
         {
             buttons[ count ] = new JButton( names[ count ] );
             buttons[ count ].addActionListener( this );
         }
         add( buttons[ 0 ], BorderLayout.NORTH ); // add button to north
         add( buttons[ 1 ], BorderLayout.SOUTH ); // add button to south
         add( buttons[ 2 ], BorderLayout.EAST ); // add button to east
         add( buttons[ 3 ], BorderLayout.WEST ); // add button to west
         add( picture, BorderLayout.CENTER ); // add button to center
    }

    // handle button events

    public void actionPerformed( ActionEvent event )
    {

    } 

  }
公共类测试器
{
公共静态void main(字符串参数[])
{
BorderLayoutFrame BorderLayoutFrame=新的BorderLayoutFrame();
borderLayoutFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
borderLayoutFrame.setSize(600600);
borderLayoutFrame.setVisible(true);
}
}
公共类BorderLayoutFrame扩展JFrame实现ActionListener
{
私有JButton按钮[];//隐藏部分的按钮数组
私有最终字符串名称[]={“北”、“南”、“东”、“西”、“中”};
私有BorderLayout;//BorderLayout对象
私有PicPanel图片=新PicPanel();
//设置GUI和事件处理
公共边界布局框架()
{
超级(“哲学问题”);
布局=新边框布局(5,5);//5个像素间距
设置布局(布局);//设置框架布局
buttons=new JButton[names.length];//设置数组大小
//创建jbutton并为其注册侦听器
对于(int count=0;count
我试图将图像添加到布局的中心

以下是图像类:

public class PicPanel extends JPanel
{
    Image img;
    private int width = 0;
    private int height = 0;

    public PicPanel()
    {
        super();
        img = Toolkit.getDefaultToolkit().getImage("table.jpg");
    }
    public void paintComponent(Graphics g)
    {
         super.paintComponents(g);
         if ((width <= 0) || (height <= 0))
         {
             width = img.getWidth(this);
             height = img.getHeight(this);
         }
         g.drawImage(img,0,0,width,height,this);
    }
}
公共类PicPanel扩展了JPanel
{
图像img;
私有整数宽度=0;
私有整数高度=0;
公共事务委员会()
{
超级();
img=Toolkit.getDefaultToolkit().getImage(“table.jpg”);
}
公共组件(图形g)
{
超级组件(g);

如果((宽度在Eclipse中,如果您使用的是路径
“table.jpg”
,那么您需要该图像位于项目的顶层

有关Eclipse项目结构的更多信息,请参见

您可能希望尝试使用来显示图像,而不是在面板上绘制图像

下面的代码将创建一个
ImageIcon
,您可以将其添加到
JPanel

ImageIcon pic = new ImageIcon(getClass().getResource("myimage.jpeg");

这使用了一种奇特的方式来加载pic,这样它在放入Jar文件时就可以工作。

您发布的代码有几个问题:

  • 您应该在
    BorderLayoutFrame
    类中使用
    getContentPane().add()
    而不是简单地使用
    add()
  • 您应该真正使用
    SwingUtilities.invokeLater()
    从tester类启动JFrame。如下所示:

  • 不要使用Toolkit加载图像!在下面的代码中,如果“Table.jpg”与PicPanel在同一个包中,图像将正确加载

  • PicPanel.PaintComponent()
    中,您调用
    super.paintComponents()
    的“s”是类型o吗
  • PicPanel.PaintComponent()
    中,您不需要所有的宽度/高度信息,只需执行以下操作:

    g.drawImage(img,0,0,getWidth(),getHeight(),this);

同时避免调用super.paintComponent,因为您正在绘制图像,为什么要让面板绘制呢

我对你的东西的最终实现:

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                System.setProperty("DEBUG_UI", "true");

                BorderLayoutFrame blf = new BorderLayoutFrame();
                blf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                blf.setSize(600,600);
                blf.setVisible(true);
            }
        });
    }

}

class BorderLayoutFrame extends JFrame implements ActionListener
{
    private final BorderLayout layout;
    private final JButton[] buttons;
    private final String names[] = {"North", "South", "East", "West", "Center"};

    public BorderLayoutFrame() {
        super( "Philosofic Problem" );
        layout = new BorderLayout( 5, 5 );
        getContentPane().setLayout( layout );
        buttons = new JButton[ names.length ];

        for (int i=0; i<names.length; i++)
        {
            buttons[i] = new JButton(names[i]);
            buttons[i].addActionListener(this);
        }

        getContentPane().add(buttons[0], BorderLayout.NORTH);
        getContentPane().add(buttons[1], BorderLayout.SOUTH);
        getContentPane().add(buttons[2], BorderLayout.EAST);
        getContentPane().add(buttons[3], BorderLayout.WEST);
        getContentPane().add(new PicPanel(), BorderLayout.CENTER);
    }

    public void actionPerformed(ActionEvent e) {
        // ignore
    }

}

class PicPanel extends JPanel
{
    private URL rUrl;
    private BufferedImage img;



    public PicPanel() {
        super();
        try {
            rUrl = getClass().getResource("UtilBtn.png");
            if (rUrl != null) {
                img = ImageIO.read(rUrl);
            }
        } catch (IOException ex) {
            Logger.getLogger(PicPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        //super.paintComponent(g);

        g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
    }

}
公共类主{
/**
*@param指定命令行参数
*/
公共静态void main(字符串[]args){
SwingUtilities.invokeLater(新的Runnable(){
@凌驾
公开募捐{
setProperty(“DEBUG_UI”,“true”);
BorderLayoutFrame blf=新的BorderLayoutFrame();
blf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
blf.设置尺寸(600600);
blf.setVisible(真);
}
});
}
}
类BorderLayoutFrame扩展JFrame实现ActionListener
{
私人最终边界布局;
私有最终JButton[]按钮;
私有最终字符串名称[]={“北”、“南”、“东”、“西”、“中”};
公共边界布局框架(){
超级(“哲学问题”);
布局=新的边界布局(5,5);
getContentPane().setLayout(布局);
按钮=新的JButton[names.length];

对于(int i=0;i好问题-问题到底是什么?;-)您是否尝试过将图像面板添加到空的
JFrame
?如果这样做会发生什么?我已经尝试过了,我没有错误,但是除了按钮之外,框架上什么也没有显示。@firestruq,我添加了您可能想尝试的其他内容到我的答案中。ImageIcon的工作方式与我在答案中发布的ImageIO代码相同。
public PicPanel() {
    super();
    try {
        rUrl = getClass().getResource("Table.jpg");
        if (rUrl != null) {
            img = ImageIO.read(rUrl);
        }
    } catch (IOException ex) {
        Logger.getLogger(PicPanel.class.getName()).log(Level.SEVERE, null, ex);
    }
}
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                System.setProperty("DEBUG_UI", "true");

                BorderLayoutFrame blf = new BorderLayoutFrame();
                blf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                blf.setSize(600,600);
                blf.setVisible(true);
            }
        });
    }

}

class BorderLayoutFrame extends JFrame implements ActionListener
{
    private final BorderLayout layout;
    private final JButton[] buttons;
    private final String names[] = {"North", "South", "East", "West", "Center"};

    public BorderLayoutFrame() {
        super( "Philosofic Problem" );
        layout = new BorderLayout( 5, 5 );
        getContentPane().setLayout( layout );
        buttons = new JButton[ names.length ];

        for (int i=0; i<names.length; i++)
        {
            buttons[i] = new JButton(names[i]);
            buttons[i].addActionListener(this);
        }

        getContentPane().add(buttons[0], BorderLayout.NORTH);
        getContentPane().add(buttons[1], BorderLayout.SOUTH);
        getContentPane().add(buttons[2], BorderLayout.EAST);
        getContentPane().add(buttons[3], BorderLayout.WEST);
        getContentPane().add(new PicPanel(), BorderLayout.CENTER);
    }

    public void actionPerformed(ActionEvent e) {
        // ignore
    }

}

class PicPanel extends JPanel
{
    private URL rUrl;
    private BufferedImage img;



    public PicPanel() {
        super();
        try {
            rUrl = getClass().getResource("UtilBtn.png");
            if (rUrl != null) {
                img = ImageIO.read(rUrl);
            }
        } catch (IOException ex) {
            Logger.getLogger(PicPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        //super.paintComponent(g);

        g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
    }

}