我正在开发一个项目,我必须在其中模拟内存管理器并显示一些内存快照。我通过我在这里找到的示例创建了一个绘图类,其中我重写了paintComponet()。一切都很好。
我希望能够绘制一个矩形来表示内存分区,然后在顶部覆盖另一个矩形来表示传入的作业(即Job1在此分区3中)。似乎发生的是我首先添加分区(总是如此)然后当我添加作业时它将位于分区块后面。除了首先绘制Job之外,还有其他方法可以在创建作业后将它们移动吗?
这是油漆覆盖
@Override public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
// set up rendering to allow anti-aliasing
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// create the rectangle to represent the memory partition block
// x = address position h = amount of memory (y & w are predefined for the display block)
Rectangle2D rect = new Rectangle2D.Double(x, y, w, h); // create the rectangle
g2d.setPaint(partColor); // set it's color
g2d.fill(rect); // fill it in
// create the transparency for the text
Composite comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .4f);
g2d.setComposite(comp);
// draw the text with color, type and size and center the text in the block created above
g2d.setPaint(Color.black);
g2d.setFont(new Font("Tahoma", Font.PLAIN, 12));
g2d.drawString(text, (int)((w / 2) - (text.length()/2)), (int)h/2);
}
绘制调用是在我的窗口类中(这会将分区放在作业前面)但我需要在不改变调用顺序的情况下进行反转。
// Draw both Text and Block with transparency
DrawPartition part1 = new DrawPartition(Color.blue, 0, 0, 110, 100, "part1");
part1.setBounds(5, 5, 110, 100);
snapPanel.add(part1);
DrawJob job1 = new DrawJob(Color.green, 0, 0, 110, 100, "Job 1");
job1.setBounds(5, 15, 110, 100);
snapPanel.add(job1);
答案 0 :(得分:0)
有什么理由你不能这样做吗?
// Draw both Text and Block with transparency
DrawPartition part1 = new DrawPartition(Color.blue, 0, 0, 110, 100, "part1");
part1.setBounds(5, 5, 110, 100);
DrawJob job1 = new DrawJob(Color.green, 0, 0, 110, 100, "Job 1");
job1.setBounds(5, 15, 110, 100);
snapPanel.add(job1);
snapPanel.add(part1);
更常见的答案是为每个矩形添加一个z组件。然后,您可以在paintComponent方法中循环遍历矩形,按z顺序绘制它们。