Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Copying the View of a JPanel

186 views
Skip to first unread message

X

unread,
Jul 2, 2008, 10:38:53 AM7/2/08
to
I have a JPanel that a user can edit and add drawings and Swing
components to, and I want to create a second JPanel that shows the
same thing as what's on the first JPanel. Does anyone know how to best
accomplish this?

My current implementation consists of calling the first JPanel's
paint() method with the second JPanel's Graphics context. This works
fine until the first Swing component is added to the screen. The
second JPanel shows everything but then "freezes" after a Swing
component is added to the first JPanel. Does anyone know what might be
wrong, or does anyone have an alternate suggestion as to how I can
have this second JPanel copy the view from the first JPanel?

Knute Johnson

unread,
Jul 2, 2008, 7:19:22 PM7/2/08
to

I tried to write a program to emulate yours but I couldn't do it. I
would be really curious to see your code if you have an SSCCE.

In any case I took a different tact, I copy the data from the first
component with a Robot and then draw it on the second. This works
pretty good but if you put something over the first panel such as
another window, that's what shows up in the second panel. Also I just
refresh the second panel every 100ms. You could capture events on the
first window and trigger a repaint then as well.

This was an interesting question but I am curious as to what the purpose
of it is. Are you trying to make some sort of whiteboard connected
across the net?

Anyway, here is my implementation.

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;

public class test extends JPanel implements Runnable {
JComponent c;
Robot robot;

public test(JComponent c) {
this.c = c;
try {
robot = new Robot();
} catch (AWTException awte) {
awte.printStackTrace();
}
}

public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException ie) { }
repaint();
}
}

public void paint(Graphics g) {
Point p = c.getLocationOnScreen();
Rectangle r = new Rectangle(p,c.getSize());
BufferedImage bi = robot.createScreenCapture(r);
g.drawImage(bi,0,0,null);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());

final JPanel p = new JPanel();
p.setPreferredSize(new Dimension(400,300));
p.setBackground(new Color(0,0,255,40));
JButton b = new JButton("Add Component");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JLabel l = new JLabel("A JLabel");
p.add(l);
p.invalidate();
f.validate();
f.repaint();
}
});
p.add(b);
f.add(p);

test t = new test(p);
t.setPreferredSize(new Dimension(400,300));
f.add(t);

f.pack();
f.setVisible(true);

new Thread(t).start();
}
});
}
}

--

Knute Johnson
email s/nospam/knute2008/

--
Posted via NewsDemon.com - Premium Uncensored Newsgroup Service
------->>>>>>http://www.NewsDemon.com<<<<<<------
Unlimited Access, Anonymous Accounts, Uncensored Broadband Access

Daniele Futtorovic

unread,
Jul 3, 2008, 1:14:37 PM7/3/08
to
On 2008-07-03 01:19 +0100, Knute Johnson allegedly wrote:
> I tried to write a program to emulate yours but I couldn't do it. I
> would be really curious to see your code if you have an SSCCE.

For the sheer fun of it...

<sscce>
package scratch;

import java.applet.Applet;
import java.awt.geom.AffineTransform;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.plaf.*;

