0

这是我的记事本应用程序的视图。我需要创建一个控制器来搜索 centerPanel 中的 textarea。我定义了一个 JButton 以及一个文本字段,并希望用户能够在该字段中输入文本并按下按钮以突出显示搜索到的文本。我在一个新类中定义了所有 ActionListener。

public NotepadView() {
        super();
        //WINDOW
        setSize (750,500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Chad's Notepad");
        setLocationRelativeTo(null);
        setBackground(Color.BLACK);

        //CENTER PANEL
        centerPanel = new JPanel();
        centerPanel.setLayout(new FlowLayout());
        textArea = new JTextArea();
        centerPanel.add(textArea);
        add(centerPanel, BorderLayout.CENTER);
        scrollPaneText = new JScrollPane(textArea);
        add(scrollPaneText);
        textArea.setLineWrap(true);
        textArea.setFont(new Font("Garamond", Font.PLAIN, 18));

        //BOTTOM PANEL
        bottomPanel = new JPanel();
        bottomPanel.setLayout(new GridLayout(1,2));
        setButton = new JButton("Find");
        textField = new JTextField("EnterText");
        bottomPanel.add(setButton);
        bottomPanel.add(textField);
        add(bottomPanel, BorderLayout.SOUTH);

        //MENU BAR
        menuBar = new JMenuBar();
        fileMenu = new JMenu("File");   
        newItem = new JMenuItem("New");
        openItem = new JMenuItem("Open");
        saveItem = new JMenuItem("Save");
        closeItem = new JMenuItem("Close");
        menuBar.add(fileMenu);
        fileMenu.add(newItem);
        fileMenu.add(openItem); 
        fileMenu.add(saveItem); 
        fileMenu.add(closeItem);
        setJMenuBar(menuBar);

        newItem.addActionListener(new NewMenuCommand(textArea));
        openItem.addActionListener(new OpenMenuCommand(textArea));
        closeItem.addActionListener(new QuitMenuCommand());
        saveItem.addActionListener(new SaveMenuCommand(textArea));
    }
}

//按钮的ActionListener新类

    public class ButtonCommand implements ActionListener {
    private JTextArea textArea;
    private String hText;
    int ind = 0;
    private String findString;


    public ButtonCommand (JTextArea ta){
        textArea = ta;
    }

    public void actionPerformed (ActionEvent e){
         hText = textArea.getText();
         findString=JOptionPane.showInputDialog(null,"Find   what","Find",JOptionPane.INFORMATION_MESSAGE);
         ind = hText.indexOf(findString,0);
         textArea.setCaretPosition(ind);
         textArea.setSelectionStart(ind);
         int a = ind+findString.length();
         textArea.setSelectionEnd(a);
    }
}
4

0 回答 0