@trashgod所以我放入了一个非空的 start() 方法,并添加了一个 JPanel,它制作了一个旋转正方形(使用从 start() 开始的线程动画)。我仍然发现 init1() 和 init2() 的行为完全相同。小心向 OP(和我自己)解释为什么您更喜欢在这种情况下使用 invokeAndWait() 。
@Andrew我知道我对上面的答案不正确。请详细说明我为什么不对,以及正确答案是什么。我试图遵循您的一个答案,但链接已断开。
这是可编译的应用程序(是的,通常我会将其放入 3 个单独的类中,但在这里我们试图回答一个特定问题)。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class P4 extends JApplet implements ActionListener {
private Frame frame; // null/applet, non-null/application
private Painter painter = new Painter();
public P4 () { super(); }
public P4 (Frame f) { this(); frame = f; }
public void init () {
// init1(); // better for application
init2(); // better for applets
}
public void init1 () {
createGUI();
}
public void init2 () {
try {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}}
private void createGUI () {
JPanel p = new JPanel(new BorderLayout());
JButton b = new JButton ("Click to say Hello to the world");
b.addActionListener (this);
p.add (b, "South");
p.add (painter, "Center");
if (frame != null) { // application
b = new JButton ("Exit");
b.addActionListener (this);
p.add (b, "North");
}
getContentPane().add(p);
}
public void actionPerformed (ActionEvent e) {
if ("Exit".equals (e.getActionCommand()))
System.exit (0);
JOptionPane.showMessageDialog (frame, "Hello, world!");
}
public void start () { new Thread (painter).start(); }
public void stop () { }
public void paint (Graphics g) {
super.paint (g);
}
public static void main (String[] args) {
JFrame fr = new JFrame ("Appletication");
P4 p4 = new P4 (fr);
p4.init(); p4.start(); // initialize GUI
fr.add (p4); fr.pack(); fr.setVisible (true);
}
public class Painter extends JPanel implements Runnable {
private int state, px[] = new int[4], py[] = new int[4];
public Painter () {
super();
setPreferredSize (new Dimension (300, 200));
}
public void run () {
for ( ; ; ) {
if (++state == 45)
state = 0;
repaint();
try {
Thread.sleep (25);
} catch (InterruptedException ex) {
}}}
public void paint (Graphics g) {
int w = getWidth(), h = getHeight(),
cx = w/2, cy = h/2, halfD = (cx < cy) ? cx : cy;
halfD -= 10;
Graphics2D g2 = (Graphics2D) g;
g2.setPaint (Color.white); g2.fillRect (0,0,w,h);
for (int i = 0 ; i < 4 ; i++) {
double theta = (i*90 + 2*state) * Math.PI / 180;
px[i] = (int) Math.round (cx + halfD * Math.cos (theta));
py[i] = (int) Math.round (cy - halfD * Math.sin (theta));
}
g2.setPaint (Color.red);
g2.fillPolygon (px, py, 4);
}}}