基本上我有一个 JApplet 尝试使用图形绘制(即 g.drawOval(10,10,100,100) 并且还包括 JCompotents(即 JButton)。实际情况是重绘会变得非常古怪。
有时图形会绘制在小部件上,反之亦然。它不可靠,会导致不可预测的行为。
(按钮也总是在那些图形之上)
我尝试过尝试覆盖或手动绘制组件、更改订单等,但认为我在这里遗漏了一些非常基本的东西。谁有同时使用 g.drawXXX 和 JCompotents 的模板或正确方法?
最佳答案
再一次,按照我的建议,
be sure never to draw directly in the JApplet but rather in a JPanel or in its contentPane (which is a JPanel). Make sure to draw in this JPanel's paintComponent(...) method.
它有效:
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);
}
}
}
}
此外,请查看 Swing 绘画教程,包括 Basic Painting Tutorial和 Advanced Painting Tutorial .
有关这方面及更多内容的好书,请考虑购买 Filthy Rich Clients切特·哈斯 (Chet Haase) 和罗曼·盖伊 (Romain Guy) 着。您不会后悔购买的!这是我拥有的最好的 Java 书籍之一。
关于java - 在 JApplet/Swing 中使用图形和小部件绘图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11424180/