基本上,我有一个JApplet,试图与图形(即,g.drawOval(10,10,100,100),也包括JCompotents (即.JButton)。发生的情况是,重新绘制可能会变得非常古怪。
有时图形会绘制在窗口小部件上,反之亦然。它是不可靠的,并导致不可预测的行为。
(按钮也始终位于这些图形的顶部)
我尝试使用它来覆盖或手动绘制组件,更改顺序等,但我认为我在这里遗漏了一些非常基本的东西。谁有一个模板或者同时使用g.drawXXX和JCompotents的正确方法?
发布于 2012-07-11 10:11:39
再说一次,只要遵循我的建议,
切勿直接在JApplet中绘制,而应在JPanel或其contentPane (即JPanel)中绘制。确保在此JPanel的paintComponent中绘制(...)方法。
而且它是有效的:
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.InvocationTargetException;
import javax.swing.*;
public class Test2 extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
Test2BPanel panel = new Test2BPanel();
setContentPane(panel);
}
});
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Test2BPanel extends JPanel {
private String[] backgroundImageFileNames = { "test", "test", "test" };
private JButton refreshButton;
private JComboBox backgroundList;
public Test2BPanel() {
setBackground(Color.white);
setLayout(new FlowLayout());
refreshButton = new JButton("replant new forest");
refreshButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
add(refreshButton);
backgroundList = new JComboBox(backgroundImageFileNames);
backgroundList.setSelectedIndex(2);
add(backgroundList);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
paintIt(g);
}
public void paintIt(Graphics g) {
for (int i = 0; i < 200; i++) {
for (int j = 0; j < 200; j++) {
g.setColor(Color.red);
g.drawOval(10 * i, j, 10, 10);
}
}
}
}另外,请查看包括Basic Painting Tutorial和Advanced Painting Tutorial在内的Swing绘画教程。
更多关于这方面的好书,请看看Chet Haase和Romain Guy写的Guy Filthy Rich Clients。你不会后悔买的东西的!这是我拥有的最好的Java书之一。
https://stackoverflow.com/questions/11424180
复制相似问题