英文:
How to make my JButtons to do different tasks on click?
问题
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
public class GUI {
JLabel eventName;
JLabel eventVenue;
JTextField name;
JTextField venue;
JButton create;
JButton reset;
JButton sortDate;
JButton sortProfit;
JTextArea text;
public GUI() {
WidgetViewer wv = new WidgetViewer();
eventName = new JLabel("Event Name");
name = new JTextField();
eventVenue = new JLabel("Event Venue");
venue = new JTextField();
// similar code for other inputs
text = new JTextArea("");
wv.add(eventName, 10, 30, 300, 20);
wv.add(name, 10, 50, 300, 20 );
wv.add(eventVenue, 10, 70, 300, 20);
wv.add(venue, 10, 90, 300, 20);
// similar for the rest
wv.add(text, 10, 470, 900, 20);
create = new JButton("Create an Event");
reset = new JButton("Reset List");
sortDate = new JButton("Sort by Date");
sortProfit = new JButton("Sort by Profit");
wv.add(create, 10, 320, 300, 20);
wv.add(reset, 10, 380, 300, 20);
wv.add(sortDate, 10, 410, 300, 20);
wv.add(sortProfit, 10, 440, 300, 20);
Inner action = new Inner();
create.addActionListener(action);
reset.addActionListener(action);
sortDate.addActionListener(action);
sortProfit.addActionListener(action);
}
class Inner implements ActionListener {
public Inner() {}
@Override
public void actionPerformed(ActionEvent e) {
String eventName = name.getText();
String eventVenue = venue.getText();
// Extract other input values
ArrayList<Event> allEvents = new ArrayList<Event>();
Event event = new Event(eventName, eventVenue, /* other input values */);
allEvents.add(event);
String eventsText = "";
for (int i = 0; i < allEvents.size(); i ++) {
eventsText = eventsText + allEvents.toString();
}
text.setText(eventsText);
// Clear input fields
name.setText("");
venue.setText("");
// Clear other input fields
if (e.getActionCommand().contains("Reset List")) {
text.setText("");
}
// Add other conditions if needed
}
}
}
英文:
I am trying to make my WidgetViewer GUI to do different tasks when the button is clicked. For example, the create button will create an Event based on the inputs and print out the Events (can be more than 1), the reset button will reset everything, etc. This is what I have so far (please note my create button doesn't work as intended, it doesn't increment my events for some reason)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
public class GUI {
JLabel eventName;
JLabel eventVenue;
JTextField name;
JTextField venue;
JButton create;
JButton sell;
JButton reset;
JButton sortDate;
JButton sortProfit;
JTextArea text;
//similar for rest
public GUI() {
WidgetViewer wv = new WidgetViewer();
eventName = new JLabel("Event Name");
name = new JTextField();
eventVenue = new JLabel("Event Venue");
venue = new JTextField();
//similar code for other inputs
text = new JTextArea("");
wv.add(eventName, 10, 30, 300, 20);
wv.add(name, 10, 50, 300, 20 );
wv.add(eventVenue, 10, 70, 300, 20);
wv.add(venue, 10, 90, 300, 20);
// similar for the rest
wv.add(text, 10, 470, 900, 20);
create = new JButton("Create an Event");
reset = new JButton("Reset List");
sortDate = new JButton("Sort by Date");
sortProfit = new JButton("Sort by Profit");
wv.add(create, 10, 320, 300, 20);
wv.add(reset, 10, 380, 300, 20);
wv.add(sortDate, 10, 410, 300, 20);
wv.add(sortProfit, 10, 440, 300, 20);
Inner action = new Inner();
create.addActionListener(action);
sell.addActionListener(action);
reset.addActionListener(action);
sortDate.addActionListener(action);
sortProfit.addActionListener(action);
}
class Inner extends WidgetViewerActionEvent {
public Inner() {}
@Override
public void actionPerformed(ActionEvent e) {
String eventName = name.getText();
String eventVenue = venue.getText();
int venueCapacity = Integer.parseInt(capacity.getText());
String eventDate = date.getText();
int ticketsSold = Integer.parseInt(sold.getText());
int ticketPrice = Integer.parseInt(price.getText());
int overhead = Integer.parseInt(costs.getText());
ArrayList<Event> allEvents = new ArrayList<Event>();
Event event = new Event(eventName, eventVenue, venueCapacity, eventDate, ticketsSold, ticketPrice, overhead);
allEvents.add(event);
String eventsText = "";
for (int i = 0; i < allEvents.size(); i ++) {
eventsText = eventsText + allEvents.toString();
}
text.setText(eventsText);
name.setText("");
venue.setText("");
capacity.setText("");
date.setText("");
sold.setText("");
price.setText("");
costs.setText("");
if (e.getActionCommand().contains("Reset List")) {
text.setText("");
}
//else ifs if that's the right approach?
}
}
}
答案1
得分: 2
以下是您要翻译的内容:
现在有几个选项:
您可以从发生事件的调用对象中获取它,或者使用操作命令。
个人而言,我喜欢创建一个响应GUI的控制器类,在其中有以下结构的几种方法:
public ActionListener getFirstButtonActionListener() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//做一些事情
}
};
}
public ActionListener getSecondButtonActionListener() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//做一些事情
}
};
}
现在,您只需将每个函数添加到正确的按钮上,这样就不会混淆了。
create.addActionListener(getController().getFirstButtonActionListener());
reset.addActionListener(getController().getSecondButtonActionListener());
编辑:
对于那些难以理解getController()
来自何处以及它应该做什么的人们 -
我们将视图和按下按钮时执行的操作拆分成两个类。
第一个是原始的WidgetViewer
类
第二个是WidgetController
类
我认为我会摆脱大部分GUI类,但这只是一个建议(我将在这里展示)。
无论如何,WidgetController
应该在构造函数中接受一个变量,该变量是WidgetViewer
对象或GUI对象,具体取决于它应该能够更改什么。
public class WidgetController
{
private WidgetViewer view;
public WidgetController(WidgetViewer view)
{
this.view = view;
}
//现在是监听器函数
public ActionListener getResetButtonActionListener()
{
return new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
//做一些事情
}
};
}
}
在WidgetViewer
内部(或在您的代码中,除非您在GUI类内部进行更改),您有一个用于控制器的类变量。
就像这样:
//小部件自己处理,它不只是一个面板,否则它就是一个无用的类
public class WidgetViewer extends JPanel
{
JLabel eventName;
JLabel eventVenue;
JTextField name;
JTextField venue;
JButton create;
JButton sell;
JButton reset;
JButton sortDate;
JButton sortProfit;
JTextArea text;
//这将保存控制器对象
WidgetController controller;
public WidgetViewer() {
//创建一个知道此视图的控制器
this.controller = new WidgetController(this);
initGui();
}
public WidgetController getController()
{
return this.controller;
}
public void initGui()
{
eventName = new JLabel("Event Name");
name = new JTextField();
eventVenue = new JLabel("Event Venue");
venue = new JTextField();
//其他输入的类似代码
text = new JTextArea("");
this.add(eventName, 10, 30, 300, 20);
this.add(name, 10, 50, 300, 20 );
this.add(eventVenue, 10, 70, 300, 20);
this.add(venue, 10, 90, 300, 20);
//其他元素的类似代码
this.add(text, 10, 470, 900, 20);
create = new JButton("Create an Event");
reset = new JButton("Reset List");
sortDate = new JButton("Sort by Date");
sortProfit = new JButton("Sort by Profit");
wv.add(create, 10, 320, 300, 20);
wv.add(reset, 10, 380, 300, 20);
wv.add(sortDate, 10, 410, 300, 20);
wv.add(sortProfit, 10, 440, 300, 20);
//每个方法应该在widgetController类内部创建
create.addActionListener(getController().getCreateButtonActionListener());
sell.addActionListener(getController().getSellButtonActionListener());
reset.addActionListener(getController().getResetButtonActionListener());
sortDate.addActionListener(getController().getSortDataButtonActionListener());
sortProfit.addActionListener(getController().getSortProfitButtonActionListener());
}
}
最后,GUI类变成了主类,并实例化了框架和小部件:
public class Gui //变成您的主类,只创建框架和小部件
{
public static void main(String[] args) throws IOException {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
WidgetViewer view = new WidgetViewer();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(view);
frame.setTitle("widget");
frame.pack();
frame.setVisible(true);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
}
});
}
}
英文:
now there are several options:
you could get the calling object from which the event originated or use action commands.
personally i like to create a controller class that responds to the GUI
in which i have several methods of the following structure:
public ActionListener getFirstButtonActionListener() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//do somethong
}
};
}
public ActionListener getSecondButtonActionListener() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//do somethong
}
};
}
now you just add each function to the correct button this way there is no confusion
create.addActionListener(getController().getFirstButtonActionListener());
reset.addActionListener(getController().getSecondButtonActionListener());
EDIT:
for those who have a hard time realizing where the getController() comes from and what it should do -
we split the view and the actions performed when pressing buttons to 2 classes.
the first is the original class WidgetViewer
the second is the WidgetController class
i think i would get reed of most of the gui class but that is a suggestion (which i`m going to show here).
anyhow the WidgetController should accept a variable in the constructor for the WidgetViewer object or the gui object depending on what it should be able to change.
so:
public class WidgetController
{
private WidgetViewer view;
public WidgetController (WidgetViewer view)
{
this.view=view;
}
//now the listener functions
public ActionListener getResetButtonActionListener()
{
return new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
//do somethong
}
};
}
}
inside the WidgetViewer (or in your code unless you change it inside the gui class) you have a class variable for the controller.
like so:
//the widget handles itself its not just a panel otherwise its a useless class
public class WidgetViewer extends JPanel
{
JLabel eventName;
JLabel eventVenue;
JTextField name;
JTextField venue;
JButton create;
JButton sell;
JButton reset;
JButton sortDate;
JButton sortProfit;
JTextArea text;
//this would hold the controller object
WidgetController controller;
public WidgetViewer() {
//create a controller that knows this view
this.controller=new WidgetController(this);
initGui();
}
public WidgetController getController()
{
return this.controller;
}
public initGui()
{
eventName = new JLabel("Event Name");
name = new JTextField();
eventVenue = new JLabel("Event Venue");
venue = new JTextField();
//similar code for other inputs
text = new JTextArea("");
this.add(eventName, 10, 30, 300, 20);
this.add(name, 10, 50, 300, 20 );
this.add(eventVenue, 10, 70, 300, 20);
this.add(venue, 10, 90, 300, 20);
// similar for the rest
this.add(text, 10, 470, 900, 20);
create = new JButton("Create an Event");
reset = new JButton("Reset List");
sortDate = new JButton("Sort by Date");
sortProfit = new JButton("Sort by Profit");
wv.add(create, 10, 320, 300, 20);
wv.add(reset, 10, 380, 300, 20);
wv.add(sortDate, 10, 410, 300, 20);
wv.add(sortProfit, 10, 440, 300, 20);
//each of the methods should be created inside the widgetController class
create.addActionListener(getController().getCreateButtonActionListener());
sell.addActionListener(getController().getSellButtonActionListener());
reset.addActionListener(getController().getResetButtonActionListener());
sortDate.addActionListener(getController().getSortDataButtonActionListener());
sortProfit.addActionListener(getController().getSortProfitButtonActionListener());
}
}
last the GUi class turns into main class and isntantiate the frame and the widget:
public class Gui //turns into your main class only creates the frame and the widget
{
public static void main(String[] args) throws IOException {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
WidgetViewer view=new WidgetViewer();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(view);
frame.setTitle("widget");
frame.pack();
frame.setVisible(true);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
}
});
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论