如何在文本字段中添加按钮?

use*_*162 2 java swing jbutton jtextfield

我正在使用swing组件在Java中创建一个文本字段。我想使搜索文本字段出现在Mozilla或其他浏览器中。

我在文本字段中添加了一个按钮。我已设定的边框布局JTextField。一切工作正常,但是只要在文本字段中写入大文本(达到文本字段的给定大小),它就会在按钮后面。就像大家都已经看到的那样,这不会在搜索栏中出现。文本不能在按钮后面,而按钮和文本之间必须有一定的间隙。

有谁知道这是怎么做到的吗?

And*_*son 5

也许从这样的事情开始:

在此处输入图片说明

闪烁的光标位于文本字段的最右侧。

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

class ButtonsInTextField {

    JPanel gui = new JPanel(new GridBagLayout());
    JTextField textField;

    ButtonsInTextField(int cols) {
        JPanel textFieldWithButtonsPanel = new JPanel(new FlowLayout(
                SwingConstants.LEADING, 5, 1));
        textField = new JTextField(cols);
        textFieldWithButtonsPanel.add(textField);

        addButtonToPanel(textFieldWithButtonsPanel, 8);
        addButtonToPanel(textFieldWithButtonsPanel, 16);
        addButtonToPanel(textFieldWithButtonsPanel, 24);

        // WARNING:  Not sensitive to PLAF change!
        textFieldWithButtonsPanel.setBackground(textField.getBackground());
        textFieldWithButtonsPanel.setBorder(textField.getBorder());
        textField.setBorder(null);
        // END WARNING:  

        gui.add(textFieldWithButtonsPanel);
    }

    private final void addButtonToPanel(JPanel panel, int height) {
        BufferedImage bi = new BufferedImage(
                // find the size of an icon from the system, 
                // this is just a guess
                24, height, BufferedImage.TYPE_INT_RGB);
        JButton b = new JButton(new ImageIcon(bi));
        b.setContentAreaFilled(false);
        //b.setBorderPainted(false);
        b.setMargin(new Insets(0,0,0,0));
        panel.add(b);
    }

    public final JComponent getGui() {
        return gui;
    }

    public final JTextField getField() {
        return textField;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                ButtonsInTextField bitf = new ButtonsInTextField(20);
                JOptionPane.showMessageDialog(null, bitf.getGui());
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency
        SwingUtilities.invokeLater(r);
    }
}
Run Code Online (Sandbox Code Playgroud)