【问题标题】:How to open only a single find and replace dialog box using java swing?java - 如何使用java swing只打开一个查找和替换对话框?
【发布时间】:2016-12-23 18:00:19
【问题描述】:

我使用 Java AWT 和 Swing API 创建了一个记事本应用程序。我能够打开、保存和执行所有操作,我还创建了一个 Jdialog 以在我的记事本应用程序中显示查找和替换对话框。

我的问题是,当我点击编辑->查找时,我点击查找按钮多次得到对话框,如何只得到一次?

final JDialog frDialog = new JDialog();
frDialog.setLayout(new GridLayout(3,4));
//frDialog.setModal(true);
frDialog.setVisible(true);
frDialog.requestFocus();

我不想用setModal的方法,我是个新手,谁能给我推荐一个更好的方法来防止对话框重复?

提前致谢。

【问题讨论】:

  • 应该花一天时间编写代码。
  • Christopher,我猜你有一个误解,即你只需要重复使用一个常见的“查找和替换”对话框。没有。你必须自己做一个。如果您使用的是 Netbeans 平台或 Eclipse 平台等平台,则可能有一些预定义的内容。但我从未使用过这些,所以这只是一个怀疑。
  • @Christopher,请尝试改写您的问题以获得更好的答案,从而实现您的目标。我已经编辑了你的问题。看看有没有帮助。
  • 我已经在网上搜索了一天,但没有找到任何东西,请帮助我。 很不错的报价。
  • @Christopher,我用代码 sn-p 更新了我的答案。您仍然需要弄清楚查找和替换的逻辑。但我希望这可以帮助您入门。

标签: java swing awt


【解决方案1】:

您可以创建带有所需选项的模态JDialog 来捕获搜索和替换字符串。并且还为匹配大小写、正则表达式等选项提供复选框。为Find NextReplaceReplace AllCancel 添加JButton 按钮。为这些按钮编写适当的逻辑,最后从记事本的actionPerformed 方法中显示对话框。这应该为您提供一个很好的起点来完成您正在寻找的东西。

更新:

使用它来抢占先机:

import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Snippet {
    public static void main(String[] args) {
        JFrame notepadFrame = createFrame();
        JDialog frDialog = new JDialog(notepadFrame);

        frDialog.setLayout(new GridLayout(3,4));

        JTextField txtFind = new JTextField();
        JTextField txtReplace = new JTextField();
        JButton btnFind = new JButton("Find");
        JButton btnReplace = new JButton("Replace");
        JButton btnReplaceAll = new JButton("Replace All");
        frDialog.add(new JLabel("Find: "));
        frDialog.add(txtFind);
        frDialog.add(new JLabel(""));
        frDialog.add(btnFind);
        frDialog.add(new JLabel("Replace with: "));
        frDialog.add(txtReplace);
        frDialog.add(new JLabel(""));
        frDialog.add(btnReplace);
        frDialog.add(new JLabel(""));
        frDialog.add(new JLabel(""));
        frDialog.add(new JLabel(""));
        frDialog.add(btnReplaceAll);

        frDialog.pack();
        frDialog.setVisible(true);

        show(notepadFrame);

    }

    public static JFrame createFrame(){
        JFrame frame = new JFrame("Notepad Frame");
        frame.setSize(600,400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JTextArea());
        return frame;
    }

    public static void show(JFrame frame) {
        frame.setVisible(true);
    }
}

希望这会有所帮助!

【讨论】:

  • 有没有其他方法可以调用默认的查找对话框,比如默认打开/保存对话框到java..?
  • @Christopher 没有“默认查找对话框”。
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
  • 2011-12-24
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
相关资源
最近更新 更多