I’m new to java programming and currently enrolled in a 2week class. I’d like to ask is it possible to separate acionlistener from the gui class? I’d like to apply mvc while I’m still learning but have no idea on how to start with and how should I do it.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class WriteFile extends JFrame implements ActionListener{
JTextArea textBox;
JButton convert;
WriteFile(){
//windows
setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
setVisible(true);
setSize(300, 300);
setLocationRelativeTo(null);
//others
textBox = new JTextArea("Type something here", 5, 15);
convert = new JButton("Display");
//layout
add(textBox, BorderLayout.CENTER);
add(convert, BorderLayout.LINE_END);
//actionlistener
convert.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent event) {
String output = "";
output = textBox.getText();
JOptionPane.showMessageDialog(null, output);
}
}
and here is my main:
import java.awt.BorderLayout;
public class main {
public static void main(String[] args) {
WriteFile wc = new WriteFile();
wc.pack();
}
}
I would take a look at the
ActionAPI.It allows you to define a “Action” and it’s properties independently of the UI.
It’s a very powerful concept as it allows you to centralise commonly used actions in a independent way that allows them to be reused.
Have a look at How to use Actions for more information.