java jbutton关联事件,java – 在另一个类中处理JButton click事件

我是来自C#的java的新手,所以我不熟悉java最佳实践.

我有一个主类打开一个JFrame来从用户获取几个输入字符串.当用户单击提交时,GUI应该关闭,主类继续使用输入进行处理.

这是主要类:

public class Main {

FInput fInput;

public void main(String[] args) {

if(args.length==0)

{

fInput = new FInput();

fInput.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

fInput.pack();

fInput.setVisible(true);

}

else

startProcess(args);

}

public void startProcess(String[] args) {

// Do stuff

}

主类将使用此框架从用户获取输入:

public class FInput extends JFrame{

private JTextField txtSourceDirectory;

private JTextField txtTargetDirectory;

private JTextField txtDefectNumber;

private JTextField txtSliceTokens;

private JButton btnStart;

public FInput() {

// Initialize text fields and button

JButton.addActionListener(something);

}

}

在我能找到的所有例子中,听众本身就是一个FMain.但是在这种情况下,我希望Main监听并使用方法startProcess中的输入.

将Main实现ActionListener,并将其传递给FMain构造函数是可行的方法吗?

解决方法:

是的,这是正确的想法.但是,为了能够做到这一点,你必须做两件事:

>将它放在FInput类的开头:

Main m = new Main(this);

>然后,把这些行放在Main类的某个地方……

FInput gui;

public Main(FInput in) { gui = in; }

现在,您可以通过执行类似操作从Main类引用FInput类中的任何组件.

gui.someComponent ...

要设置监听器,只需编写someComponent.addItemListener(m);或类似的东西.

希望这可以帮助!

@Yoav回复你的最新评论……

You don’t have to separate the listening class from the GUI class; you can combine the two into one class…

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class Main extends JFrame implements ActionListener {

private JTextField txtSourceDirectory;

private JTextField txtTargetDirectory;

private JTextField txtDefectNumber;

private JTextField txtSliceTokens;

private JButton btnStart;

public Main() {

txtSourceDirectory = new JTextField(40); //change this to the amount of characters you need

txtTargetDirectory = new JTextField(40);

txtDefectNumber = new JTextField(40);

txtSliceTokens = new JTextField(40);

btnStart = new JButton("Start");

add(txtSourceDirectory);

add(txtTargetDirectory);

add(txtDefectNumber);

add(txtSliceTokens);

add(btnStart);

btnStart.addActionListener(this);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

pack();

setVisible(true);

}

public void actionPerformed(ActionEvent event) {

//do stuff

}

static void startProcess(String[] ARGS) {

//do stuff

}

public static void main(String[] args) {

if (args.length == 0) {

Main frame = new Main();

} else {

startProcess(args);

}

}

}

标签:java,events,swing

来源: https://codeday.me/bug/20191008/1870522.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值