java - 在正确的框架中加载图像时出现问题

标签 java image filechooser

这是我在主框架窗口中的代码:

public class DynamicalSystem {


    public static  void createAndShowGraphic() {


    //Create and set up the window.
    JFrame frame = new JFrame("Dynamical System: The beauty of Chaos");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel emptyLabel = new JLabel("");
    emptyLabel.setPreferredSize(new Dimension(500, 500));
    frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);




    //Display the window.

    MenuLook menubar = new MenuLook();  //display menubar
    frame.setJMenuBar(menubar.createMenuBar());

    frame.pack();
    frame.setVisible(true);




 }
}

这是来 self 的缓冲图像:

public class LabelDemo extends JPanel
{
//path of image
private String path;

//image object
private Image img;

public LabelDemo(String path) throws IOException
{
//save path
this.path = path;

//load image
img = ImageIO.read(new File(path));

}

//override paint method of panel
public void paint(Graphics g)
{
//draw the image
if( img != null)
g.drawImage(img,0,0, this);
}

}
//class image frame periexei tin methodo createloadimage i opoia pernei
//to path apo ton filechooser kai kanei load tin eikona

class ImageFrame{

    public static void createLoadImage(){

       try
    {

        //create frame
        JFrame f = new JFrame();

        //ask for image file
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(f);

        //create panel with selected file
        LabelDemo panel = new LabelDemo( chooser.getSelectedFile().getPath() );

        //add panel to pane
        f.getContentPane().add(panel);


        //show frame
        f.setBounds(0,0,800,800);
        f.setVisible(true);
    }
        catch(Exception e)
         {
         System.out.println ( "Den dialeksate eikona!");
         }
   }
}

我希望图像在我的主窗口中打开,而不是在新窗口中打开。我该怎么做?

最佳答案

也许我遗漏了一些东西,但看起来您实际上根本没有将图像放入主框架中,从您的问题来看,主框架似乎是 DynamicalSystem。相反,看起来您正在 ImageFrame 中创建一个新窗口并将图像放在那里。尝试调用

LabelDemo panel = new LabelDemo( Chooser.getSelectedFile().getPath() );

来自 DynamicalSystem 并将 LabelDemo 放入该帧而不是 ImageFrame 中。

关于java - 在正确的框架中加载图像时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5652614/

相关文章:

java - JAX-RS 1.1 的最低 Servlet API 版本

java - 如何左旋转数组的元素

java - BouncyCasLe 错误 : can't recognise key type in ECDSA based signer

wpf - 通过样式将按钮的内容设置为 <Image>

html - 更改 div 中的图像背景位置?

Android - 如何从用户选择的歌曲创建 MediaPlayer

java - 将 ISO 时间戳格式的 Java String 转换为 SimpleDateFormat

C# 通过 HTTP 发送图像

android - 如何在android中选择文件夹?

安卓文件选择器