tenho que passar um objeto de um jdalog pra outro porem nao estou conseguindo passar
tenho um jframe consultar e ali tem alterar, quando clico emalterar teria que abrir outro jframe ja com o objeto inteiro fiz o seguinte
private Cliente getSelecionadoCliente(){
if(tabela.getSelectedRow() == -1) {
JOptionPane.showMessageDialog(this, "Selecione uma linha da tabela.",
"ERRO", JOptionPane.ERROR_MESSAGE);
return null;
}
DefaultTableModel modelo = (DefaultTableModel) tabela.getModel();
Integer id = Integer.parseInt(modelo.getValueAt(tabela.getSelectedRow(), 0).toString());
System.out.println(id);
ClienteDao cliente = new ClienteDao();
return cliente.Consultar(id);
isso ai pega o objeto selecionado na tabela
funcao consular
public Cliente Consultar(Integer id_cliente) {
String sql = "SELECT * FROM cliente WHERE id_cliente = ?";
try {
PreparedStatement stmt = getConexao().prepareStatement(sql);
stmt.setInt(1, id_cliente);
ResultSet rs = stmt.executeQuery();
List<Cliente> lista = getCliente(rs);
if(lista.size() > 0)
return lista.get(0);
} catch (SQLException sQLException) {
System.out.println("Erro ao consultar Cliente");
}
return null;
}
e o getcliente
public List<Cliente> getCliente(ResultSet rs) {
if(rs == null)
return null;
List<Cliente> lista = new ArrayList<Cliente>();
try {
while (rs.next()) {
Cliente cli = new Cliente();
cli.setId_cliente(rs.getInt("id_cliente"));
cli.setNome(rs.getString("nome"));
cli.setEndereco(rs.getString("endereco"));
cli.setData(new Date(rs.getDate("data").getTime()));
lista.add(cli);
}
} catch (SQLException ex) {
Logger.getLogger(ClienteDao.class.getName()).log(Level.SEVERE, null, ex);
}
return lista;
}
e passo assim para o outro jframe
Cliente cli = null;
cli = getSelecionadoCliente();
if(cli == null)
return;
new alterar(null, true, cli).setVisible(true);
porem nao aparece no outro jframe o objeto CLI sae em branco
o construtor do alterar
public alterar(java.awt.Frame parent, boolean modal, Cliente cli) {
this(parent, modal);
this.cli = cli;
mostrarDados();
}
public void mostrarDados() {
if(cli == null)
return;
jtf_nome.setText(cli.getNome());
}
teria q setar o campo com o nome vindo do banco
Ajuda java
4 Respostas
Eu criaria um JDialog e dentro dele eu criaria um método “public objeto edit( objeto )” dai dentro deste método criaria o dialog ja com os dados do objeto passado por parametro, dai depois de alterar é retornado o objeto já alterado…
como cara, poderia dar um exemplo ???
Presente
Cara vo te passa as classes que eu costumo usar mais por questão de organização…
Esse é um editor defaul que eu costumo usar, dai eu somente passo um painel que dentro dele ja é feito alguns tratamentos a mais…
public class DefaultDialog extends JDialog
{
/**
* createDialog
*
* @param owner Component
* @param title String
* @param panel DialogPanel
* @return DefaultDialog
*/
public static DefaultDialog createDialog( Component owner, String title, DialogPanel panel )
{
DefaultDialog dialog = null;
if ( owner != null )
{
Window parent = SwingUtilities.windowForComponent( owner );
if ( parent != null )
{
if ( parent instanceof Frame )
{
dialog = new DefaultDialog( (Frame) parent );
}
else if ( parent instanceof Dialog )
{
dialog = new DefaultDialog( (Dialog) parent );
}
}
}
if ( dialog == null )
{
dialog = new DefaultDialog();
}
dialog.setTitle( title );
dialog.setDialogPanel( panel );
return dialog;
}
private JButton acceptButton = new JButton( "Accept" );
private JButton cancelButton = new JButton( "Cancel" );
private JPanel buttonPane = new JPanel();
private DialogPanel dialogPanel = null;
private boolean accepted = false;
public DefaultDialog()
{
initComponents();
}
public DefaultDialog( Frame parent )
{
super( parent );
initComponents();
}
public DefaultDialog( Dialog parent )
{
super( parent );
initComponents();
}
/**
* getDialogPanel
*
* @return DialogPanel
*/
public DialogPanel getDialogPanel()
{
return dialogPanel;
}
/**
* setDialogPanel
*
* @param value DialogPanel
*/
public void setDialogPanel( DialogPanel value )
{
if ( dialogPanel != null )
{
remove( dialogPanel );
}
dialogPanel = value;
if ( dialogPanel != null )
{
add( dialogPanel, new GridBagConstraints( 0, 0, 1, 1, 1.0, 1.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets( 10, 10, 10, 10 ), 0, 0 ) );
dialogPanel.setDialog( this );
}
pack();
Dimension screenSize = getToolkit().getScreenSize();
Dimension dialogSize = getSize();
setLocation( ( screenSize.width - dialogSize.width ) / 2,
( screenSize.height - dialogSize.height ) / 2 );
}
/**
* @return boolean
*/
public boolean isAccepted()
{
return accepted;
}
/**
* acceptDialog
*
*/
public void acceptDialog()
{
if ( dialogPanel.validateInput() )
{
accepted = true;
setVisible( false );
dispose();
}
}
/**
* cancelDialog
*
*/
public void cancelDialog()
{
accepted = false;
setVisible( false );
dispose();
}
/**
* initComponents
*
*/
private void initComponents()
{
buttonPane.add( acceptButton );
buttonPane.add( cancelButton );
setModal( true );
setLayout( new GridBagLayout() );
JLabel ruler = new JLabel();
ruler.setBorder( BorderFactory.createMatteBorder( 0, 0, 2, 0, Color.gray ) );
add( ruler, new GridBagConstraints( 0, 1, 1, 1, 1.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL,
new Insets( 5, 10, 0, 10 ), 0, 0 ) );
add( buttonPane, new GridBagConstraints( 0, 2, 1, 1, 1.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets( 5, 5, 5, 5 ), 0, 0 ) );
acceptButton.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
acceptDialog();
}
} );
cancelButton.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
cancelDialog();
}
} );
addWindowFocusListener(new WindowAdapter()
{
@Override
public void windowGainedFocus(WindowEvent e)
{
JComponent initialFocus = dialogPanel.getInitialFocus();
if ( initialFocus != null )
{
initialFocus.requestFocusInWindow();
}
}
});
}
}
dai este seria um exemplo de um editor :
public class TestEditor
extends DialogPanel
{
/**
* edit
*
* @param owner Component
* @param Test Test
* @return boolean
*/
public static boolean edit( Component owner, Test test )
{
TestEditor editor = new TestEditor();
editor.setTest( test );
DefaultDialog dialog = DefaultDialog.createDialog( owner,
"Tests Editor",
editor );
dialog.setVisible( true );
boolean accepted = dialog.isAccepted();
if ( accepted )
{
editor.getTest( test );
}
return accepted;
}
/**
* TestEditor
*
*/
public TestEditor()
{
initComponents();
}
/**
* setTest
*
* @param t Test
*/
public void setTest( Test s )
{
nameField.setText( s.getName() );
infoTextArea.setText( s.getInfo() );
}
/**
* getTest
*
* @param t Test
*/
public void getTest( Test s )
{
s.setName( nameField.getText().trim() );
s.setInfo( infoTextArea.getText().trim() );
}
/**
* validateInput
*
* @return boolean
*/
public boolean validateInput()
{
String error = null;
if ( nameField.getText().trim().length() == 0 )
{
error = "A Test title must be provided!";
}
if ( error != null )
{
JOptionPane.showMessageDialog( this, error );
}
return error == null;
}
/**
* initComponents
*
*/
private void initComponents()
{
infoTextArea.setLineWrap( true );
infoTextArea.setWrapStyleWord( true );
add( titleLabel, new GridBagConstraints( 0, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets( 5, 5, 0, 5 ), 0, 0 ) );
add( nameField, new GridBagConstraints( 1, 0, 1, 1, 1.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
new Insets( 5, 0, 0, 5 ), 0, 0 ) );
add( infoLabel, new GridBagConstraints( 0, 1, 1, 1, 0.0, 0.0,
GridBagConstraints.NORTHEAST, GridBagConstraints.NONE,
new Insets( 5, 5, 0, 5 ), 0, 0 ) );
add( infoScroller, new GridBagConstraints( 1, 1, 1, 1, 1.0, 1.0,
GridBagConstraints.WEST, GridBagConstraints.BOTH,
new Insets( 5, 0, 5, 5 ), 0, 0 ) );
}
private JLabel titleLabel = new JLabel( "Title:" );
private JLabel infoLabel = new JLabel( "Info:" );
private JTextField nameField = new JTextField();
private JTextArea infoTextArea = new JTextArea();
private JScrollPane infoScroller = new JScrollPane( infoTextArea );
}
dai da outra classe, digamos que o frame que voce usa, eu usaria o método edit desta ultima classe dai passaria o objeto test…
dai caso não fosse cancelada a operação, meu objeto estaria alterado…
OK valeu pela ajuda cara vou tentar muito obrigadooo