使TitledBorder标题可编辑

时间:2018-07-18 14:11:12

标签: java swing titled-border

有没有一种方法可以使TitledBorder中的标题可编辑,以便用户可以编辑标题?或者,如果还有另一个边界可以允许这样做,那是什么?

Box.setBorder(new TitledBorder(editableString));

编辑:

以下是我更具体的基于双击的编辑问题的链接: Make TitledBorder editable upon double click

1 个答案:

答案 0 :(得分:1)

基本上,保留对标题边框的引用,在需要时进行更改,然后使用边框重新绘制组件。如下所示:更改文本字段中的文本,然后按 Enter 查看效果。

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);
    }
}