【发布时间】:2020-11-20 09:56:44
【问题描述】:
在我之前关于Drawing rectangle within the loop?的问题之后
现在我想从另一个类中绘制矩形,在 for 循环内。这是循环的类:
public class FaceDetect extends SwingWorker {
IntegralCalc3 ic3 = new IntegralCalc3();
MainFrame mf = new MainFrame();
Rectangle R;
protected FaceDetect doInBackground() throws Exception {
//Initial width and height is 60, 60
outerloop:
for(int w = 50; w <= ic3.integral.length && w <= ic3.integral[0].length; w = (int) Math.round(w*1.2) ) {
int h = w;
for(int x = 0; x <= ic3.integral.length-w; x+=5 ) {
for(int y = 0; y <= ic3.integral[0].length-w; y+=5 ) {
R = new Rectangle (x, y, w, h);
mf.lm.add(R);
mf.lm.revalidate();
mf.lm.repaint();
}
}
}
return null;
}
}
这是我的矩形类:
public class Rect extends JComponent {
public int x;
public int y;
public int w;
public int h;
public Rect (int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
repaint();
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g);
g2.setColor(Color.green);
g2.drawRect(x+15, y+15, w, h);
}
}
最后是我在 JFrame 类中的按钮:
public class MainFrame extends JFrame {
Rect R = new Rect(15, 15, 50, 50);
JPanel lm = new JPanel();
LayoutManager lay = new OverlayLayout(lm);
JButton animate = new JButton("animate");
public MainFrame () {
setSize(1200, 700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
lm.setLayout(lay);
lm.add(R);
}
animate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
new FaceDetect().execute();
} catch (Exception ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
public static void main(String[] args) {
EventQueue.invokeLater(() -> new MainFrame());
}
}
但是当我点击animate 按钮时什么也没发生。我的代码缺陷在哪里?
【问题讨论】:
-
您必须在事件调度线程 (EDT) 上调用
repaint()方法。方法doInBackground()确实不在 EDT 上运行。参考Concurrency in Swing