connectjbutton到void类

omjgkv6w  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(355)

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

但似乎不起作用。。。有什么想法吗?我刚开始编写代码,我认为这是一个简单的项目,但我已经有麻烦了。为此,请你尽可能解释清楚好吗?谢谢您。

d8tt03nd

d8tt03nd1#

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

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 在主方法中初始化。

相关问题