简体   繁体   中英

add jpanel from method to jframe

In my project I have some classes. One class to create the gui, except of the JFrame. I will create the JFrame in my Main class such as:

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

public class KodeHusker {

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable(){
        @Override
        public void run(){
            JFrame f = new JFrame();
            f.setLayout(new FlowLayout());
            f.add(new JLabel("test"));
            f.add(new GUI().viewProgram());//it works fine, when i remove this
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }
    });
}
}

the gui class is where I create all the gui, and the viewProgram method is declared as:

public JPanel viewProgram(){}

which returns a JPanel.

As the comment in the code tells, when I remove that line it all works fine, but when I have it, the JFrame never shows, although there aren't any exceptions. The shortcut to close the program doesn't work neither.

Anybody who has an idea of what i'm doing wrong? Thanks in advise.

here is what a jPanel should look like, not sure (can see your code?)

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class JPanelExt extends JPanel  implements Runnable {
private int xCoor = 50;
private boolean moving = false;

 public JPanelExt() {       
      //Thread 
          thread = new Thread (this);       //
          thread.start();   }   

  public void paintComponent (Graphics g)
     {  
            super.paintComponent(g);
    g.drawString("DVC 10.0",xCoor,30);  
            g.drawRect(50, 50, 200,100);    
            g.drawOval(50,50,200,100);  
}   
    @Override
public void run() {
while (true)
        {   
    if (moving==true)
                   {    
          this.xCoor = this.xCoor+10;
        if (xCoor > this.getWidth())
                             {  
            xCoor = 0;      
                       }
            this.repaint(); 
               }        
        try {
            Thread.sleep(50);
        }
                catch (InterruptedException e) {    
        e.printStackTrace();            
                    }   
   }    
   public void setMoving(boolean moving) 
       {    
            this.moving = moving;   
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM