Trocar a imagem quando clicar no botão
Oi gente, tenho uma dúvida e não consigo resolver.
Como eu faço pra chamar uma outra imagem quando apertar o botão?
Tai o código:
Obrigada desde já. :-D
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
//criar um novo metodo, usando ImageButton;
public class BotaoComando extends JFrame implements ActionListener {
JButton botaoComando;
String pedindoComando = "@@@,a?,&";
char[] comandoChar = pedindoComando.toCharArray();
int[] comandoInteiro = new int[comandoChar.length];
JLabel label;
DriverSerial driver;// = new DriverSerial ("comandoInteiro");
public BotaoComando()
{
super(" Controle ");
Container tela = getContentPane();
tela.setLayout(null);
botaoComando = new JButton ("Controle TV");
botaoComando.setBounds(180, 30, 100, 40);
ImageIcon img = (new ImageIcon("C:/Katarina/Controle/controle.jpg"));
if(img == null)
{
System.out.println("erro");
}
label = new JLabel(img);
label.setBounds(80,80,290,290);
tela.add(botaoComando);
tela.add(label);
this.setSize(600,440);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
botaoComando.addActionListener((ActionListener) this);
botaoComando.setToolTipText("Clique neste botão "
+ "para usar o controle.");
driver = new DriverSerial("Controle TV");
driver.open();
}
private boolean ImageIcon(String string) {
// TODO Auto-generated method stub
return false;
}
public void actionPerformed(ActionEvent e)
{
for (int cont = 0; cont >= comandoInteiro.length; cont++)
{
System.out.println (comandoInteiro[0]);
}
//System.out.println("Testando código");
driver.sendBytes(comandoInteiro);
}
public static void main(String args[])
{
new BotaoComando();
}
}Katarina
Curtidas 0
Respostas
Thales Barbosa
21/10/2010
Eu sei que isso funciona com o label agora no botão eu nunca testei, tenta ai e me fala
jLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("arquivo de imagemf")));
Deve ser gif ou png (senão me engano)
GOSTEI 0
Thales Barbosa
21/10/2010
Oi, obrigada por responder =)
Testei, mas deu mtos erros quando compilou, olha só:
Coisas assim... :roll:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at javax.swing.ImageIcon.<init>(Unknown Source) at BotaoComando.actionPerformed(BotaoComando.java:66) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
GOSTEI 0
Thales Barbosa
21/10/2010
Katarina eu testei no netbeans 6.5 e funciona perfeitamente, eu adicionei um botão no formulario e no evento dele coloquei esse código
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/xSimbolo.gif")));
Funcionou sem erro nenhum e a imagem foi alterada.
GOSTEI 0
Thales Barbosa
21/10/2010
Oii Thales, testei de novo.
Primeiro da um erro, pq tem q criar uma variavel Jlabel, depois pede pra inicializar, então corrigindo isso, o código fica assim:
O seu ta da mesma forma?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
//criar um novo metodo, usando ImageButton;
public class BotaoComando extends JFrame implements ActionListener {
JButton botaoComando;
String pedindoComando = "@@@,a?,&";
char[] comandoChar = pedindoComando.toCharArray();
int[] comandoInteiro = new int[comandoChar.length];
JLabel label;
DriverSerial driver;// = new DriverSerial ("comandoInteiro");
public BotaoComando()
{
super(" Controle ");
Container tela = getContentPane();
tela.setLayout(null);
botaoComando = new JButton ("Controle TV");
botaoComando.setBounds(180, 30, 100, 40);
ImageIcon img = (new ImageIcon("C:/Katarina/Controle/controle.jpg"));
if(img == null)
{
System.out.println("erro");
}
label = new JLabel(img);
label.setBounds(80,80,290,290);
tela.add(botaoComando);
tela.add(label);
this.setSize(600,440);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
botaoComando.addActionListener((ActionListener) this);
botaoComando.setToolTipText("Clique neste botão "
+ "para usar o controle.");
driver = new DriverSerial("Controle TV");
driver.open();
}
private boolean ImageIcon(String string) {
// TODO Auto-generated method stub
return false;
}
public void actionPerformed(ActionEvent e)
{
JLabel Jlabel = null;
Jlabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("C:/Katarina/Controle/ctr.jpg")));
// botaoComando.setActionCommand("C:/Katarina/Controle/ctr.jpg");
for (int cont = 0; cont >= comandoInteiro.length; cont++)
{
System.out.println (comandoInteiro[0]);
}
//System.out.println("Testando código");
driver.sendBytes(comandoInteiro);
}
public static void main(String args[])
{
new BotaoComando();
}
}
GOSTEI 0
Thales Barbosa
21/10/2010
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
//criar um novo metodo, usando ImageButton;
public class BotaoComando extends JFrame implements ActionListener {
JButton botaoComando;
String pedindoComando = "@@@,a?,&";
char[] comandoChar = pedindoComando.toCharArray();
int[] comandoInteiro = new int[comandoChar.length];
JLabel label;
//DriverSerial driver;// = new DriverSerial ("comandoInteiro");
public BotaoComando()
{
super(" Controle ");
Container tela = getContentPane();
tela.setLayout(null);
botaoComando = new JButton ("Controle TV");
botaoComando.setBounds(180, 30, 100, 40);
//TEM QUE SER ATRIBUIDO IMAGEM ASSIM NO CODIGO
ImageIcon img = (new javax.swing.ImageIcon(getClass().getResource("/vSimbolo.gif")));
if(img == null)
{
System.out.println("erro");
}
label = new JLabel(img);
label.setBounds(80,80,290,290);
tela.add(botaoComando);
tela.add(label);
this.setSize(600,440);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
botaoComando.addActionListener((ActionListener) this);
botaoComando.setToolTipText("Clique neste botão "
+ "para usar o controle.");
//driver = new DriverSerial("Controle TV");
//driver.open();
}
private boolean ImageIcon(String string) {
// TODO Auto-generated method stub
return false;
}
public void actionPerformed(ActionEvent e)
{
//PARA ALTERAR A IMAGEM DO LABEL QUE FOI INSERIDO ANTES TIRA ESSE LABEL AI VOCê ESTA COLOCANDO OUTRO E COM PARAMETROS NULOS, E DEIXA O LABEL(INSERIDO ACIMA).
//JLabel Jlabel = null;
label.setIcon(new javax.swing.ImageIcon(getClass().getResource("/xSimbolo.gif")));
// botaoComando.setActionCommand("C:/Katarina/Controle/ctr.jpg");
//for (int cont = 0; cont >= comandoInteiro.length; cont++)
//{
// System.out.println (comandoInteiro[0]);
//}
//System.out.println("Testando código");
//driver.sendBytes(comandoInteiro);
}
public static void main(String args[])
{
new BotaoComando();
}
Eu fiz o seguinte coloquei comentários em tudo que não precisava para imagem alterar imagem isolando erros então ficou assim oh as alterações estão como comentário no código.
FUNCIONOU PERFEITAMENTE AGORA EU COLOCARIA A IMAGEM DENTRO DO PROJETO E CHAMARIA COMO EU FIZ NO EXEMPLO QUE TE MANDEI, ESTAREI NA NET AMANHÃ NOVAMENTE QQ DÚVIDA DEIXA AQUI NO FÓRUM QUE DOU UMA OLHADA AMANHÃ.
GOSTEI 0
Thales Barbosa
21/10/2010
Oii Thales :D
Bom, fiz da forma que vc falou e deu esse erro:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at BotaoComando.<init>(BotaoComando.java:121)
at BotaoComando.main(BotaoComando.java:172)
Não entendo, tudo parece tão certo e não compila =/
GOSTEI 0
Thales Barbosa
21/10/2010
Coloca seu código. Para dar uma olhada, volto daqui a pouco, coloca o seu codigo inteiro ai pra eu ver, OK.
GOSTEI 0
Thales Barbosa
21/10/2010
Aii ele Thales.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
//criar um novo metodo, usando ImageButton;
public class BotaoComando extends JFrame implements ActionListener {
JButton botaoComando;
String pedindoComando = "@@@,a?,&";
char[] comandoChar = pedindoComando.toCharArray();
int[] comandoInteiro = new int[comandoChar.length];
JLabel label;
String name = "C:/Katarina/Controle/ctr.jpg";
ImageIcon img = new ImageIcon(getClass().getResource("C:/Katarina/Controle/controle.jpg"));
ImageIcon img2 = new ImageIcon(getClass().getResource("C:/Katarina/Controle/ctr.jpg"));
DriverSerial driver;// = new DriverSerial ("comandoInteiro");
public BotaoComando() {
super(" Controle ");
Container tela = getContentPane();
tela.setLayout(null);
botaoComando = new JButton("Controle TV");
botaoComando.setBounds(180, 30, 100, 40);
//ImageIcon img = new ImageIcon("C:/Katarina/Controle/controle.jpg");
//ImageIcon img2 = new ImageIcon(getClass().getResource("C:/Katarina/Controle/ctr.jpg"));
//ImageIcon img = new ImageIcon(getClass().getResource("C:/Katarina/Controle/ctr.jpg"));
//ImageIcon img = new ImageIcon(Menu.class.getResource("C:/Katarina/Controle/ctr.jpg"));
if (img == null) {
System.out.println("erro");
}
label = new JLabel(img);
label.setBounds(80, 80, 290, 290);
tela.add(botaoComando);
tela.add(label);
this.setSize(600, 440);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
botaoComando.addActionListener(this);
botaoComando.setToolTipText("Clique neste botão "
+ "para usar o controle.");
driver = new DriverSerial("Controle TV");
driver.open();
}
private boolean ImageIcon(String string) {
// TODO Auto-generated method stub
return false;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == this.botaoComando){
System.out.println("Apertado");
botaoComando.setActionCommand(name);
botaoComando.setIcon(img2);
}
else
System.out.println("Apertado2");
// JLabel Jlabel = null;
// Jlabel.setIcon(new javax.swing.ImageIcon(getClass().getResource(
// "C:/Katarina/Controle/ctr.jpg")));
for (int cont = 0; cont >= comandoInteiro.length; cont++)
System.out.println(comandoInteiro[0]);
}
public static void main(String args[]) {
new BotaoComando();
}
}
GOSTEI 0
Thales Barbosa
21/10/2010
Katarina eu vi seu código e ta rodando OK, se ainda estiver dando null exception copia a imagem para a pasta do projeto se ainda estiver dando esse problema, comigo aconteceu uma vez isso o problema era que eu tinha compilado o projeto e depois adicionei uma imagem ele não tava reconhecendo eu fiz o limpar e construir ele aceitou, o seu código ta OK, testado e rodou perfeitamente
GOSTEI 0
Thales Barbosa
21/10/2010
é como o [url="http://javafree.uol.com.br/viewprofile.jbb?u=30067"][u]thales.barbosa[/u][/url] escreveu, é problema ao carregar as imagens.
Não olhei direito o código, mas o erro
indica que o ImageIcon está sendo construido com um argumento 'null'. Portanto o problema é que o 'getClass().getResource("C:/Katarina/Controle/controle.jpg")' não encontrou a imagem. O getResource procura caminhos relattivos (que não começam com barra) a partir de onde se encontra a classe, e a partir do CLASSPATH para caminhos absolutos (começam com barra '/').
Se o controle.jpg estiver no mesmo diretório que a classe (arquivo BotaoComando.class), use
(semelhante para as outras imagens)
[[]]
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
...
...
ImageIcon img = new ImageIcon(getClass().getResource("controle.jpg"));
...GOSTEI 0
Thales Barbosa
21/10/2010
Pois é, chequei novamente as imagens, o caminho está correto.
Não sei onde está o erro... =/
GOSTEI 0
Thales Barbosa
21/10/2010
Gentee, deu certo :!:
Troquei as imagens de pasta, daí quando mudei o caminho deu certo!
Muiito obrigada pela ajuda de vcs^^
GOSTEI 0
Thales Barbosa
21/10/2010
[quote="Katarina"]Pois é, chequei novamente as imagens, o caminho está correto.
Não sei onde está o erro... =/
talvez tenho que ser mais direto: caminhos com "C:/" no começo não devem funcionar...
O 'getResource' da Class procura com o algoritmo usado para [i]procurar[/i] uma classe.
[[]]
GOSTEI 0
Thales Barbosa
21/10/2010
Oi Carlos, obrigada pela explicação.
Foi exatamente o que eu fiz, coloquei as imagens no mesmo diretório, talvez não tenha conseguido explicar isso.
Mas tbm funciona usando apenas o ImageIcon.
Obrigada novamente pela ajuda. :mrgreen:
GOSTEI 0