Olá Feras, tenho um jTable do Netbeans, como faço para deixar o foco na 1° linha e coluna, o melhor na célula do jTable como se fosse clickar, para com o teclado dar up ou down.
Esse é meu codigo nao consigo mesmo assim implementar, pois meu problema é que tenho um textfield que fica com o foco nao consigo fazer com que o foco fica na 1° celula da tabela e como selecionada
package cadastros;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import javax.swing.table.DefaultTableModel;
import java.sql.SQLException;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import utilitarios.conexao;
public class vizgrupo extends javax.swing.JDialog {
int navega = 0;
int carregagrupo = 0;
conexao con_grupo;
String ordenacao="codigo";
public String codigo;
public String descricao;
public vizgrupo() {
setModal(true);
initComponents();
KeyListener ouvinte = new KeyListener()
{
@Override
public void keyTyped(final KeyEvent e)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
JTextField campo = (JTextField) e.getSource();
int posicaoCursor = campo.getCaretPosition();
campo.setText(campo.getText().toUpperCase());
if(posicaoCursor !=campo.getCaretPosition())
{
campo.setCaretPosition(posicaoCursor);
}
}
});
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
};
jTable1.setAutoCreateRowSorter(true);
con_grupo = new conexao();
con_grupo.conecta();
con_grupo.executeSQL("select * from grupo order by "+ordenacao);
try
{
con_grupo.resultset.first();
}
catch(SQLException erro)
{
JOptionPane.showMessageDialog(null,"Não localizou dados"+erro);
}
preencher_jtable1();
atualiza_selecao_linha_ftable();
}
public vizgrupo (String codigo, String descricao) {
this.codigo = codigo;
this.descricao = descricao;
}
/** 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.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
grupo_ordenacao = new javax.swing.ButtonGroup();
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabel5 = new javax.swing.JLabel();
tf_pesquisa = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jPanel1 = new javax.swing.JPanel();
rd_codigo = new javax.swing.JRadioButton();
rd_nome = new javax.swing.JRadioButton();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Grupos");
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36));
jLabel1.setText("GRUPOS");
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 18));
jLabel5.setText("PESQUISAR:");
tf_pesquisa.setFont(new java.awt.Font("Tahoma", 0, 18));
tf_pesquisa.setToolTipText("Digite as iniciais da busca");
tf_pesquisa.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tf_pesquisaActionPerformed(evt);
}
});
jScrollPane1.setFont(new java.awt.Font("Tahoma", 0, 18));
jTable1.setFont(new java.awt.Font("Tahoma", 0, 18));
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null},
{null, null}
},
new String [] {
"CÓDIGO", "DESCRIÇÃO"
}
) {
boolean[] canEdit = new boolean [] {
false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTable1.setSelectionForeground(new java.awt.Color(0, 0, 204));
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTable1KeyPressed(evt);
}
});
jScrollPane1.setViewportView(jTable1);
grupo_ordenacao.add(rd_codigo);
rd_codigo.setSelected(true);
rd_codigo.setText("CÓDIGO");
rd_codigo.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
rd_codigo.setMargin(new java.awt.Insets(0, 0, 0, 0));
rd_codigo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rd_codigoActionPerformed(evt);
}
});
grupo_ordenacao.add(rd_nome);
rd_nome.setText("DESCRIÇÃO");
rd_nome.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
rd_nome.setMargin(new java.awt.Insets(0, 0, 0, 0));
rd_nome.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rd_nomeActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(rd_codigo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(rd_nome)
.addGap(97, 97, 97))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(rd_nome)
.addComponent(rd_codigo))
);
jButton1.setIcon(new javax.swing.ImageIcon("C:\\Estoque\\IMAGENS\\Busca.png")); // NOI18N
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 462, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(tf_pesquisa, javax.swing.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(16, 16, 16)))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(157, 157, 157)
.addComponent(jLabel1)
.addContainerGap(170, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(tf_pesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32))
);
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-461)/2, (screenSize.height-352)/2, 461, 352);
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
con_grupo.executeSQL("select * from grupo where descricao like '"+tf_pesquisa.getText()+"%' order by "+ordenacao);
preencher_jtable1();
}
private void tf_pesquisaActionPerformed(java.awt.event.ActionEvent evt) {
try
{
String pesquisa = "select * from grupo where descricao like '"+tf_pesquisa.getText()+"%'";
con_grupo.executeSQL(pesquisa);
if (con_grupo.resultset.first())
{
preencher_jtable1();
}
else JOptionPane.showMessageDialog(null,"Não localizou dados"+tf_pesquisa.getText().toUpperCase());
}
catch (Exception erro)
{
JOptionPane.showMessageDialog(null,"Não localizou dados, erro = "+erro);
}
}
private void rd_nomeActionPerformed(java.awt.event.ActionEvent evt) {
ordem_visualizacao("descricao");
}
private void rd_codigoActionPerformed(java.awt.event.ActionEvent evt) {
ordem_visualizacao("codigo");
} private void botao_alterarActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getClickCount() == 2) { // Aqui dentro vai o código que tu quer que execute no duplo clique
int linhasel = jTable1.getSelectedRow();
codigo = (String) jTable1.getValueAt(linhasel, 0);
descricao = (String) jTable1.getValueAt(linhasel, 1);
setVisible(false);
}
}
private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {
int linhaENTER = jTable1.getSelectedRow();
int tecla=evt.getKeyCode();
if (tecla==KeyEvent.VK_ENTER){
codigo = (String) jTable1.getValueAt(linhaENTER, 0);
descricao = (String) jTable1.getValueAt(linhaENTER, 1);
setVisible(false);
}
KeyListener ouvinte = null;
jTable1.addKeyListener(ouvinte);
}
public void mousePressed(MouseEvent evt) {
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run()
{
new vizgrupo().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup grupo_ordenacao;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTable jTable1;
private javax.swing.JRadioButton rd_codigo;
private javax.swing.JRadioButton rd_nome;
private javax.swing.JTextField tf_pesquisa;
// End of variables declaration
public void preencher_jtable1()
{
jTable1.getColumnModel().getColumn(0).setPreferredWidth(20);
jTable1.getColumnModel().getColumn(1).setPreferredWidth(280);
con_grupo.executeSQL("select * from grupo where descricao like '"+tf_pesquisa.getText()+"%' order by "+ordenacao);
DefaultTableModel modelo = (DefaultTableModel)jTable1.getModel();
modelo.setNumRows(0);
try
{
while (con_grupo.resultset.next())
modelo.addRow(new Object []{con_grupo.resultset.getString("codigo"),con_grupo.resultset.getString("descricao")});
con_grupo.resultset.first();
}
catch (SQLException erro){
JOptionPane.showMessageDialog(null,"Erro ao listar dados");
}
}
public void ordem_visualizacao(String Ordem){
ordenacao = Ordem;
con_grupo.executeSQL("select * from grupo order by "+ordenacao);
preencher_jtable1();
try
{
con_grupo.resultset.first();
}
catch (SQLException erro){
JOptionPane.showMessageDialog(null,"Erro na ordenação dos dados "+erro);
}
atualiza_selecao_linha_ftable();
}
public void atualiza_selecao_linha_ftable()
{
jTable1.getSelectionModel().setSelectionInterval(carregagrupo, carregagrupo);
}
void dados(int registro) {
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}