我有一個擴展JPanel的類(時間軸)。時間軸面板包含許多手動定位的JLabel(綠色和橙色元素)(「null-Layout」)。在時間軸之上是幾個月之間切換的按鈕。有時候,當我在幾個月之間切換時,swing不會繪製JLabels,但總是會繪製網格背景。在Swing中繪畫
我已經嘗試了許多的「神奇」的方法(重畫,重新驗證,廢止,驗證,updateUI)。
成功繪時間軸:
失敗畫:
簡單例子:
public interface IDateSelectorRegistrar {
void addListener(DateSelectorListener listener);
void removeListener(DateSelectorListener listener);
}
public interface DateSelectorListener {
void dateChanged(Timestamp from, Timestamp to);
}
public interface ITimelineModel {
Timespan[] getTimespans(Timestamp from, Timestamp to);
}
public class Timespan {
private String title;
private Timestamp to;
private Timestamp from;
public Timespan(String title, Timestamp from, Timestamp to) {
this.title = title;
this.from = from;
this.to = to;
}
// setters and getters
}
public class TimelineLabel extends JLabel {
public TimelineLabel(Timespan timespan) {
super(timespan.getTitle());
}
@Override
protected void paintComponent(Graphics g) {
// paint colored background
super.paintComponent(g);
}
}
public class Timeline extends JPanel {
public Timeline(final ITimelineModel model, IDateSelectorRegistrar registrar) {
registrar.addListener(new DateSelectorListener() {
public void dateChanged(Timestamp from, Timestamp to) {
Timeline.this.removeAll();
Timespan[] timespans = model.getTimespans(from, to);
for(Timespan timespan : timespans) {
TimelineLabel label = new TimelineLabel(timespan);
Timeline.this.add(label);
// label positioning because of Timestamp object data
}
// repaint of timeline
Timeline.this.invalidate();
Timeline.this.repaint();
}
});
}
@Override
protected void paintComponent(Graphics g) {
// paint background grid
super.paintComponent(g);
}
}
當畫失敗,你檢查是否你的相應塗料/的paintComponent方法被調用? – ARRG
@endian我從來沒有看到的是,你把那些的JLabel的JPanel中的工具插圖???, – mKorbel
中的JLabel的paintComponent方法裏面不叫。 – endian