gpt4 book ai didi

java - 在 Swing 中绘画

转载 作者:行者123 更新时间:2023-12-02 08:00:18 25 4
gpt4 key购买 nike

我有一个扩展 JPanel 的类(Timeline)。时间轴面板包含许多手动定位的 JLabel(绿色和橙色元素)(“空布局”)。时间轴顶部有一些用于在月份之间切换的按钮。有时,当我在几个月之间切换时,swing 不会绘制 JLabels,但总是绘制网格背景。

我已经尝试过许多“神奇”方法(重绘、重新验证、无效、验证、updateUI)。

成功绘制时间轴:

Timeline succesful

绘画失败:

Timeline failed

一个简短的例子:

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);
}
}

最佳答案

作为替代方案,请考虑 org.jfree.chart.renderer.category.GanttRenderer ,这是时域图的理想选择,并且允许各种定制。如下所示的示例可以在 here 中找到。 .

Gantt Subtasks

关于java - 在 Swing 中绘画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8988645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com