【问题标题】:Is it possible to limit in a JTextField the area where characters can be inserted?是否可以在 JTextField 中限制可以插入字符的区域?
【发布时间】:2022-10-21 23:02:06
【问题描述】:

我有一个 JTextField,里面有一个 JButton,位于东侧。目前,当插入的字符到达按钮时,重叠的文本部分会插入到它的下方。

这里有一个 sn-p 来重现问题

class TextFieldWithIconLauncher {

    public static void main(String[] args) {
        JTextField modelFileTField = new JTextField();
        modelFileTField.setLayout(new BorderLayout());
        JButton button = new JButton("click");
        button.addActionListener(listener -> System.err.println("clicked!"));
        modelFileTField.add(button, BorderLayout.EAST);

        JFrame frame = new JFrame();
        frame.setSize(200, 100);
        frame.add(modelFileTField);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setMinimumSize(new Dimension(200, 100));
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

相反,这些是真实情况的截图

我想避免文本与按钮重叠,而不限制用户可以插入的字符数。

PS:如果我在 JPanel 中添加 JTextField 和 JButton ,它就像一个魅力,但我有一些限制,不幸的是,这种方法目前不可行

【问题讨论】:

  • 我不明白:您认为您的文本字段内会有一个按钮?
  • 我在 JButton 中有一个 JTextField。看代码sn-p
  • 隐约记得我们(在 SwingX 中)使用了包含额外组件的自定义边框和/或自定义布局来正确放置所有内容.. 所以它可能不是完全微不足道的,忘记了肮脏的细节;)
  • 查看Component Border,它可以满足您的需求。我有一些限制,不幸的是,目前这种方法不可行- 有什么限制?为什么不可行?
  • @camickr 谢谢你的建议,我试试看!但是,我正在研究公司使用的 Swing 库,因此存在限制。显然这些可以改变,但......不是现在,这是一个版本的修复

标签: java swing jbutton jtextfield


【解决方案1】:

我解决了使用 FlatLaf 外观和感觉 (https://www.formdev.com/flatlaf/)。这样,在 JTextField 文本和图标上设置特定属性不再重叠。 具体来说,我做了:

class TextFieldWithIconLauncher {

    public static void main(String[] args) {
        JTextField textField = new JTextField();
        textField.setLayout(new BorderLayout());
        JButton button = new JButton("click");
        button.addActionListener(listener -> System.err.println("clicked!"));
        textField.add(button, BorderLayout.EAST);

        //Property to set
        textField.putClientProperty(FlatClientProperties.TEXT_FIELD_TRAILING_COMPONENT, button);

        JFrame frame = new JFrame();
        frame.setSize(200, 100);
        frame.add(modelFileTField);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setMinimumSize(new Dimension(200, 100));
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    • 2019-06-12
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多