gpt4 book ai didi

java - GUI 类(JTextField-JTextArea)

转载 作者:行者123 更新时间:2023-12-01 18:51:16 25 4
gpt4 key购买 nike

我是 GUI 和 java 新手,当我尝试编写此问题的代码时,我遇到了 actionPerformed 方法的问题:

  1. 使用下面所示的框架布局,编写一个程序来搜索在文本字段中输入标题的电影。当用户按下SEARCH按钮或按下ENTER键时,电影的信息(标题、年份和类型)显示在文本区域中。如果未找到该电影,则在文本区域中显示一条消息,指示该电影不存在。使用数组来存储多部电影的信息。

如果有人解释如何让此代码正常工作,我将非常感激。
我的尝试:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class movie {
public String title;
public String year;
public String genre;
public movie(String t, String y, String g) {
title = t;
year = y;
genre = g;
}
public String toString() {
return "TITLE: " + title + "\nYEAR: " + year + "\nGENRE: " + genre;
}
}

public class searchMovieFrame extends JFrame implements ActionListener {
public movie m1 = new movie("Iron Man", "2008", "Action,Adventure");
public movie m2 = new movie("Iron Man", "2010", "Action,Adventure");
public movie m3 = new movie("Total Recall", "2012", "Action,Adventure");
public movie[] movies = {
m1, m2, m3
};

private static final int width = 300;
private static final int height = 200;
private static final int x = 360;
private static final int y = 150;
private JButton search;
private JTextField input;
private JTextArea output;
private JLabel message;

public searchMovieFrame() {
Container contentPane = getContentPane();
setSize(width, height);
setResizable(false);
setTitle("Search Movie Frame");
setLocation(x, y);
contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));
message = new JLabel();
message.setText("Enter the movie title please");
message.setSize(150, 25);
contentPane.add(message);
input = new JTextField();
input.setColumns(15);
contentPane.add(input);
input.addActionListener(this);
search = new JButton("Search");
contentPane.add(search);
search.addActionListener(this);
output = new JTextArea();
output.setColumns(23);
output.setRows(5);
output.setEditable(false);
contentPane.add(output);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent event) {
for (int i = 0; i < 3; i++)
if (input.getText().equals(movies[i].title)) output.setText(toString());
else output.setText("THAT MOVIE IS NOT AVAILABLE");
}

public static void main(String[] args) {
searchMovieFrame frame = new searchMovieFrame();
frame.setVisible(true);
}
}

最佳答案

找到正确的电影后,您需要中断

还使用 Movie#toString 而不是当前 JFrametoString 表示形式。不要将搜索限制为前 3 部电影,请使用 movies.length 作为搜索上限。为了提高效率,任何组件更新都应该在循环处理完之后进行。

Movie searchMovie = null;
for (int i = 0; i < movies.length; i++) {
if (input.getText().equals(movies[i].title)) {
searchMovie = movies[i];
break;
}
}

if (searchMovie == null) {
output.setText("THAT MOVIE IS NOT AVAILABLE");
} else {
output.setText(searchMovie.toString());
}

旁白:使用 Java 命名约定来区分类,例如 Movie

关于java - GUI 类(JTextField-JTextArea),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15854532/

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