djangofan
djangofan

Reputation: 29669

Show .png image in a JFrame?

I am a little stuck. Why wont this work? I just get a error saying:

java.lang.NoSuchMethodError: main

Exception in thread "main"

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

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

  public void main(String arg) 
  { 
    if (arg == null ) {
        arg = "C:/Eclipse/workspace/ShowPNG/bin/a.png";
    }      
    JPanel panel = new JPanel(); 
    panel.setSize(500,640);
    panel.setBackground(Color.CYAN); 
    ImageIcon icon = new ImageIcon(arg); 
    JLabel label = new JLabel(); 
    label.setIcon(icon); 
    panel.add(label);
    this.getContentPane().add(panel); 
    this.setVisible(true);
  }
  
}

Upvotes: 5

Views: 34396

Answers (3)

djangofan
djangofan

Reputation: 29669

This was the finished code:

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

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

  public ShowPNG(String argx) { 
    if ( argx == null ) {
      argx = "a.png";
 }   
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
 this.setSize(500,640);
    JPanel panel = new JPanel();  
    //panel.setSize(500,640);
    panel.setBackground(Color.CYAN);  
    ImageIcon icon = new ImageIcon(argx);  
    JLabel label = new JLabel();  
    label.setIcon(icon);  
    panel.add(label); 
    this.getContentPane().add(panel);    
  } 

  public static void main(String[] args) { 
      new ShowPNG(args.length == 0 ? null : args[0]).setVisible(true);
  } 

}

Upvotes: 4

Leo Izen
Leo Izen

Reputation: 4289

main needs to be static, and must have an argument of String[], not String.

To fix this stick everything in a constructor, such as

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

@SuppressWarnings("serial")
public class ShowPNG extends JFrame
{    
  private ShowPNG(String arg){
      if (arg == null ) {
        arg = "C:/Eclipse/workspace/ShowPNG/bin/a.png";
    }      
    JPanel panel = new JPanel(); 
    panel.setSize(500,640);
    panel.setBackground(Color.CYAN); 
    ImageIcon icon = new ImageIcon(arg); 
    JLabel label = new JLabel(); 
    label.setIcon(icon); 
    panel.add(label);
    this.getContentPane().add(panel); 
  }
  public static void main(String[] args) {
      new ShowPNG(args.length == 0 ? null : args[0]).setVisible(true); 
  }
}

Upvotes: 10

robert_x44
robert_x44

Reputation: 9314

Your main method should be:

public static void main(String[] args)

Upvotes: 11

Related Questions