2010-11-12 6 views
4

Je suis un peu coincé. Pourquoi ne pas ce travail? Je viens de faire une erreur en disant:Afficher une image .png dans un JFrame?

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); 
    } 

} 
+2

s/void main publique (String arg)/publique ** statique ** void main (String ** [] ** arg) – OscarRyz

Répondre

8

principaux besoins d'être statique et doit avoir un argument de String [], non String.

Pour résoudre ce bâton tout dans un constructeur, comme

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); 
    } 
} 
+0

RD avait raison, que la méthode principale était incorrecte mais Leo Izen obtient cette réponse car il fournit tout le code. Ce code n'a cependant pas fonctionné ... vous devez utiliser this.setSize sur le JFrame pour le redimensionner correctement. Merci quand même! Voir mon message ci-dessous pour la réponse réelle. – djangofan

+1

Vous pouvez toujours utiliser Frame.pack(); –

11

Votre principale méthode doit être:

4

Ce fut le code fini:

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); 
    } 

} 
+1

Modifier 'this.setSize (500,640); .. this.getContentPane(). Add (panneau); 'for' .. this.getContentPane(). Add (panneau); this.pack(); ' –

Questions connexes