将 jbutton 连接到 void class

Connect jbutton to void class

我想将 jcomp1 连接到 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);
    }

我试过:

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);
  } 
} );

但是好像不行... 有任何想法吗? 我刚开始编码,我认为这是一个简单的项目,但我已经遇到了麻烦。出于这个原因,你能解释得尽可能清楚吗?谢谢。

这是一个如何创建带有交互式按钮的基本 java 摆动框架的示例。

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");
}
}

您只需要在主方法中实例化 win class。