/*
 * Copyright (C) 2017 chcan
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package controlador.editores;

import controlador.Editor;
import controlador.apoios.ComboBoxSuperRender;
import diagramas.logico.Campo;
import diagramas.logico.Constraint;
import diagramas.logico.DiagramaLogico;
import diagramas.logico.LogicoLinha;
import diagramas.logico.Tabela;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.event.ListSelectionEvent;

/**
 *
 * @author chcan
 */
public class EditorDeIrFK extends javax.swing.JDialog {

    /**
     * Creates new form EditorDeCampos
     */
    public EditorDeIrFK(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel12 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        comboTabelas = new javax.swing.JComboBox<>();
        jLabel1 = new javax.swing.JLabel();
        jSplitPane7 = new javax.swing.JSplitPane();
        jPanel11 = new javax.swing.JPanel();
        jScrollPane9 = new javax.swing.JScrollPane();
        Listador = new javax.swing.JList<>();
        jToolBar9 = new javax.swing.JToolBar();
        jSeparator25 = new javax.swing.JToolBar.Separator();
        btnUP2 = new javax.swing.JButton();
        btnDown2 = new javax.swing.JButton();
        jSeparator26 = new javax.swing.JToolBar.Separator();
        btnAdd = new javax.swing.JButton();
        btnDel = new javax.swing.JButton();
        jSeparator27 = new javax.swing.JToolBar.Separator();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel4 = new javax.swing.JPanel();
        jToolBar1 = new javax.swing.JToolBar();
        Adicionar = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        chkIsnomeada = new javax.swing.JCheckBox();
        jLabel2 = new javax.swing.JLabel();
        txtNome = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        comboTabelasLigadas = new javax.swing.JComboBox<>();
        jLabel7 = new javax.swing.JLabel();
        comboIR = new javax.swing.JComboBox<>();
        jLabel3 = new javax.swing.JLabel();
        comboLigacoes = new javax.swing.JComboBox<>();
        btnEditar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        Principal = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        mostrador = new javax.swing.JTextArea();
        jPanel2 = new javax.swing.JPanel();
        btnPronto = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("principal/Formularios_pt_BR"); // NOI18N
        setTitle(bundle.getString("EditorDeCampos.title")); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(Editor.fromConfiguracao.getValor("Inspector.obj.constraint.fkey")));

