gpt4 book ai didi

java - 将 AcionListener 与 GUI 分离

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:55:30 25 4
gpt4 key购买 nike

我是 Java 编程的新手,目前正在参加为期 2 周的类(class)。请问是否可以将acionlistener与gui类分开?我想在学习期间应用 mvc,但不知道如何开始以及应该如何做。

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;


public class WriteFile extends JFrame implements ActionListener{
JTextArea textBox;
JButton convert;

WriteFile(){
//windows
setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
setVisible(true);
setSize(300, 300);
setLocationRelativeTo(null);
//others
textBox = new JTextArea("Type something here", 5, 15);
convert = new JButton("Display");
//layout
add(textBox, BorderLayout.CENTER);
add(convert, BorderLayout.LINE_END);
//actionlistener
convert.addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent event) {
String output = "";
output = textBox.getText();
JOptionPane.showMessageDialog(null, output);

}
}

这是我的主要内容:

import java.awt.BorderLayout;

public class main {

public static void main(String[] args) {
WriteFile wc = new WriteFile();
wc.pack();
}
}

最佳答案

我会看一下 Action API。

它允许您定义“操作”及其独立于 UI 的属性。

这是一个非常强大的概念,因为它允许您以独立的方式集中常用的操作,从而允许它们被重用。

看看How to use Actions获取更多信息。

关于java - 将 AcionListener 与 GUI 分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12833030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com