package javaapplication1;
import javax.swing.*;
import java.awt.event.*;
class Elem implements ActionListener{
void perform(){
JFrame frame = new JFrame();
JButton button;
button = new JButton("Button");
frame.getContentPane().add(button) ;
frame.setSize(350,350);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent ev){
button.setText("Clicked");
}
}
public class JavaApplication1 {
public static void main(String[] args) {
Elem obj = new Elem();
obj.perform();
}
}
Acabei de terminar minha primeira GUI java baseada em eventos, mas não tenho certeza de onde errei. Quando não havia manipulação de eventos, o código funcionava perfeitamente.
Por acaso você fez na mão isso ou usou um RAD como o WindowBuilder do eclipse? Mexer com JSwing do zero é inviável, mesmo vale para WindowsForms sem RAD do Visual Studio.
Usando o WindowBuilder do eclipse geraria um code behind assim:
package javaapplication1;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class JavaApplication1 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JavaApplication1 frame = new JavaApplication1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JavaApplication1() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JButton button = new JButton("Button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button.setText("Clicked");
}
});
contentPane.add(button);
}
}