我是来自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