public class Test {

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {
public void run() {
ChainingRepaintManager crm = new
ChainingRepaintManager( RepaintManager.currentManager(null) );
RepaintManager.setCurrentManager(crm);

JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel c = new JPanel(new GridLayout(2, 1));

c.add(new JCheckBox("Byte me!"));
c.add(new JCheckBox("Byte me too!"));

f.getContentPane().add(c, BorderLayout.WEST);
f.getContentPane().add( new MirrorComponent(c) ,
BorderLayout.EAST );

f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}

private static class MirrorComponent
extends JComponent
{
public MirrorComponent(JComponent mirrored){
super();

setUI( new MirrorUI(mirrored) );
}
}

private static class MirrorUI
extends ComponentUI
{
private JComponent
mirroredComponent
;

private ComponentListener
compListener
;

private AffineTransform
transform
;

private final Dimension
lastSize = new Dimension()
;

private PaintChain
paintChain
;

public MirrorUI(JComponent mirrored){
mirroredComponent = mirrored;
}

public void paint(Graphics g, JComponent c) {
if( transform == null ){
updateTransform();
}

Image i =
RepaintManager.currentManager(mirroredComponent).getOffscreenBuffer(c,
c.getWidth(), c.getHeight());

Graphics scratch = i.getGraphics();
mirroredComponent.paint( scratch );
scratch.dispose();

Graphics2D g2d = (Graphics2D) g;

AffineTransform old = g2d.getTransform();

g2d.transform( transform );

g2d.drawImage(i, 0, 0, null);

g2d.setTransform( old );
}

public void uninstallUI(JComponent c) {
mirroredComponent.removeComponentListener( compListener );

RepaintManager rm = RepaintManager.currentManager(c);

if( paintChain != null && rm instanceof
ChainingRepaintManager ){
((ChainingRepaintManager)rm).removePaintChain(
paintChain );
}
}

public void installUI(JComponent c) {
mirroredComponent.addComponentListener(
createComponentListener(c) );

RepaintManager rm = RepaintManager.currentManager(c);

if( rm instanceof ChainingRepaintManager ){
paintChain = new PaintChain(mirroredComponent, c);
((ChainingRepaintManager)rm).addPaintChain( paintChain );
}
}

public Dimension getPreferredSize(JComponent c) {
return mirroredComponent.getPreferredSize();
}

public Dimension getMinimumSize(JComponent c) {
return mirroredComponent.getMinimumSize();
}

public Dimension getMaximumSize(JComponent c) {
return mirroredComponent.getMaximumSize();
}

private ComponentListener createComponentListener(JComponent c){
return compListener = new _ComponentListener(c);
}

private void updateTransform(){
Dimension d = mirroredComponent.getSize();

if( transform == null || ! d.equals(lastSize) ){
lastSize.setSize(d);
transform = new AffineTransform(-1, 0, 0, 1, d.width, 0);
}
}

private class _ComponentListener
extends ComponentAdapter
{
private final JComponent component;

public _ComponentListener(JComponent c){
super();

component = c;
}

public void componentHidden(ComponentEvent e) {
component.setVisible(false);
}

public void componentShown(ComponentEvent e) {
component.setVisible(true);
}

public void componentResized(ComponentEvent e) {
updateTransform();
}
}
}

private static class PaintChain {
protected final Component
sourceComponent,
targetComponent
;

public PaintChain(Component source, Component target){
sourceComponent = source;
targetComponent = target;

if( source == null || target == null ){
throw new IllegalArgumentException(new
NullPointerException());
}

if( source == target ){
throw new IllegalArgumentException("source equals target");
}
}

public Component getSourceComponent() {
return sourceComponent;
}

public Component getTargetComponent() {
return targetComponent;
}

public int hashCode(){
return sourceComponent.hashCode() ^ targetComponent.hashCode();
}

public boolean equals(Object o){
return o != null && (o == this || o instanceof PaintChain
&& o.hashCode() == this.hashCode());
}
}

private static class ChainingRepaintManager
extends RepaintManager
{
protected final RepaintManager
delegate
;

private Set<PaintChain>
chains = new HashSet<PaintChain>()
;

public ChainingRepaintManager(RepaintManager delegate){
this.delegate = delegate;
}

public boolean addPaintChain(PaintChain pc){
return chains.add(pc);
}

public boolean removePaintChain(PaintChain pc){
return chains.remove(pc);
}

public String toString() {
return delegate.toString();
}

public void validateInvalidComponents() {
delegate.validateInvalidComponents();
}

public void paintDirtyRegions() {
delegate.paintDirtyRegions();
}

public Dimension getDoubleBufferMaximumSize() {
return delegate.getDoubleBufferMaximumSize();
}

public int hashCode() {
return delegate.hashCode();
}

public boolean isDoubleBufferingEnabled() {
return delegate.isDoubleBufferingEnabled();
}

public void addDirtyRegion(Window window, int x, int y, int w,
int h) {
delegate.addDirtyRegion(window, x, y, w, h);
}

public boolean equals(Object obj) {
return delegate.equals(obj);
}

public Image getOffscreenBuffer(Component c, int proposedWidth,
int proposedHeight) {
return delegate.getOffscreenBuffer(c, proposedWidth,
proposedHeight);
}

public Image getVolatileOffscreenBuffer(Component c, int
proposedWidth, int proposedHeight) {
return delegate.getVolatileOffscreenBuffer(c,
proposedWidth, proposedHeight);
}

public void addDirtyRegion(JComponent c, int x, int y, int w,
int h) {
delegate.addDirtyRegion(c, x, y, w, h);

for(JComponent chained: collectChainedAncestors(c)){
delegate.markCompletelyDirty(chained);
}
}

public void setDoubleBufferingEnabled(boolean aFlag) {
delegate.setDoubleBufferingEnabled(aFlag);
}

public void addDirtyRegion(Applet applet, int x, int y, int w,
int h) {
delegate.addDirtyRegion(applet, x, y, w, h);
}

public void setDoubleBufferMaximumSize(Dimension d) {
delegate.setDoubleBufferMaximumSize(d);
}

public void removeInvalidComponent(JComponent component) {
delegate.removeInvalidComponent(component);
}

public void addInvalidComponent(JComponent invalidComponent) {
delegate.addInvalidComponent(invalidComponent);

for(JComponent chained:
collectChainedAncestors(invalidComponent)){
delegate.addInvalidComponent(chained);
}
}

public Rectangle getDirtyRegion(JComponent aComponent) {
return delegate.getDirtyRegion(aComponent);
}

public boolean isCompletelyDirty(JComponent aComponent) {
return delegate.isCompletelyDirty(aComponent);
}

public void markCompletelyClean(JComponent aComponent) {
delegate.markCompletelyClean(aComponent);
}

public void markCompletelyDirty(JComponent aComponent) {
delegate.markCompletelyDirty(aComponent);

for(JComponent chained: collectChainedAncestors(aComponent)){
delegate.markCompletelyDirty(chained);
}
}

private Collection<JComponent>
collectChainedAncestors(JComponent comp){
Collection<JComponent> ret = new HashSet<JComponent>();

for(Container c = comp; c instanceof JComponent; c =
c.getParent()){
for(PaintChain pc: chains){
if( pc.getSourceComponent() == c ){
ret.add( (JComponent) pc.getTargetComponent() );
}
}
}

return ret;
}
}
}
</sscce>

--
DF.
to reply privately, change the top-level domain
in the FROM address from "invalid" to "net"

X

unread,
Jul 8, 2008, 11:49:23 AM7/8/08
to
On Jul 2, 6:19 pm, Knute Johnson <nos...@rabbitbrush.frazmtn.com>
wrote:

Thanks; your implementation works very well. I actually figured out my
problem, though; I learned that my implementation is no longer buggy
if I make sure to grab a fresh graphics context every time I want to
repaint the mirrored JPanel.

Sorry that I don't have any short code to illustrate, but I basically
just grab a graphics context from the mirrored JPanel and call the
original JPanel's paint() method, passing in that graphics context.
The purpose was to create a JPanel whose view can be altered (i.e.,
through affine transformations) while having the original JPanel in
view and intact. I also found out that drawing to a BufferedImage and
having the mirrored JPanel draw that image works just as well.

0 new messages