Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Pessoal, estou começando com Swing..
tenho uma classe simples, que ao clicar num botão produz o resultado de mudar o texto de uma "label";
o metodo do clicar segue abaixo:
class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent ae) {
if ( ae.getSource() == sim ) {
mensagem.setText("Clicado: SIM");
} else if ( ae.getSource() == nao ) {
mensagem.setText("Clicado: NAO");
}
}
}
essa classe ok ("sim" e "nao" são os botões que alteram a "label" mensagem).
Agora queria mudar a cor de um painel, então adaptei assim:
class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent ae){
if (ae.getSource() == b1){
painel2.setBackground(Color.RED);
}
else if (ae.getSource() == b2){
painel2.setBackground(Color.BLUE);
}
else if (ae.getSource() == b3){
painel2.setBackground(Color.GREEN);
}
else{
}
}
}
compila (isso q eu acho estranho) e exibe os painéis, botões ok.. mas ao clicar em qualquer botão da erro de "Action Listener", "GetSource"..
(ainda não estou usando IDE; bloco de notas mesmo, puro e simples).
agradeço antecipadamente por alguma dica..
olá.. claro; a classe toda segue abaixo:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TestaBotao2 extends JFrame{
private JButton b1,b2,b3;
private JPanel painel1;
private JPanel painel2;
public TestaBotao2(){
super ("I am a JFrame");
b1=new JButton ("Red");
b2=new JButton ("Blue");
b3=new JButton ("Green");
}
public void init(){
ButtonHandler buttonHandler=new ButtonHandler();
b1.addActionListener(buttonHandler);
b2.addActionListener(buttonHandler);
b3.addActionListener(buttonHandler);
Container tela = this.getContentPane();
tela.setLayout(new GridLayout());
JPanel painel1=new JPanel();
painel1.setBackground(Color.GREEN);
painel1.setSize(200, 100);
JPanel painel2=new JPanel();
painel2.setBackground(Color.BLUE);
painel2.setSize(200, 100);
tela.add(painel1);
tela.add(painel2);
painel1.add(b1);
painel1.add(b2);
painel1.add(b3);
this.setSize(400,150);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent ae){
if (ae.getSource() == b1){
painel2.setBackground(Color.RED);
}
else if (ae.getSource() == b2){
painel2.setBackground(Color.BLUE);
}
else if (ae.getSource() == b3){
painel2.setBackground(Color.GREEN);
}
else{
}
}
}
public static void main (String args[]) {
new TestaBotao2().init();
}
}Não consegui identificar o erro. Acredito que você seja por você estar comparando de forma errada a instancia dos botões na classe "ButtonHandler". Eu fiz um código rápido aqui, espero que ajude:
Main:
public class Main {
public static void main(String[] args) {
new ButtonHandler(new ButtonTest());
}
}
ButtonTest:
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class ButtonTest extends JFrame {
public ButtonTest() {
super("I am a JFrame!");
for (int i = 0; i < button.length; i++)
this.button[i] = new JButton(buttonName[i]);
initFrame();
}
private void initFrame() {
this.getContentPane().setLayout(new GridLayout());
this.setSize(400, 150);
panel1 = new JPanel();
panel1.setBackground(Color.GREEN);
panel1.setSize(200, 100);
this.getContentPane().add(panel1);
panel2 = new JPanel();
panel2.setBackground(Color.BLUE);
panel2.setSize(200, 100);
this.getContentPane().add(panel2);
for (int i = 0; i < button.length; i++)
this.panel1.add(button[i]);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
public JButton getButton(int i) {
return button[i];
}
public void setColor (String color) {
switch(color){
case "Red": this.panel1.setBackground(Color.RED); break;
case "Blue": this.panel1.setBackground(Color.BLUE); break;
case "Green": this.panel1.setBackground(Color.GREEN); break;
}
}
private JButton button[] = new JButton[3];
private String buttonName[] = {"Red", "Blue", "Green"};
private JPanel panel1, panel2;
}
ButtonHandler:
import java.awt.event.*;
import javax.swing.*;
public class ButtonHandler extends JFrame implements ActionListener {
private ButtonTest buttonTest;
public ButtonHandler(ButtonTest bt) {
buttonTest = bt;
for (int i = 0; i < 3; i++) {
buttonTest.getButton(i).addActionListener(this);
}
}
@Override
public void actionPerformed(ActionEvent e) {
JButton bt = (JButton)e.getSource();
switch (bt.getText()) {
case "Red": buttonTest.setColor("Red"); break;
case "Blue": buttonTest.setColor("Blue"); break;
case "Green": buttonTest.setColor("Green"); break;
}
}
}olá.. agradeço, mas nem vai compilar pq switch não testa string..
Basta fazer com enum e comparar os números, dá na mesma.
Fiz no Netbeans 7.3 e funcionou perfeitamente.
ok, vou tentar. agradeço
Poderia postar o código da classe contendo o JFrame e os componentes?