gpt4 book ai didi

Java 按钮不起作用

转载 作者:行者123 更新时间:2023-11-30 03:57:01 25 4
gpt4 key购买 nike

我正在尝试调试我的程序以完成家庭作业,但我什至无法做到这一点,因为我不知道为什么我的按钮不起作用。任何帮助表示赞赏,谢谢! (我知道我的 findnext 现在很奇怪,但我不知道还能做什么,所以我现在只是调试它)

public class Window extends JFrame implements ActionListener {
private JButton findnext;
private JButton replace;
private JButton delete;
private JButton upper;
private JTextField from,to;
private JTextArea textArea;
final static Color found = Color.PINK;
final Highlighter hilit;
final Highlighter.HighlightPainter painter;

public Window() {
setTitle("Project 8");
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
setSize((d.width/4)*3,d.height);
textArea = new JTextArea ("The apple ate the apple.",8,40);
textArea.setLineWrap(true);
Container contentPane = getContentPane();
addWindowListener(new Close());
contentPane.add(textArea);
JPanel panel = new JPanel();
JButton findnext = new JButton("FindNext");
panel.add(findnext);
from = new JTextField(8);
panel.add(from);
findnext.addActionListener(this);
JButton replace = new JButton("Replace");
panel.add(replace);
to = new JTextField(8);
panel.add(to);
findnext.addActionListener(this);
JButton delete = new JButton("Delete");
panel.add(delete);
findnext.addActionListener(this);
JButton upper = new JButton("Upper");
panel.add(upper);
findnext.addActionListener(this);
contentPane.add(panel, "South");
hilit = new DefaultHighlighter();
painter = new DefaultHighlighter.DefaultHighlightPainter(found);
textArea.setHighlighter(hilit);
}

public void actionPerformed(ActionEvent evt) {
String f = from.getText();
String t = to.getText();
int n = textArea.getText().indexOf(f);
Object source = evt.getSource();

if (source == findnext) {
hilit.removeAllHighlights();
String text = textArea.getText();
int index = text.indexOf(f,0);
if (index>0) {
try {
hilit.addHighlight(index, index+f.length(), DefaultHighlighter.DefaultPainter);
}
catch (BadLocationException e) {
;
}
}else if (source == replace) {
if (n>=0 && f.length() > 0) {
textArea.replaceRange(to.getText(),n,n+f.length());
;
}else if (source == delete) {
textArea.setText(" ");
}else if (source == upper) {
f.toUpperCase() ;
}
}
}
}
}

最佳答案

您遇到了阴影问题。你声明...

private JButton findnext;
private JButton replace;
private JButton delete;
private JButton upper;

但是在你的构造函数中你...

JButton findnext = new JButton("FindNext");
//...
JButton replace = new JButton("Replace");
//...
JButton delete = new JButton("Delete");
//...
JButton upper = new JButton("Upper");

这是重新声明这些变量。

这意味着当您尝试并执行...

if (source == findnext) {

总是

您还将 ActionListener (this) 添加到 findnext 按钮四次...我认为您的意思是添加它到其他每个按钮

请注意,AWT 中已经有一个名为 Window 的类,这可能会引起人们的困惑。也不鼓励直接从 JFrame 等顶级容器进行扩展,而应该从 JPanel 开始,并将其添加到 JFrame 的实例中(或者你喜欢的任何容器)

关于Java 按钮不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22904006/

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