Make a TitledBorder title editable

自作多情 提交于 2019-12-24 08:39:38

问题


Is there a way to make the title in TitledBorder editable so the user can edit what the title is? Or if there's another border that may allow this, what is it?

Box.setBorder(new TitledBorder(editableString));

EDIT:

Here's a link to my more specific question of editing based on a double click: Make TitledBorder editable upon double click


回答1:


Basically, keep a reference to the titled border, change it when needed, then repaint the component with the border. As below: change the text in the text field then hit Enter to see the effect.

import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class EditableTitledBorder {

    private JComponent ui = null;
    private TitledBorder titledBorder;

    EditableTitledBorder() {
        initUI();
    }

    public void initUI() {
        if (ui!=null) return;

        ui = new JPanel(new BorderLayout(4,4));
        String initialTitle = "Dark Image";
        titledBorder = new TitledBorder(initialTitle);
        ui.setBorder(titledBorder);
        final JTextField titleField = new JTextField(initialTitle);
        ActionListener changeTitleListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                titledBorder.setTitle(titleField.getText());
                ui.repaint();
            }
        };
        titleField.addActionListener(changeTitleListener);
        ui.add(titleField, BorderLayout.PAGE_START);
        ui.add(new JLabel(new ImageIcon(
                new BufferedImage(200,40,BufferedImage.TYPE_INT_RGB))));
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {
                }
                EditableTitledBorder o = new EditableTitledBorder();

                JFrame f = new JFrame(o.getClass().getSimpleName());
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.setContentPane(o.getUI());
                f.pack();
                f.setMinimumSize(f.getSize());

                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}


来源:https://stackoverflow.com/questions/51404241/make-a-titledborder-title-editable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!