gpt4 book ai didi

java - panel.setFocusable() 不起作用

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

我正在制作一个程序,允许用户在 JTextField 中输入文件路径,并在单击“查看”JButton 或按下 Enter 键时在 JTextArea 中显示文件的内容。

问题:单击“查看”按钮即可(显示文件内容)。但是,回车键不起作用。我认为 southPanel.setFocusable(true) 很困惑。

import java.awt.BorderLayout;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.*;

public class CFrame extends JFrame{
JTextArea outputTextArea = new JTextArea(); // Create a TextArea on which the contents of the file will be displayed
JPanel southPanel = new JPanel(); // Create a panel to be placed at the bottom of the frame
JScrollPane output = new JScrollPane(outputTextArea); // Create a ScrollPane for outputTextArea
JButton view = new JButton("View"); // This button, when clicked, displays the file's contents in outputTextArea
JTextField fileNameField = new JTextField(); // File Path/Name is entered in this field
CFrame() {
southPanel.setFocusable(true);
southPanel.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == e.VK_ENTER) {
view.setEnabled(true);
}
}
});
southPanel.setLayout(new BorderLayout());
southPanel.add(fileNameField,BorderLayout.CENTER);
southPanel.add(new JLabel(" File Name: "), BorderLayout.WEST);
southPanel.add(view, BorderLayout.EAST);
outputTextArea.setEditable(false);
setLayout(new BorderLayout(0,1));
add(output,BorderLayout.CENTER);
add(southPanel,BorderLayout.SOUTH);
view.addActionListener(new ButtonListener());
}

public class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String fileName = fileNameField.getText();
String data = "";
File file = new File(fileName);
try {
Scanner input = new Scanner(file);
while(input.hasNextLine()) {
data = data + input.nextLine() + "\n\r";
}
outputTextArea.setText(data);
}
catch(FileNotFoundException ex) {
System.out.println("No such file");
}
southPanel.requestFocusInWindow();
}
}
}

最佳答案

enter file path in a JTextField and displays the contents of the file in a JTextArea when the "View" JButton is clicked or the Enter Key is pressed

你的设计是错误的。您不应尝试监听面板上的 Enter 键。

将 ActionListener 添加到文本字段。如果文本字段具有焦点并且您按 Enter 键,则会调用 ActionListener。

关于java - panel.setFocusable() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31420461/

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