[英]JPanel isn't visible in JFrame
我知道有人問過這類問題,但我找不到解決方案。
我正在嘗試在我的JPanel中繪制一些動畫,該動畫將在JFrame中。 JPanel不可見,JFrame以及我放置在其中的測試標簽都可見。 另外,由於某種原因,我無法設置JFrame背景。 這是無效的代碼:(構造函數在項目的另一個類中)。
public class WindowClass extends JPanel implements ActionListener{
Graphics graphics;
JFrame window;
Timer timer;
private JLabel label = new JLabel("Best Label Around");
private int height;
private int width;
private Color bgColor;
public void init(){
window = new JFrame("Jumping Balls");
window.add(this);
window.add(label);
this.setSize(150,150);
window.setSize(500, 300);
window.setDefaultCloseOperation(window.EXIT_ON_CLOSE);
window.setVisible(true);
setVisible(true);
//timer = new Timer(100, this); //TODO
//timer.start();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
setBackground(Color.BLUE);
}
順便說一句-這是另一個程序的另一個非常相似的代碼,它確實起作用,我不知道為什么,它確實讓我大吃一驚。這是他的一些代碼:
public class ShowClass extends JPanel implements ActionListener{
int count=0;
Graphics graphics;
JFrame window;
Timer timer;
Random random = new Random();
Color generalColor = Color.BLACK;
int wHeight = 400;
int wWidth = 550;
final int MAXSIZE = 60; //Ball's Maximum Size
//BackGround colors
int randomRed = 100;
int randomGreen = 100;
int randomBlue = 100;
//Ball colors
int randomBallRed = 255;
int randomBallGreen = 255;
int randomBallBlue = 255;
public void init(){
window = new JFrame("Jumping Balls");
window.add(this);
window.setSize(wHeight, wWidth);
window.setDefaultCloseOperation(window.EXIT_ON_CLOSE);
window.setVisible(true);
timer = new Timer(100, this); //TODO
timer.start();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
setBackground(new Color(randomRed,randomGreen,randomBlue));
for(Ball b : ManagerClass.balls){
//b.setBallColor(new Color(randomRed,randomGreen,randomBlue)); TODO
g.setColor(b.getBallColor());
g.fillOval((int)b.getLocation().getX(),(int)b.getLocation().getY(),b.getHeight(),b.getWidth());
}
}
謝謝!
默認情況下,窗口(特別是窗口的內容窗格)使用BorderLayout
布局管理器。
BorderLayout
具有五個位置-頂部,底部,左側,右側和中央。 add
組件add
到BorderLayout
,如果不指定位置,則默認為中心。 每個位置只能容納一個組件。
這個:
window.add(this);
window.add(label);
this
添加到中心位置。 然后將其添加label
到中心位置-其去除this
,因為只有一個組件可以是在中心。
您可以使用其他布局管理器(不在此答案范圍內),也可以繼續使用BorderLayout
並顯式設置位置。 后者的示例,假設您希望標簽顯示在面板上方:
window.add(this, BorderLayout.CENTER); // or just window.add(this);
window.add(label, BorderLayout.NORTH);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.