2012-09-12 10 views
6

Solo queremos conectar paneles trazando una línea b/w.Cómo podemos dibujar líneas entre 2 paneles en columpio

Tengo dos paneles y ambos paneles contienen un Jtable. Quiero conectar cada celda de jtable de un panel a otro Jtable de otro jpanel.

enter image description here

Aquí quiero dibujar las líneas de esa manera he destacado por el círculo de color rosa.

y este es el fragmento de código que estoy utilizando para crear JTables

DefaultTableModel fcdbDataModel = new DefaultTableModel(fcdbIdTxnArray, 
    fcdbIdTxnColumnArray); 
fcdbIdTxnJTable = new FieldMapperJTable(fcdbDataModel); 

aquí FieldMapperJTable es mi clase JTable personalizado.

+0

Se agradecerá cualquier tipo de ayuda o idea de usar otra forma. Gracias mucho por adelantado. –

+1

@Stanislav Muchas gracias por su publicación. Esto fue trabajado para mí. "http://java-sl.com/connector.html" –

+0

@Se preguntará por qué eliminó la respuesta de Stani. Definitivamente es útil – kleopatra

Respuesta

8

Puede hacerlo fácilmente usando JFrame/JDialog GlassPane como el campo de pintura. Simplemente configure su componente personalizado como un panel de vidrio para el marco y pinte el enlace directamente en él.

También puede hacer lo mismo utilizando el panel de capas del cuadro/diálogo.

Aquí es un pequeño ejemplo práctico de cómo dibujar este tipo de "enlaces" en el componente de cristal:

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.HashMap; 
import java.util.Map; 

/** 
* @see http://stackoverflow.com/a/12389479/909085 
*/ 

public class ComponentLinkerTest extends JComponent 
{ 
    private Map<JComponent, JComponent> linked; 

    public ComponentLinkerTest() 
    { 
     super(); 
     linked = new HashMap<JComponent, JComponent>(); 
    } 

    public void link (JComponent c1, JComponent c2) 
    { 
     linked.put (c1, c2); 
     repaint(); 
    } 

    protected void paintComponent (Graphics g) 
    { 
     Graphics2D g2d = (Graphics2D) g; 
     g2d.setRenderingHint (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 

     g2d.setPaint (Color.BLACK); 
     for (JComponent c1 : linked.keySet()) 
     { 
      Point p1 = getRectCenter (getBoundsInWindow (c1)); 
      Point p2 = getRectCenter (getBoundsInWindow (linked.get (c1))); 
      g2d.drawLine (p1.x, p1.y, p2.x, p2.y); 
     } 
    } 

    private Point getRectCenter (Rectangle rect) 
    { 
     return new Point (rect.x + rect.width/2, rect.y + rect.height/2); 
    } 

    private Rectangle getBoundsInWindow (Component component) 
    { 
     return getRelativeBounds (component, getRootPaneAncestor (component)); 
    } 

    private Rectangle getRelativeBounds (Component component, Component relativeTo) 
    { 
     return new Rectangle (getRelativeLocation (component, relativeTo), 
       component.getSize()); 
    } 

    private Point getRelativeLocation (Component component, Component relativeTo) 
    { 
     Point los = component.getLocationOnScreen(); 
     Point rt = relativeTo.getLocationOnScreen(); 
     return new Point (los.x - rt.x, los.y - rt.y); 
    } 

    private JRootPane getRootPaneAncestor (Component c) 
    { 
     for (Container p = c.getParent(); p != null; p = p.getParent()) 
     { 
      if (p instanceof JRootPane) 
      { 
       return (JRootPane) p; 
      } 
     } 
     return null; 
    } 

    public boolean contains (int x, int y) 
    { 
     return false; 
    } 

    private static ComponentLinkerTest linker; 

    public static void main (String[] args) 
    { 
     setupLookAndFeel(); 

     JFrame frame = new JFrame(); 

     linker = new ComponentLinkerTest(); 
     frame.setGlassPane (linker); 
     linker.setVisible (true); 

     JPanel content = new JPanel(); 
     content.setLayout (new GridLayout (10, 5, 5, 5)); 
     content.setBorder (BorderFactory.createEmptyBorder (5, 5, 5, 5)); 
     frame.add (content); 

     for (int i = 0; i < 50; i++) 
     { 
      final JButton button = new JButton ("Button" + i); 
      button.addActionListener (new ActionListener() 
      { 
       public void actionPerformed (ActionEvent e) 
       { 
        link (button); 
       } 
      }); 
      content.add (button); 
     } 

     frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); 
     frame.pack(); 
     frame.setLocationRelativeTo (null); 
     frame.setVisible (true); 
    } 

    private static JButton last = null; 

    private static void link (JButton button) 
    { 
     if (last == null) 
     { 
      last = button; 
     } 
     else 
     { 
      linker.link (last, button); 
      last = null; 
     } 
    } 

    private static void setupLookAndFeel() 
    { 
     try 
     { 
      UIManager.setLookAndFeel (UIManager.getSystemLookAndFeelClassName()); 
     } 
     catch (ClassNotFoundException e) 
     { 
      e.printStackTrace(); 
     } 
     catch (InstantiationException e) 
     { 
      e.printStackTrace(); 
     } 
     catch (IllegalAccessException e) 
     { 
      e.printStackTrace(); 
     } 
     catch (UnsupportedLookAndFeelException e) 
     { 
      e.printStackTrace(); 
     } 
    } 
} 

Y el resultado:
(simplemente haga clic en cualquiera de los dos botones, uno tras otro y van a conseguir vinculado)
enter image description here

PS Para hacer las líneas más gruesas, puede cambiar el trazo al pintar:

g2d.setStroke (new BasicStroke (5f)); 
+0

No estoy seguro de si esto todavía se aplica pero en los días en que Swing era nuevo y brillante, tuve muchos problemas para manejar eventos al intentar usar el cristal. –

+0

+1 Para renderizar encima de los componentes, así como un admirable estilo de comentarios. :-) – trashgod

+0

@JensSchauder sí, hay problemas, si quieres que el cristal maneje cualquier evento (no hay problemas, pero sí pequeñas dificultades). De todos modos, es por eso que anulo el método "contiene" del componente del panel de vidrio. Si siempre devuelve falso allí (o lo limita con la forma de las líneas) - no "absorberá" eventos en cualquier lugar (o solo en los límites de forma, lo cual también está bien). –

Cuestiones relacionadas