RESOLVIDO: JComboBox nao recebe o foco

5 respostas
R

Bom dia.
Preciso que o combo cbx receba o foco do txt1 ao teclar enter e mande o foco para o txt2 ao telar enter.
Peço ajuda pois devo estar errando em algo obvio que não consigo enxergar.

import java.awt.BorderLayout;

import java.awt.EventQueue;

import java.awt.Font;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyAdapter;

import java.awt.event.KeyEvent;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Calendar;

import java.util.Date;

import javax.swing.JButton;

import javax.swing.JComboBox;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JTextField;

import javax.swing.SwingConstants;

import javax.swing.DefaultComboBoxModel;

import javax.swing.text.Caret;

import java.awt.Color;

import java.awt.event.FocusAdapter;

import java.awt.event.FocusEvent;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;
public class JComboBoxAPRENDER extends JFrame {

private JTextField txt1;

private JTextField txt2;
static String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";  
static String base = "C:\\Documents and Settings\\Reis\\Desktop\\Banca_Sol_2013\\Dados_Banca.mdb";
static Connection conn = null;  
static Statement stmt; 

static String sCb[];

static ArrayList<String> sCombo = new ArrayList<>();   
static Date d = new Date();
static Calendar c = Calendar.getInstance();
static DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);

/**
 * Launch the application.
 * @throws SQLException 
 */
public static void main(String[] args) throws SQLException{
	c.setTime(d);

	try{
		database += base; 
		conn = DriverManager.getConnection(database);
		JOptionPane.showMessageDialog(null, "Conectou!");
		stmt = conn.createStatement();
    	String sSQL = "Select * from Fornecedores";
    	ResultSet rs = stmt.executeQuery(sSQL);
    		while(rs.next()){  
    			sCombo.add(rs.getString("Fornecedor"));
    		}
    	rs.close();
    	sSQL = null;
    	stmt.close();
    	}catch(Exception e){
   			JOptionPane.showMessageDialog(null, "O ERRO AO ABRIR É: " + e.getMessage());				    
    	}

		  EventQueue.invokeLater(new Runnable() {
		public void run() {
			try {
				JComboBoxAPRENDER frame = new JComboBoxAPRENDER();
				frame.setVisible(true);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
			});
}

/**
* Create the frame.

  • @throws SQLException
    
    */
    
    public JComboBoxAPRENDER() throws SQLException {
    
    addWindowListener(new WindowAdapter() {
    
    <a class="mention" href="/u/override">@Override</a>
    
    public void windowOpened(WindowEvent arg0) {
    
    JOptionPane.showMessageDialog(null, df.format(c.getTime()));
    
    txt1.setText(df.format(c.getTime()));
    
    txt2.setText(df.format(c.getTime()));
    
    }
    
    });
    
    setTitle("Registro de pagamentos " + df.format(c.getTime()));
    
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    setBounds(100, 100, 500, 300);
    
    JPanel panel = new JPanel();
     getContentPane().add(panel, BorderLayout.CENTER);
     panel.setLayout(new GridLayout(6, 2, 10, 10));
     
     txt1 = new JTextField();
     txt1.addKeyListener(new KeyAdapter() {
     	@Override
     	public void keyPressed(KeyEvent e) {
     		 int key = e.getKeyCode();
     		 if (key ==10) {
     		 //JOptionPane.showMessageDialog(null, key);
     	
     		 //cbx.grabfocus
               }
     	}
    
    });
    
    txt1.setHorizontalAlignment(SwingConstants.CENTER);
    
    txt1.setFont(new Font(Monotype Corsiva, Font.BOLD, 20));
    
    panel.add(txt1);
    
    txt1.setColumns(10);
    
    JComboBox cbx = new JComboBox();
     cbx.setFocusable(true);
     
     cbx.addKeyListener(new KeyAdapter() {
     	  public void keyPressed(KeyEvent e) {
     			//JOptionPane.showMessageDialog(null,"In key pressed");
     	    if (e.getKeyCode() == KeyEvent.VK_DELETE){
     			//JOptionPane.showMessageDialog(null,"Delete");
     		}
     	  }
     	});
     	DefaultComboBoxModel defaultComboBox = new DefaultComboBoxModel(sCombo.toArray());//Instanciando o DefaultComboBoxMode
     	cbx.setModel(defaultComboBox);//passando os valores do "modelo" pro ComboBox
     	cbx.getEditor().getItem();  
     	JOptionPane.showMessageDialog(null,cbx.getEditor().getItem()); 
     
     cbx.setEditable(true);
     cbx.setFont(new Font("Monotype Corsiva", Font.BOLD, 20));
     panel.add(cbx);
     
     txt2 = new JTextField();
     txt2.addKeyListener(new KeyAdapter() {
     	@Override
     	public void keyPressed(KeyEvent e) {
     		 int key = e.getKeyCode();
     		 if (key ==10) {
     		 JOptionPane.showMessageDialog(null, key);
     		 txtVencimento.grabFocus(); 
               }
     	}
    
    });
    
    txt2.setHorizontalAlignment(SwingConstants.CENTER);
    
    txt2.setFont(new Font(Monotype Corsiva, Font.BOLD, 20));
    
    txt2.setColumns(10);
    
    panel.add(txt2);
    
    }}
    

5 Respostas

mauricioadl

para forçar um componente receber o focus, use o metodo requestFocus();

[]'s

L

Cara, coloca teu código dentro da tag code.

Obs: Este seu código contém erros:

este trecho static ArrayList<String> sCombo = new ArrayList<>();

devera ficar assim:

static ArrayList<String> sCombo = new ArrayList<String>();

e também vc deve declarar essa sua variável:

txtVencimento
L

a

carlinbh

Esse código não está errado não cara:

static ArrayList<String> sCombo = new ArrayList<>();

A partir da versão 7 do java se eu não me engano pode ser feito isso sem problema.

R

Boa noite, declarando o JComboBox do void main ele passou a receber o foco.
ponto resolvido.

o proximo passo é enviar o foco para o txt2 apos teclar enter, tem uma parte do codigo com o evento keypressed
ai em baixo, noa está funcionando, por acaso tenho que fazer alguma declaraçao exttra la em cima?

conto com vcs.
obrigado
Reis

... static Calendar c = Calendar.getInstance(); static DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT); JComboBox cbx = new JComboBox(); /** * Launch the application. * @throws SQLException */ public static void main(String[] args) throws SQLException{
c.setTime(d);

	try{
		database += base; 
		conn = DriverManager.getConnection(database);
		JOptionPane.showMessageDialog(null, "Conectou!");
		stmt = conn.createStatement();
    ...
Criado 17 de abril de 2013
Ultima resposta 18 de abr. de 2013
Respostas 5
Participantes 4