[RESOLVIDO] Tratando evento para JButton + JComboBox
4 respostas
T
tsmalavasi
Boa noite galera, sou novo por aqui e fiquei em dúvida se abria o tópico em Java Básico ou aqui mesmo.
Tenho um programinha bem simples, que adiciona uma nova linha no JComboBox, e um botão Apagar que limpa o mesmo JComboBox.
O que acontece é que depois que criei o evento que trata o botão apagar, ele aparece vários erros e por fim, não limpa a Combo.
Segue abaixo o código:
importjava.awt.BorderLayout;importjava.awt.GridLayout;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjavax.swing.JButton;importjavax.swing.JComboBox;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JMenu;importjavax.swing.JMenuBar;importjavax.swing.JMenuItem;importjavax.swing.JOptionPane;importjavax.swing.JPanel;publicclassPrincipalextendsJFrameimplementsActionListener{publicstaticvoidmain(String[]args){// TODO Auto-generated method stubPrincipalJFE=newPrincipal();JFE.setSize(400,150);JFE.setVisible(true);JFE.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}Stringnovo;String[]lista=newString[]{"Clique em Adicionar para inserir um novo item..."};JComboBoxcombo1=newJComboBox(lista);publicPrincipal(){super("Lab5");BorderLayoutl1=newBorderLayout();setLayout(l1);JMenuBarbar=newJMenuBar();this.setJMenuBar(bar);JMenum1=newJMenu("Adicionar");bar.add(m1);JMenum2=newJMenu("Sair");bar.add(m2);JMenuItemit1=newJMenuItem("Novo");it1.addActionListener(this);m1.add(it1);JMenuItemit3=newJMenuItem("Sair");it3.addActionListener(this);m2.add(it3);JPaneljp1=newJPanel();add(jp1);GridLayoutl2=newGridLayout(3,1,10,10);jp1.setLayout(l2);JLabellabel1=newJLabel("Adicione elementos:");jp1.add(label1);label1.setHorizontalAlignment(JLabel.CENTER);jp1.add(combo1);JButtonbotaoadd=newJButton("Apagar");jp1.add(botaoadd);botaoadd.addActionListener(this);}publicvoidactionPerformed(ActionEvente){JMenuItemmenuItem=(JMenuItem)e.getSource();if(menuItem.getText()=="Novo"){novo=JOptionPane.showInputDialog("Digite uma nova opção:");combo1.addItem(novo);}if(menuItem.getText()=="Sair"){System.exit(EXIT_ON_CLOSE);}JButtonbotao=(JButton)e.getSource();if(botao.getText()=="Apagar"){combo1.removeAllItems();}}}
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(botaoadd)){
combo1.removeAllItems();
}
}
T
tsmalavasi
silasyudi:
Acho que o erro é na comparação das Strings.
Acho q poderia fazer assim também:
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(botaoadd)){
combo1.removeAllItems();
}
}
Boa noite, os erros continuam os mesmos com qualquer uma das 2 opções, porém notei q eles começam quando dou ok na ImputDialog.
Segue abaixo as mensagens do console:
[color=red]Exception in thread “AWT-EventQueue-0” java.lang.ClassCastException: javax.swing.JMenuItem cannot be cast to javax.swing.JButton
at Principal.actionPerformed(Principal.java:73)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)[/color]
J
JuniorMaia
Este CAST é inválido, Faça um action para cada botão.
Este CAST é inválido, Faça um action para cada botão.
T
tsmalavasi1 like
JuniorMaia:
Este CAST é inválido, Faça um action para cada botão.
Resolvido! Muito obrigado à todos! Segue abaixo o código:
importjava.awt.BorderLayout;importjava.awt.GridLayout;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjavax.swing.JButton;importjavax.swing.JComboBox;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JMenu;importjavax.swing.JMenuBar;importjavax.swing.JMenuItem;importjavax.swing.JOptionPane;importjavax.swing.JPanel;publicclassPrincipalextendsJFrameimplementsActionListener{publicstaticvoidmain(String[]args){// TODO Auto-generated method stubPrincipalJFE=newPrincipal();JFE.setSize(400,150);JFE.setVisible(true);JFE.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}Stringnovo;String[]lista=newString[]{"Clique em Adicionar para inserir um novo item..."};JComboBoxcombo1=newJComboBox(lista);publicPrincipal(){super("Lab5");BorderLayoutl1=newBorderLayout();setLayout(l1);JMenuBarbar=newJMenuBar();this.setJMenuBar(bar);JMenum1=newJMenu("Adicionar");bar.add(m1);JMenum2=newJMenu("Sair");bar.add(m2);JMenuItemit1=newJMenuItem("Novo");ActionListeneral1=newActionListener(){publicvoidactionPerformed(ActionEvente){novo=JOptionPane.showInputDialog("Digite uma nova opção:");combo1.addItem(novo);}};it1.addActionListener(al1);m1.add(it1);JMenuItemit3=newJMenuItem("Sair");ActionListeneral2=newActionListener(){publicvoidactionPerformed(ActionEvente){System.exit(EXIT_ON_CLOSE);}};it3.addActionListener(al2);m2.add(it3);JPaneljp1=newJPanel();add(jp1);GridLayoutl2=newGridLayout(3,1,10,10);jp1.setLayout(l2);JLabellabel1=newJLabel("Adicione elementos:");jp1.add(label1);label1.setHorizontalAlignment(JLabel.CENTER);jp1.add(combo1);JButtonbotaoadd=newJButton("Apagar");ActionListeneral3=newActionListener(){publicvoidactionPerformed(ActionEvente){combo1.removeAllItems();}};botaoadd.addActionListener(al3);jp1.add(botaoadd);}@OverridepublicvoidactionPerformed(ActionEvente){// TODO Auto-generated method stub}}