我试图调试我的家庭作业计划,但我甚至不能这样做,因为我不知道为什么我的按钮不起作用。 任何帮助表示赞赏,谢谢! (我知道我的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() ;
}
}
}
}
}
答案 0 :(得分:1)
你有一个阴影问题。你声明......
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) {
总是false
您还要将ActionListener
(this
)添加到findnext
按钮四次...我认为您的意思是将其添加到其他每个按钮
请注意,AWT中已经有一个名为Window
的课程,这可能会让人感到困惑。它也不鼓励直接从像JFrame
这样的顶级容器扩展,而应该从JPanel
开始并将其添加到JFrame
的实例(或者任何容器)你喜欢)
答案 1 :(得分:1)
试试这个: 在你的构造函数中更新这一行:
JButton findnext = new JButton("FindNext");
//
JButton replace = new JButton("Replace");
//
JButton delete = new JButton("Delete");
//
JButton upper = new JButton("Upper");
使用这个:
findnext = new JButton("FindNext");
//
replace = new JButton("Replace");
//
delete = new JButton("Delete");
//
upper = new JButton("Upper");