Reputation: 145
Ok so I'm trying to get familier with Java, and I've made a simple thing where if you click a button then some text appears. How can I make it so the button and label are created in one class file, and put the code for when the button is clicked in another? Sorry if it sounds like a silly question.
Pastebin code:
package com.nate.derp;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Derp {
private JFrame frmHello;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Derp window = new Derp();
window.frmHello.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Derp() {
initialize();
}
public void initialize() {
frmHello = new JFrame();
frmHello.setTitle("Hello");
frmHello.setBounds(100, 100, 225, 160);
frmHello.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmHello.getContentPane().setLayout(null);
final JLabel helloLabel = new JLabel("Hello World!");
helloLabel.setVisible(false);
helloLabel.setBounds(40, 89, 145, 16);
frmHello.getContentPane().add(helloLabel);
final JButton btnClickMe = new JButton("Click Me!");
btnClickMe.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
helloLabel.setVisible(true);
}
});
btnClickMe.setBounds(54, 29, 117, 29);
frmHello.getContentPane().add(btnClickMe);
}
}
Upvotes: 2
Views: 228
Reputation: 3899
You can do this by creating a JButton and adding an ActionListener, which can be implemented by another class.
So you first create the JButton:
Jbutton button = new JButton("hello");
Then add the Actionlistener:
button.addActionListener(new MyListener());
Where MyListener is your implementation class
class MyListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
...
}
}
Upvotes: 1