我可能做了一些非常愚蠢的事情,却看不到它,但我一直在试图将矩形的大小调整为条形图。代码符合,但在我的帧中什么也没有显示。完全空白。
package server2;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Bar extends JPanel implements Runnable {
int height = 0;
Color barColor;
Rectangle bar;
Thread bartender;
public Bar(int x, int y, Color barColor) {
this.barColor=barColor;
this.bar = new Rectangle(x, y, 15, this.height);
this.bartender= new Thread(this);
}
public void update() {
bar.setSize(this.bar.width, this.bar.height++);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(this.barColor);
g2d.fill(this.bar);
}
public void callBarTender() {
this.bartender.notify();
}
@Override
public void run() {
for(int i = this.bar.height; i<this.height; i++ ) {
try {
update();
repaint();
Thread.sleep(30);
} catch(Exception e) {
System.out.println(e);
}
}
try {
this.bartender.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Bar bar1 = new Bar(200,200, Color.blue);
bar1.setVisible(true);
frame.add(bar1);
bar1.height = 10;
bar1.bartender.start();
}发布于 2015-03-23 00:59:27
改变...
bar.setSize(this.bar.width, this.bar.height++);至
bar.setSize(this.bar.width, this.bar.height + 1);或
bar.setSize(this.bar.width, ++this.bar.height);this.bar.height++的赋值是一种被忽略的后分配。
你也应该改变这两行的顺序..。
bar1.setVisible(true);
frame.add(bar1);因此,setVisible是在您准备好UI之后调用的。
您还应该考虑使用Swing Timer,它可以更安全地更新UI或UI可能依赖的任何数据进行绘图。
https://stackoverflow.com/questions/29201736
复制相似问题