I wanted to connect jcomp1 to the void class somma
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import javax.swing.*;
import javax.swing.event.*;
@SuppressWarnings({ "unused", "serial" })
public class Calcolatrice extends JPanel {
private JButton jcomp1;
public Calcolatrice() {
//construct components
jcomp1 = new JButton ("Somma");
}
void somma(){
String val1 = jcomp5.getText();
String val2 = jcomp6.getText();
String sum = val1 + val2;
System.out.println(sum);
}
And I tried with:
jcomp1.addActionListener(new ActionListener() {
public void somma(ActionEvent e) {
String val1 = jcomp5.getText();
String val2 = jcomp6.getText();
String sum = val1 + val2;
System.out.println(sum);
}
} );
But it doesn't seem to work... Any ideas? I just started coding and I thought this was an easy project but I'm already having troubles. For this reason could you explain as clear as possible please? Thank you.
This is an example of how to create a basic java swing frame with an interactive button.
public class Win extends JFrame implements ActionListener {
private JButton btn;
private JTextField tf;
private JTextField tf1;
private Label label;
private Panel panel;
public Win() {
btn = new JButton("Click");
tf = new JTextField(" ");
tf1 = new JTextField(" ");
label = new Label();
label.setPreferredSize(new Dimension(300,100));
panel = new Panel();
btn.addActionListener(this);
panel.add(btn);
panel.add(tf);
panel.add(tf1);
panel.add(label);
this.add(panel);
this.setSize(500, 500);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
label.setText(tf.getText()+" "+tf1.getText());
System.out.println("clicked");
}
}
You just need to instanciate the win
class inside your main method.