[英]add jpanel from method to jframe
在我的項目中,我有一些課程。 除了JFrame外,一類用於創建gui。 我將在我的Main類中創建JFrame,例如:
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);
}
});
}
}
gui類是我創建所有gui的地方,並且viewProgram方法聲明為:
public JPanel viewProgram(){}
它返回一個JPanel。
正如代碼中的注釋所表明的那樣,當我刪除該行時,一切正常,但是當我擁有該行時,盡管沒有任何異常,但JFrame卻從不顯示。 關閉程序的快捷方式也不起作用。
有人知道我在做什么錯嗎? 感謝您的建議。
這是jPanel的外觀,不確定(可以看到您的代碼嗎?)
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.