Swing:Exemplo JComboBox
De Wiki Cursos IFPR Foz
package swing;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class FolhaDePagamento extends JFrame{
private static final int marginLeft = 20;
private static final int marginMeio = 200;
private static int top = 20;
private List<Funcionario> funcionarios;
public FolhaDePagamento(String title){
super(title);
setSize(500,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// sem layout...
getContentPane().setLayout(null);
inicializaFuncionarios();
JTextField salTxt = new JTextField();
JLabel jfun = new JLabel("Tipo Funcionario:");
jfun.setBounds(marginLeft,top,200,30);
add(jfun);
JComboBox select =
new JComboBox(funcionarios.toArray());
select.setBounds(marginMeio,top,200,30);
select.insertItemAt("--Selecione o cargo--", 0);
select.setSelectedIndex(0);
select.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(select.getSelectedIndex()!=0){
// retorna o objeto selecionado:
Funcionario f = (Funcionario)select.getSelectedItem();
salTxt.setText(f.getSalario()+"");
}else{
salTxt.setText("");
}
}
});
add(select);
top = top + 50;
JLabel jSal = new JLabel("Salário:");
jSal.setBounds(marginLeft,top,200,30);
add(jSal);
salTxt.setBounds(marginMeio,top,200,30);
add(salTxt);
top = top + 50;
JLabel jBono = new JLabel("Bonificacao:");
jBono.setBounds(marginLeft,top,200,30);
add(jBono);
JTextField bonoTxt = new JTextField();
bonoTxt.setBounds(marginMeio,top,200,30);
add(bonoTxt);
top = top + 50;
JSeparator sep = new JSeparator();
sep.setBounds(marginLeft,top,400,5);
add(sep);
top = top + 50;
JLabel jtotal = new JLabel("Total:");
jtotal.setBounds(marginLeft,top,200,30);
add(jtotal);
JLabel jvalor = new JLabel("R$ ");
jvalor.setBounds(marginMeio,top,200,30);
add(jvalor);
}
private void inicializaFuncionarios() {
funcionarios = new ArrayList<Funcionario>();
Funcionario f1 = new Funcionario("Diretor",4000d);
Funcionario f2 = new Funcionario("Gerente",5000d);
Funcionario f3 = new Funcionario("Analista",3000d);
funcionarios.add(f1);
funcionarios.add(f2);
funcionarios.add(f3);
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel");
FolhaDePagamento f =
new FolhaDePagamento("Folha de pagamento");
f.setVisible(true);
}
}