        comboTabelas.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel1.setText(bundle.getString("EditorDeIR.Tabela.selecionada")); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(comboTabelas, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboTabelas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 0, Short.MAX_VALUE))
        );

        jSplitPane7.setDividerLocation(221);
        jSplitPane7.setResizeWeight(0.1);

        Listador.setModel(new javax.swing.AbstractListModel<String>() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public String getElementAt(int i) { return strings[i]; }
        });
        jScrollPane9.setViewportView(Listador);

        jToolBar9.setFloatable(false);
        jToolBar9.setOrientation(javax.swing.SwingConstants.VERTICAL);
        jToolBar9.setRollover(true);
        jToolBar9.add(jSeparator25);

        btnUP2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/up.png"))); // NOI18N
        btnUP2.setText(bundle.getString("FormHelp.btnUP2.text")); // NOI18N
        btnUP2.setToolTipText(bundle.getString("FormHelp.btnUP2.toolTipText")); // NOI18N
        btnUP2.setFocusable(false);
        btnUP2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnUP2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnUP2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUP2ActionPerformed(evt);
            }
        });
        jToolBar9.add(btnUP2);

        btnDown2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/down.png"))); // NOI18N
        btnDown2.setToolTipText(bundle.getString("FormHelp.btnDown2.toolTipText")); // NOI18N
        btnDown2.setFocusable(false);
        btnDown2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnDown2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnDown2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDown2ActionPerformed(evt);
            }
        });
        jToolBar9.add(btnDown2);
        jToolBar9.add(jSeparator26);

        btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/add_16.gif"))); // NOI18N
        btnAdd.setText(bundle.getString("FormHelp.btnAdd.text")); // NOI18N
        btnAdd.setToolTipText(bundle.getString("FormHelp.btnAdd.toolTipText")); // NOI18N
        btnAdd.setActionCommand(bundle.getString("FormHelp.btnAdd.actionCommand")); // NOI18N
        btnAdd.setFocusable(false);
        btnAdd.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAdd.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });
        jToolBar9.add(btnAdd);

        btnDel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/busy.png"))); // NOI18N
        btnDel.setText(bundle.getString("FormHelp.btnDel.text")); // NOI18N
        btnDel.setToolTipText(bundle.getString("FormHelp.btnDel.toolTipText")); // NOI18N
        btnDel.setFocusable(false);
        btnDel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnDel.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnDel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDelActionPerformed(evt);
            }
        });
        jToolBar9.add(btnDel);
        jToolBar9.add(jSeparator27);

        javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11);
        jPanel11.setLayout(jPanel11Layout);
        jPanel11Layout.setHorizontalGroup(
            jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel11Layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addComponent(jScrollPane9, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE))
            .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel11Layout.createSequentialGroup()
                    .addComponent(jToolBar9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 195, Short.MAX_VALUE)))
        );
        jPanel11Layout.setVerticalGroup(
            jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane9, javax.swing.GroupLayout.DEFAULT_SIZE, 425, Short.MAX_VALUE)
            .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jToolBar9, javax.swing.GroupLayout.DEFAULT_SIZE, 425, Short.MAX_VALUE))
        );

        jSplitPane7.setLeftComponent(jPanel11);

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        Adicionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/mais.png"))); // NOI18N
        Adicionar.setText(bundle.getString("EditorDeIR.Adicionar.Campo")); // NOI18N
        Adicionar.setFocusable(false);
        Adicionar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        Adicionar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        Adicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AdicionarActionPerformed(evt);
            }
        });
        jToolBar1.add(Adicionar);

        chkIsnomeada.setText(bundle.getString("EditorDeIR.nomeada")); // NOI18N

        jLabel2.setText(bundle.getString("EditorDeIR.lblIR.nome")); // NOI18N

        txtNome.setText("jTextField1");

        jLabel6.setText(bundle.getString("EditorDeIrUnique.lblTabelaOrigem")); // NOI18N

        comboTabelasLigadas.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel7.setText(bundle.getString("EditorDeIrUnique.lblRI")); // NOI18N

        comboIR.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel3.setText(bundle.getString("EditorDeIrUnique.lblLigacoes")); // NOI18N

        comboLigacoes.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/mini_edit.png"))); // NOI18N
        btnEditar.setText(bundle.getString("EditorDeIrUnique.Editar")); // NOI18N
        btnEditar.setEnabled(false);
        btnEditar.setFocusable(false);
        btnEditar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnEditar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(chkIsnomeada)
                        .addGap(44, 44, 44)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addGap(32, 32, 32)
                        .addComponent(comboTabelasLigadas, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel7)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(comboLigacoes, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 335, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(comboIR, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnEditar)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(chkIsnomeada)
                    .addComponent(jLabel2)
                    .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboTabelasLigadas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(comboIR)
                        .addComponent(jLabel7)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(comboLigacoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        Principal.setBackground(new java.awt.Color(204, 204, 204));
        Principal.setLayout(null);
        jScrollPane1.setViewportView(Principal);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 563, Short.MAX_VALUE)
            .addComponent(jScrollPane1)
            .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 245, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab(bundle.getString("EditorDeIrFk.TabAdicionar"), jPanel4); // NOI18N

        jSplitPane7.setRightComponent(jTabbedPane1);

        javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);
        jPanel12.setLayout(jPanel12Layout);
        jPanel12Layout.setHorizontalGroup(
            jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jSplitPane7, javax.swing.GroupLayout.DEFAULT_SIZE, 735, Short.MAX_VALUE))
        );
        jPanel12Layout.setVerticalGroup(
            jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel12Layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 434, Short.MAX_VALUE))
            .addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel12Layout.createSequentialGroup()
                    .addGap(50, 50, 50)
                    .addComponent(jSplitPane7, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE)))
        );

        mostrador.setEditable(false);
        mostrador.setColumns(20);
        mostrador.setRows(5);
        jScrollPane2.setViewportView(mostrador);

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btnPronto.setText(bundle.getString("EditorDeCampos.Fechar")); // NOI18N
        btnPronto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnProntoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnPronto)
                .addGap(2, 2, 2))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addComponent(btnPronto))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 795, Short.MAX_VALUE)
            .addComponent(jPanel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(1, 1, 1)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(1, 1, 1)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnProntoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnProntoActionPerformed
        DoneTexto();
        this.setVisible(false);
    }//GEN-LAST:event_btnProntoActionPerformed

    private void btnDelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDelActionPerformed
        tabelaSelecionada.RemoveConstraint(constrSelecionada);
        changeTabela();
    }//GEN-LAST:event_btnDelActionPerformed

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        Constraint cc = new Constraint(tabelaSelecionada);
        cc.setTipo(Constraint.CONSTRAINT_TIPO.tpFK);
        tabelaSelecionada.repaint();
        changeTabela();
        Listador.setSelectedIndex(Listador.getModel().getSize() - 1);
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnDown2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDown2ActionPerformed
        performMove(1);
    }//GEN-LAST:event_btnDown2ActionPerformed

    private void btnUP2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUP2ActionPerformed
        performMove(-1);
    }//GEN-LAST:event_btnUP2ActionPerformed

    private void AdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AdicionarActionPerformed
        Campo c = tabelaSelecionada.Add(Editor.fromConfiguracao.getValor("diagrama.Campo.nome"));
        AdicionarPainel(c);
        tabelaSelecionada.DoMuda();
        populando = true;
        RearranjeItens();
        populando = false;
    }//GEN-LAST:event_AdicionarActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        if (constrOrigem != null) {
            constrOrigem.getTabela().setConstraintSelecionado(constrOrigem);
            int tp = constrOrigem.getTipo() == Constraint.CONSTRAINT_TIPO.tpPK ? Constraint.TAG_COMMAND_PK : Constraint.TAG_COMMAND_UN;
            diagrama.setSelecionado(constrOrigem.getTabela());
            diagrama.LancarEditorDeIR(tp);
            tabelaSelecionada.setConstraintSelecionado(constrSelecionada);
            diagrama.setSelecionado(tabelaSelecionada);
            changeTabela();
        }
    }//GEN-LAST:event_btnEditarActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Adicionar;
    private javax.swing.JList<String> Listador;
    private javax.swing.JPanel Principal;
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDel;
    private javax.swing.JButton btnDown2;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnPronto;
    private javax.swing.JButton btnUP2;
    private javax.swing.JCheckBox chkIsnomeada;
    private javax.swing.JComboBox<String> comboIR;
    private javax.swing.JComboBox<String> comboLigacoes;
    private javax.swing.JComboBox<String> comboTabelas;
    private javax.swing.JComboBox<String> comboTabelasLigadas;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel12;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane9;
    private javax.swing.JToolBar.Separator jSeparator25;
    private javax.swing.JToolBar.Separator jSeparator26;
    private javax.swing.JToolBar.Separator jSeparator27;
    private javax.swing.JSplitPane jSplitPane7;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar9;
    private javax.swing.JTextArea mostrador;
    private javax.swing.JTextField txtNome;
    // End of variables declaration//GEN-END:variables

    DiagramaLogico diagrama = null;
    List<Tabela> tabelas = null;
    List<Tabela> tabelasLigadas = null;
    List<Constraint> constrDaTabOrigem = null;
    List<Constraint> constrDaTabSelecionada = null;

    List<LogicoLinha> Ligacoes = null;
    ArrayList<InternalItem> Itens = new ArrayList<>();
    int v = 0;
    private Tabela tabelaSelecionada = null;
    private Tabela tabelaDeOrigem = null;
    private boolean populando = false;
    private Constraint constrOrigem = null;
    private Constraint constrSelecionada = null;
    String strSelecione = "";
    boolean desabiliteTudo = false;
    LogicoLinha linha = null;
    List<Campo> camposOrigem = null;

    //<editor-fold defaultstate="collapsed" desc="Apoio">
    public class InternalItem {

        javax.swing.JCheckBox chkPK = new javax.swing.JCheckBox();
        javax.swing.JCheckBox chkfk = new javax.swing.JCheckBox();
        javax.swing.JButton btnExcluirCampo = new javax.swing.JButton();
        javax.swing.JCheckBox chkCampo = new javax.swing.JCheckBox();
        javax.swing.JCheckBox chUnique = new javax.swing.JCheckBox();
        javax.swing.JComboBox<String> comboCmpOrigem = new javax.swing.JComboBox<>();

        Campo campo = null;
    }

    private void Done() {
        Constraint pk = constrSelecionada;
        if (pk == null) {
            chkIsnomeada.setSelected(false);
            txtNome.setText("");
            txtNome.setEnabled(false);
            mostrador.setText("");
            return;
        }
        chkIsnomeada.setSelected(pk.isNomeada());
        txtNome.setEnabled(pk.isNomeada());
        txtNome.setText(pk.getNome());
        mostrador.setText(pk.getDDL());
    }

    private void DoneTexto() {
        Constraint pk = constrSelecionada;
        if (pk == null) {
            chkIsnomeada.setSelected(false);
            txtNome.setText("");
            txtNome.setEnabled(false);
            mostrador.setText("");
            return;
        }
        if (pk.isNomeada() != chkIsnomeada.isSelected() || !pk.getNome().equals(txtNome.getText())) {
            pk.setNomeada(chkIsnomeada.isSelected());
            pk.setNome(txtNome.getText());
            tabelaSelecionada.DoMuda();
            changeTabela();
        }
        txtNome.setEnabled(pk.isNomeada());
        txtNome.setText(pk.getNome());
        mostrador.setText(pk.getDDL());
    }

    private void performMove(int passo) {
        int ix = constrDaTabSelecionada.indexOf(constrSelecionada) + passo;
        Constraint dest = constrDaTabSelecionada.get(ix);

        int idx = tabelaSelecionada.getConstraints().indexOf(dest);
        tabelaSelecionada.getConstraints().remove(constrSelecionada);
        tabelaSelecionada.getConstraints().add(idx, constrSelecionada);

        btnDown2.setEnabled(constrSelecionada != null && idx < constrDaTabSelecionada.size() - 1);
        btnUP2.setEnabled(constrSelecionada != null && idx > 0);
        changeTabela();
    }

    //</editor-fold>
    public void Inicie(DiagramaLogico diag) {
        diagrama = diag;
        comboTabelas.removeAllItems();
        tabelas = diagrama.getListaDeTabelas();
        tabelaSelecionada = (diag.getSelecionado() instanceof Tabela ? (Tabela) diag.getSelecionado() : null);
        int idx = 0;
        for (int i = 0; i < tabelas.size(); i++) {
            Tabela t = tabelas.get(i);
            comboTabelas.addItem(String.valueOf(i + 1) + " - " + t.getTexto());
            if (t == tabelaSelecionada) {
                idx = i;
            }
        }
        tabelaSelecionada = tabelas.get(idx);
        comboTabelas.setSelectedIndex(idx);

        comboTabelas.addItemListener((ItemEvent e) -> {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                Tabela ada = tabelas.get(comboTabelas.getSelectedIndex());
                if (ada != tabelaSelecionada) {
                    tabelaSelecionada = ada;
                    changeTabela();
                }
            }
        });

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("principal/Formularios_pt_BR");
        strSelecione = bundle.getString("EditorDeIrFk.selecione");

        Listador.addListSelectionListener((ListSelectionEvent arg) -> {
            if (!arg.getValueIsAdjusting() && !populando) {
                Constraint tmp;
                if (Listador.getSelectedIndex() > -1) {
                    tmp = constrDaTabSelecionada.get(Listador.getSelectedIndex());
                } else {
                    tmp = null;
                }
                if (tmp != constrSelecionada) {
                    constrSelecionada = tmp;
                    populando = true;
                    changeConstraint();
                    RearranjeItens();
                    populando = false;
                }
            }
        });

        txtNome.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
            }

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                    if (constrSelecionada == null) {
                        return;
                    }
                    txtNome.setText(constrSelecionada.getNome());
                } else if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    DoneTexto();
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
            }
        });

        chkIsnomeada.addItemListener((java.awt.event.ItemEvent evt) -> {
            if (populando) {
                return;
            }
            DoneTexto();
        });

        chkIsnomeada.addActionListener((java.awt.event.ActionEvent evt) -> {
            if (populando) {
                return;
            }
            DoneTexto();
        });

        comboTabelasLigadas.addItemListener((ItemEvent e) -> {
            if (e.getStateChange() == ItemEvent.SELECTED && !populando) {
                Tabela ta = null;
                if (comboTabelasLigadas.getSelectedIndex() > 0) {
                    ta = tabelasLigadas.get(comboTabelasLigadas.getSelectedIndex() - 1);
                }
                if (ta != tabelaDeOrigem) {
                    ManualMudaTabela(ta);
                }
            }
        });

        comboIR.addItemListener((ItemEvent e) -> {
            if (e.getStateChange() == ItemEvent.SELECTED && !populando && constrSelecionada != null) {
                Constraint tmp = null;
                if (comboIR.getSelectedIndex() > 0) {
                    tmp = constrDaTabOrigem.get(comboIR.getSelectedIndex() - 1);
                }
                if (tmp != constrOrigem) {
                    constrOrigem = tmp;
                    constrSelecionada.setConstraintOrigem(constrOrigem);
                    tabelaSelecionada.DoMuda();
                    camposOrigem = (constrOrigem == null) ? new ArrayList<>() : constrOrigem.getCamposDeOrigem().stream().filter(c -> (c != null)).collect(Collectors.toList());
                    populando = true;
                    constrSelecionada.getCamposDeDestino().stream().forEach(c -> {
                        Itens.stream().filter(it -> it.campo == c).forEach(it -> it.comboCmpOrigem.setSelectedIndex(0));
                    });
                    //RearranjeItens();
                    populando = false;
                }
                btnEditar.setEnabled(constrOrigem != null);
            }
        });

        comboLigacoes.addItemListener((ItemEvent e) -> {
            if (e.getStateChange() == ItemEvent.SELECTED && !populando && constrSelecionada != null) {
                LogicoLinha tmp = null;
                if (comboLigacoes.getSelectedIndex() > 0) {
                    tmp = Ligacoes.get(comboLigacoes.getSelectedIndex() - 1);
                }
                if (tmp != linha) {
                    linha = tmp;
                    constrSelecionada.setLigacao(linha);
                    tabelaSelecionada.DoMuda();
                }
            }
        });

        changeTabela();
    }

    private void changeTabela() {
        populando = true;
        Principal.removeAll();
        Principal.validate();
        Itens.clear();
        v = 0;

        //Tabela de origem
        tabelasLigadas = tabelaSelecionada.getListaDeTabelasLigadas();
        comboTabelasLigadas.removeAllItems();
        comboTabelasLigadas.addItem(strSelecione);
        tabelasLigadas.forEach(t -> {
            comboTabelasLigadas.addItem((t != tabelaSelecionada ? String.valueOf(comboTabelasLigadas.getItemCount()) + " - " : "[AUTO] - ") + t.getTexto());
        });

        //Constraint da tabela selecionada
        constrDaTabSelecionada = tabelaSelecionada.getConstraints().stream().filter(c -> c.getTipo() == Constraint.CONSTRAINT_TIPO.tpFK).collect(Collectors.toList());
        DefaultListModel lst = new DefaultListModel();
        int t = 1;
        for (Constraint contr : constrDaTabSelecionada) {
            lst.addElement(Integer.toString(t++) + " - " + contr.getNomeFormatado());
        }
        Listador.setModel(lst);
        constrSelecionada = tabelaSelecionada.getConstraintSelecionado();
        if (constrSelecionada == null && !constrDaTabSelecionada.isEmpty()) {
            constrSelecionada = constrDaTabSelecionada.get(0);
        }

        changeConstraint();

        tabelaSelecionada.getCampos().stream().forEach(c -> AdicionarPainel(c));
        Principal.repaint();

        RearranjeItens();
        populando = false;
    }

    /**
     * Usado para incluir incluir uma tabela não não mais ligada à principal, mas que uma Constraint ainda esteja ativa
     */
    private Tabela toRemoveOnNext = null;

    private void changeConstraint() {
        if (constrSelecionada != null) {
            comboTabelasLigadas.setEnabled(true);
            int idx = constrDaTabSelecionada.indexOf(constrSelecionada);
            Listador.setSelectedIndex(idx);
            desabiliteTudo = false;
            constrOrigem = constrSelecionada.getConstraintOrigem();

            if (toRemoveOnNext != null) {
                int x = tabelasLigadas.indexOf(toRemoveOnNext);
                if (x > -1) {
                    tabelasLigadas.remove(x);
                    boolean bk = populando;
                    populando = true;
                    comboTabelasLigadas.removeItemAt(x + 1);
                    populando = bk;
                }
                toRemoveOnNext = null;
            }

            tabelaDeOrigem = constrSelecionada.getConstraintOrigem() == null ? null : constrSelecionada.getConstraintOrigem().getTabela();

            if (tabelaDeOrigem != null && tabelasLigadas.indexOf(tabelaDeOrigem) == -1) {
                toRemoveOnNext = tabelaDeOrigem;
                tabelasLigadas.add(tabelaDeOrigem);
                boolean bk = populando;
                populando = true;
                comboTabelasLigadas.addItem("* " + tabelaDeOrigem.getTexto());
                populando = bk;
            }

            idx = tabelasLigadas.indexOf(tabelaDeOrigem);
            comboTabelasLigadas.setSelectedIndex(idx + 1);
            linha = constrSelecionada.getLigacao();
        } else {
            desabiliteTudo = true;
            constrOrigem = null;
            tabelaDeOrigem = null;

            comboTabelasLigadas.setEnabled(false);
        }

        if (tabelaSelecionada.isSelecionado() && tabelaSelecionada.getConstraintSelecionado() != constrSelecionada) {
            tabelaSelecionada.setConstraintSelecionado(constrSelecionada);
            diagrama.PerformInspector();
        }

        changeTabelaOrigem();

        Done();
    }

    private void changeTabelaOrigem() {
        int t;

        comboIR.removeAllItems();
        comboLigacoes.removeAllItems();
        comboIR.addItem(strSelecione);
        comboLigacoes.addItem(strSelecione);
        if (tabelaDeOrigem != null) {
            constrDaTabOrigem = tabelaDeOrigem.getConstraints().stream().filter(c -> c.getTipo() != Constraint.CONSTRAINT_TIPO.tpFK).collect(Collectors.toList());
            t = 1;
            for (Constraint contr : constrDaTabOrigem) {
                comboIR.addItem(Integer.toString(t++) + " - " + contr.getNomeFormatado());
            }
            Ligacoes = tabelaSelecionada.getListaDeLigacoes().stream().filter(lig -> ((lig instanceof LogicoLinha) && (lig.getOutraPonta(tabelaSelecionada) == tabelaDeOrigem)))
                    .map(lig -> (LogicoLinha) lig)
                    .collect(Collectors.toList());
            Ligacoes.forEach(lig -> {
                boolean aMb = lig.getCardA().CardToInt() > lig.getCardB().CardToInt();
                boolean bMa = lig.getCardA().CardToInt() < lig.getCardB().CardToInt();
                if (lig.getFormaPontaB() == tabelaDeOrigem) {
                    comboLigacoes.addItem(String.valueOf(comboLigacoes.getItemCount()) + " - " + lig.getFormaPontaB().getTexto() + " (" + lig.getCardB().CardToString() + ")"
                            + (aMb ? " <-- " : (bMa ? " --> " : " <-> "))
                            + lig.getFormaPontaA().getTexto() + " (" + lig.getCardA().CardToString() + ")");
                } else {
                    comboLigacoes.addItem(String.valueOf(comboLigacoes.getItemCount()) + " - " + lig.getFormaPontaA().getTexto() + " (" + lig.getCardA().CardToString() + ")"
                            + (aMb ? " --> " : (bMa ? " <-- " : " <-> "))
                            + lig.getFormaPontaB().getTexto() + " (" + lig.getCardB().CardToString() + ")");
                }
            });
            if (constrOrigem != null) {
                int idx = constrDaTabOrigem.indexOf(constrOrigem) + 1;
                comboIR.setSelectedIndex(idx);
                btnEditar.setEnabled(true);
            } else {
                btnEditar.setEnabled(false);
            }
            if (linha != null) {
                int idx = Ligacoes.indexOf(linha) + 1;
                comboLigacoes.setSelectedIndex(idx);
            }
        }
//        else {
//            Ligacoes = new ArrayList<>();
//            constrDaTabOrigem = new ArrayList<>();
//            linha = null;
//            btnEditar.setEnabled(false);
//        }
        camposOrigem = (constrOrigem == null) ? new ArrayList<>() : constrOrigem.getCamposDeOrigem().stream().filter(c -> (c != null)).collect(Collectors.toList());
    }

    public void RearranjeItens() {
        btnDel.setEnabled(constrSelecionada != null);
        int ix = constrSelecionada != null ? constrDaTabSelecionada.indexOf(constrSelecionada) : -1;
        btnDown2.setEnabled(constrSelecionada != null && ix < constrDaTabSelecionada.size() - 1);
        btnUP2.setEnabled(constrSelecionada != null && ix > 0);

        Itens.stream().forEach(item -> {
            item.chkCampo.setEnabled(!desabiliteTudo);
            //item.chkPK.setEnabled(!desabiliteTudo);
            //item.chUnique.setEnabled(!desabiliteTudo);
            item.chkfk.setEnabled(!desabiliteTudo);
            item.comboCmpOrigem.setEnabled(!desabiliteTudo);

            //item.comboCmpOrigem.setSelectedIndex(0);
        });
        if (constrSelecionada == null && desabiliteTudo) {
            return;
        }

        Itens.stream().forEach(item -> {

            item.chkfk.setSelected(item.campo.isFkey());
            if (constrSelecionada.getCamposDeDestino().indexOf(item.campo) > -1) {
                item.chkCampo.setSelected(true);
                item.chkCampo.setEnabled(true);
                item.chkfk.setEnabled(false);
                item.comboCmpOrigem.setEnabled(true);

//                int idx = camposOrigem.indexOf(item.campo);
//                idx++;
//                item.comboCmpOrigem.setSelectedIndex(idx);
            } else {
                item.chkCampo.setEnabled(!item.campo.isFkey());
                item.chkCampo.setSelected(item.campo.isFkey());
                item.chkfk.setEnabled(item.campo.isFkey());
                item.comboCmpOrigem.setEnabled(false);
//                item.comboCmpOrigem.setSelectedIndex(0);
            }
        });
    }

    private int largura = 0;

    public void AdicionarPainel(Campo cmp) {
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("principal/Formularios_pt_BR");
        javax.swing.JPanel ItemPan = new javax.swing.JPanel();
        final int altura = 37;
        java.awt.FlowLayout lay = new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 10, 5);
        ItemPan.setLayout(lay);

        ItemPan.setSize(675, altura);

        InternalItem item = new InternalItem();
        Itens.add(item);
        item.campo = cmp;

        javax.swing.JCheckBox chkCampo = item.chkCampo;
        javax.swing.JCheckBox chkPK = item.chkPK;
        javax.swing.JCheckBox chkfk = item.chkfk;
        javax.swing.JButton btnExcluir = item.btnExcluirCampo;
        javax.swing.JCheckBox chUnique = item.chUnique;
        javax.swing.JComboBox<String> comboCmpOrigem = item.comboCmpOrigem;
        javax.swing.JLabel lblCmpOrigem = new javax.swing.JLabel();

        chkCampo.setText(cmp.getTexto()); // NOI18N
        chkCampo.setPreferredSize(new Dimension(120, 23));
        ItemPan.add(chkCampo);

        lblCmpOrigem.setText(bundle.getString("EditorDeIrFk.lblCmpOrigem")); // NOI18N
        lblCmpOrigem.setSize(new Dimension(34, 14));
        ItemPan.add(lblCmpOrigem);

        final String ori_txt = cmp.getCampoOrigem() == null ? bundle.getString("EditorDeIrFk.selecione") : cmp.getCampoOrigem().getTexto();

        comboCmpOrigem.setModel(new javax.swing.DefaultComboBoxModel());
        comboCmpOrigem.setPreferredSize(new Dimension(120, 20));
        ItemPan.add(comboCmpOrigem);

        chkPK.setText(bundle.getString("EditorDeIR.chkPK")); // NOI18N
        chkPK.setSize(new Dimension(97, 23));
        ItemPan.add(chkPK);

        chkfk.setText(bundle.getString("EditorDeIR.chkFK")); // NOI18N
        chkfk.setSize(new Dimension(115, 23));
        ItemPan.add(chkfk);

        chUnique.setText(bundle.getString("EditorDeIR.chkUNIQUE")); // NOI18N
        chUnique.setSize(new Dimension(51, 23));
        ItemPan.add(chUnique);

        btnExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/excluir.png"))); // NOI18N
        btnExcluir.setToolTipText(bundle.getString("EditorDeCampos.tooltip.excluir")); // NOI18N
        btnExcluir.setPreferredSize(new Dimension(49, 25));
        ItemPan.add(btnExcluir);

        Principal.add(ItemPan);
        if (largura == 0) {
            largura = lay.preferredLayoutSize(ItemPan).width;
        }
        ItemPan.setBounds(0, v, largura, altura);
        v += altura + 3;
        //Principal.setSize(new Dimension(675, v));
        Principal.setPreferredSize(new Dimension(largura, v));

        chkCampo.setSelected(cmp.isFkey());
        chkfk.setSelected(cmp.isFkey());
        chkPK.setSelected(cmp.isKey());
        chUnique.setSelected(cmp.isUnique());

        chUnique.setToolTipText(Editor.fromConfiguracao.getValor("Inspector.dica.campo.unique"));
        chkfk.setToolTipText(Editor.fromConfiguracao.getValor("Inspector.dica.campo.fkey"));

        comboCmpOrigem.addItem(bundle.getString("EditorDeIrFk.selecione"));
        boolean ja = ori_txt.equals(bundle.getString("EditorDeIrFk.selecione"));
        for (Campo c : camposOrigem) {
            comboCmpOrigem.addItem(c.getTexto());
            ja = ja ? true : (c.getTexto().equals(ori_txt));
        }
        if (!ja) {
            comboCmpOrigem.addItem(ori_txt);
        }
        comboCmpOrigem.setSelectedItem(ori_txt);

        chUnique.addItemListener((java.awt.event.ItemEvent evt) -> {
            if (populando) {
                return;
            }
            if (cmp.isUnique() != chUnique.isSelected()) {
                cmp.setUnique(chUnique.isSelected());
                cmp.getTabela().DoMuda();
                cmp.InvalidateArea();
                Done();
            }
        });

        chkPK.addItemListener((java.awt.event.ItemEvent evt) -> {
            if (populando) {
                return;
            }
            if (cmp.isKey() != chkPK.isSelected()) {
                cmp.setKey(chkPK.isSelected());
                cmp.getTabela().DoMuda();
                cmp.InvalidateArea();
                Done();
            }
        });

        chkCampo.addItemListener((java.awt.event.ItemEvent evt) -> {
            if (constrSelecionada == null || populando) {
                return;
            }
            if (cmp.isFkey() != chkCampo.isSelected()) {
                if (chkCampo.isSelected()) {
                    cmp.SetFkey(true);
                    Campo ori = getCampoOrigemSelecionado(item);
                    constrSelecionada.Add(ori, cmp, linha, constrOrigem);
                    cmp.getTabela().DoMuda();
                    cmp.InvalidateArea();
                    Done();
                } else {
                    cmp.SetFkey(false);
                    constrSelecionada.RemoveFromDestino(cmp);
                    cmp.getTabela().DoMuda();
                    cmp.InvalidateArea();
                    Done();
                }
            }
            populando = true;
            changeConstraint();
            RearranjeItens();
            populando = false;
        });

        chkfk.addItemListener((java.awt.event.ItemEvent evt) -> {
            if (constrSelecionada == null || populando) {
                return;
            }
            //if (cmp.isFkey() != chkfk.isSelected()) {

            cmp.SetFkey(false);
            constrSelecionada.RemoveFromDestino(cmp);
            cmp.getTabela().DoMuda();
            cmp.InvalidateArea();
            Done();

            populando = true;
            changeConstraint();
            RearranjeItens();
            populando = false;
            // }
        });

        btnExcluir.addActionListener((java.awt.event.ActionEvent evt) -> {
            cmp.getTabela().RemoveCampo(cmp);
            InternalItem itemdel = Itens.stream().filter(it -> it.campo == cmp).findAny().orElse(null);
            Itens.remove(itemdel);
            ItemPan.setEnabled(false);
            chkCampo.setEnabled(false);
            chkPK.setEnabled(false);
            chUnique.setEnabled(false);
            chkfk.setEnabled(false);
            btnExcluir.setEnabled(false);
            ItemPan.setBackground(Color.lightGray);
            comboCmpOrigem.setEnabled(false);
            Done();
            populando = true;
            changeConstraint();
            RearranjeItens();
            populando = false;
        });

        comboCmpOrigem.addActionListener((ActionEvent e) -> {
            if (constrSelecionada == null || populando) {
                return;
            }
            Campo ori = getCampoOrigemSelecionado(item);
            constrSelecionada.Add(ori, cmp, linha, constrOrigem);
            cmp.getTabela().DoMuda();
            populando = true;
            RearranjeItens();
            Done();
            populando = false;
        });

        comboCmpOrigem.getEditor().addActionListener((ActionEvent e) -> {
            if (constrSelecionada == null || populando) {
                return;
            }
            Campo ori = getCampoOrigemSelecionado(item);
            constrSelecionada.Add(ori, cmp, linha, constrOrigem);
            cmp.getTabela().DoMuda();
            populando = true;
            RearranjeItens();
            Done();
            populando = false;
        });

        comboCmpOrigem.setRenderer(new ComboBoxSuperRender(comboCmpOrigem.getRenderer()) {
            @Override
            public void ProcesseFonte(JLabel lbl, int item_idx, boolean selcted) {
                super.ProcesseFonte(lbl, item_idx, selcted);
                item_idx--;
                if (item_idx > -1 && item_idx < camposOrigem.size()) {
                    if (constrSelecionada != null) {
                        if (constrSelecionada.getCamposDeOrigem().indexOf(camposOrigem.get(item_idx)) > -1) {
                            lbl.setFont(new Font(lbl.getFont().getFontName(), Font.PLAIN, lbl.getFont().getSize()));
                            lbl.setForeground(Color.red);
                        } else {
                            lbl.setFont(new Font(lbl.getFont().getFontName(), Font.BOLD, lbl.getFont().getSize()));
                            lbl.setForeground(Color.BLACK);
                        }
                    }
                }
            }
        });

        comboCmpOrigem.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            @Override
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
                if (constrSelecionada != null) {
                    Campo cmpx = constrSelecionada.getOrigem(cmp);
                    if (cmpx != null) {
                        comboCmpOrigem.setSelectedItem(cmpx.getTexto());
                    } else {
                        comboCmpOrigem.setSelectedItem(bundle.getString("EditorDeIrFk.selecione"));
                    }
                }
            }

            @Override
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                if (constrSelecionada != null) {
                    Campo cmpx = constrSelecionada.getOrigem(cmp);
                    if (cmpx != null) {
                        comboCmpOrigem.setSelectedItem(cmpx.getTexto());
                    } else {
                        comboCmpOrigem.setSelectedItem(bundle.getString("EditorDeIrFk.selecione"));
                    }
                }
            }

            @Override
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
                boolean bkp = populando;
                populando = true;
                comboCmpOrigem.removeAllItems();
                comboCmpOrigem.addItem(bundle.getString("EditorDeIrFk.selecione"));
                //boolean ja = ori_txt.equals(bundle.getString("EditorDeIrFk.selecione"));
                for (Campo c : camposOrigem) {
                    comboCmpOrigem.addItem(c.getTexto());
                    //ja = ja ? true : (c.getTexto().equals(ori_txt));
                }
//                if (!ja) {
//                    comboCmpOrigem.addItem(ori_txt);
//                }
                populando = bkp;
            }
        });
        ItemPan.validate();
        Principal.validate();
    }

    public Campo getCampoOrigemSelecionado(InternalItem item) {
        int idx = item.comboCmpOrigem.getSelectedIndex();
        if (idx == 0) {
            return null;
        }
        if (idx == item.comboCmpOrigem.getItemCount()) {
            return constrSelecionada.getOrigem(item.campo);
        }
        idx--;
        return camposOrigem.get(idx);
    }

    private void ManualMudaTabela(Tabela novaOrigem) {
        tabelaDeOrigem = novaOrigem;
        constrSelecionada.setConstraintOrigem(null);
        constrOrigem = null;
        populando = true;
        constrSelecionada.getCamposDeDestino().stream().forEach(c -> {
            Itens.stream().filter(it -> it.campo == c).forEach(it -> it.comboCmpOrigem.setSelectedIndex(0));
        });
        changeTabelaOrigem();
        Done();
        populando = false;
        constrSelecionada.getTabela().DoMuda();
    }
}
