【发布时间】:2015-04-15 08:21:28
【问题描述】:
我知道有人问过这类问题,但我找不到任何解决问题的方法。
我正在尝试在我的 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());
}
}
谢谢!
【问题讨论】:
-
你想如何在窗口中排列标签和面板?
-
请看这个线程,关于JComponent not showing Picture background。希望这可以为您解决问题 :-) 此外,避免设置属性,就像您在
paintComponent(...)方法中执行setBackground(...)一样。大多数布局都尊重组件的大小,在这种情况下,JPanel的大小为(0, 0),这就是它没有显示的原因。尝试overrideJComponent.getPreferredSize()方法(示例) -
我已经更改了 setBackground() 的位置,并且也更改了 getPreferredSize() 的位置,但它仍然不起作用。我最大的问题是为什么这段代码不起作用并且第二个,几乎是一样的,有用吗?
-
您是否将两个类(ShowClass 和 WIndowClass)作为一个项目一起运行?你在EventDisptacherThread上运行与Swing相关的代码吗?
标签: java swing jframe jpanel visibility