[英]Drawing with graphics and with widgets in JApplet/Swing?
基本上我有一个试图用图形绘制的JApplet(即g.drawOval(10,10,100,100),还包括JCompotents(即JButton)。发生的事情是重绘可能变得非常古怪。
有时,图形将绘制小部件或反之亦然。 它不可靠并导致不可预测的行为。
(按钮也始终位于这些图形的顶部)
我玩过它试图覆盖或手动绘制组件,更改订单等,但我想我在这里缺少一些非常基本的东西。 任何人都有模板或正确使用g.drawXXX和JCompotents的方法?
再次,按照我的建议,
确保永远不要直接在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);
}
}
}
}
另外,请查看Swing绘画教程,包括Basic Painting Tutorial和Advanced Painting Tutorial 。
关于这本以及更多内容的好书,请考虑购买Chet Haase和Romain Guy的Filthy Rich Clients 。 你不会后悔购买! 这是我拥有的最好的Java书籍之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.