import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Draw extends JFrame{
JPanel jPanel=new JPanel();
public Draw() {
jPanel.setBackground(Color.red);
add(jPanel);
Drawation drawaction=new Drawation();//添加画图,把上面jpanel的设置给覆盖了;要是先添加画图再添加
add(drawaction); //jpanel则把画图覆盖了
}
public static void main(String[] args){
Draw draw=new Draw();
draw.setTitle("abc");
draw.setSize(300,300);
draw.setVisible(true);
draw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class Drawation extends JPanel{
public void paintComponent(Graphics g){
super.paintComponents(g);
g.drawString("agagh", 50, 45);
}
}
这只是一段简单的验证代码,没什么意义。就是想了解怎么才能在动态画图的同时可以保留原有jpanel上的各种组件,而且可以在其上画图
------解决方案--------------------
JLayer 的例子。JXLayer(从 swinglabs网站下载)的类似,JLayer就是 JXLayer整合到java 7的结果。
import javax.swing.*;
import javax.swing.plaf.LayerUI;
import java.awt.*;
public class JLayerSample {
private static JLayer<JComponent> createLayer() {
// This custom layerUI will fill the layer with translucent green
// and print out all mouseMotion events generated within its borders
LayerUI<JComponent> layerUI = new LayerUI<JComponent>() {
public void paint(Graphics g, JComponent c) {
// paint the layer as is
super.paint(g, c);
// fill it with the translucent green
g.setColor(new Color(0, 128, 0, 128));
g.fillRect(0, 0, c.getWidth(), c.getHeight());
}
public void installUI(JComponent c) {
super.installUI(c);
// enable mouse motion events for the layer's subcomponents
((JLayer) c).setLayerEventMask(AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
public void uninstallUI(JComponent c) {
super.uninstallUI(c);
// reset the layer event mask
((JLayer) c).setLayerEventMask(0);
}
// overridden method which catches MouseMotion events
public void eventDispatched(AWTEvent e, JLayer<? extends JComponent> l) {
System.out.println("AWTEvent detected: " + e);