2016-05-10 14 views
-1

Wie JPanel zu JFrame in andere Klasse hinzufügen? Ich habe mit diesem Code versucht, aber wenn ich es kompiliere, zeigte es keine Komponente in MyFrame.java (das Label "Hello World"). Was ist falsch an meinem Code?Hinzufügen JPanel zu JFrame hat nicht funktioniert

(Button in MainFrame.java genannt MyFrame.java)

Hier ist der Code:

MyPanel.java (enthält Button und Label)

public class MyPanel extends javax.swing.JPanel { 

    public MyPanel() { 
     initComponents(); 
     myLabel.setText("Hello World"); 
    } 
} 

MyFrame.java

public class MyFrame extends javax.swing.JFrame { 

    MyPanel myPanel = new MyPanel(); 

    public MyFrame() { 
     initComponents(); 
     this.add(myPanel); 
    } 
} 

MainFrame.java

public class MainFrame extends javax.swing.JFrame { 

    public MainFrame() { 
     initComponents(); 
    } 

    private void btnCallFrameActionPerformed(java.awt.event.ActionEvent evt) {           
     new MyFrame().setVisible(true); 
    } 

    public static void main(String args[]) { 
     java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       new MainFrame().setVisible(true); 
      } 
     }); 
    } 
}  
+0

Für bessere Hilfe früher, post ein [MCVE] oder [kurze, unabhängige, korrekte Beispiel] (http://www.sscce.org/). –

Antwort

0

Ich weiß nicht, was Sie in initComponents Verfahren getan haben. Also habe ich deinen Code ein wenig geändert.

public class MyPanel extends javax.swing.JPanel { 

    public MyPanel() { 
     initComponents(); 
     //I don't know what you did in initComponents(); so I ve changed the layout to be sure that you didn't use null layout. 
     this.setLayout(new BorderLayout()); 

     JLabel myLabel = new JLabel(); 
     myLabel.setText("Hello World"); 

     //adding the label in MyPanel 
     this.add(myLabel); 
    } 
} 

public class MyFrame extends javax.swing.JFrame { 

    MyPanel myPanel = new MyPanel(); 

    public MyFrame() { 
     initComponents(); 
     // added because of the former reason 
     this.setLayout(new BorderLayout()); 
     this.add(myPanel); 
    } 
} 

Ich hoffe, Sie sicher sind, dass Sie die btnCallFrameActionPerformed Methode mit einigen Taste aufrufen können.