Making JLable in JTextPane Undeletable

时间:2016-02-12 19:54:22

标签: java swing jtextpane styleddocument

I currently have a JLabel embedded in a JTextPane using this:

import javax.swing.*;
import javax.swing.text.*;

public class MainFrame
{
    JFrame mainFrame = new JFrame("Main Frame");
    JTextPane textPane = new JTextPane();

    public MainFrame()
    {
        String[] components = {"Title", "\n"};
        String[] styles = {"LABEL_ALIGN", "LEFT_ALIGN"};

        StyledDocument sd = textPane.getStyledDocument();
        Style DEFAULT_STYLE = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);

        Style LEFT_STYLE = sd.addStyle("LEFT_ALIGN", DEFAULT_STYLE);
        StyleConstants.setAlignment(LEFT_STYLE, StyleConstants.ALIGN_LEFT);

        Style CENTER_STYLE = sd.addStyle("CENTER_ALIGN", DEFAULT_STYLE);
        StyleConstants.setAlignment(CENTER_STYLE, StyleConstants.ALIGN_CENTER);

        JLabel titleLbl = new JLabel("Title");
        Style LABEL_STYLE = sd.addStyle("LABEL_ALIGN", DEFAULT_STYLE);
        StyleConstants.setAlignment(LABEL_STYLE, StyleConstants.ALIGN_CENTER);
        StyleConstants.setComponent(LABEL_STYLE, titleLbl);

        for(int i = 0; i < components.length; i++)
        {
            try
            {
                sd.insertString(sd.getLength(), components[i], sd.getStyle(styles[i]));
                sd.setLogicalStyle(sd.getLength(), sd.getStyle(styles[i]));
            }
            catch(BadLocationException e)
            {
                e.printStackTrace();
            }
        }

        mainFrame.add(textPane);
        mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        mainFrame.setLocationRelativeTo(null);
        mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        mainFrame.pack();
        mainFrame.setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(MainFrame::new);
    }
}

How can I make the label un-deletable? Because whenever I hold backspace, the label ends up getting removed from the JTextPane

2 个答案:

答案 0 :(得分:5)

You might be able to use a <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:fab="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context=".UI.MainActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/appBarLayouy" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" app:layout_scrollFlags="scroll|enterAlways" /> <android.support.design.widget.TabLayout android:id="@+id/sliding_tabs" android:layout_width="match_parent" android:layout_height="@dimen/tabsHeight" style="@style/NavigationTab"/> </android.support.design.widget.AppBarLayout> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"/> <include layout="@layout/content_main"/> <com.getbase.floatingactionbutton.FloatingActionsMenu android:id="@+id/floatingActionMenu" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" fab:fab_addButtonColorNormal="@color/blood_orange" fab:fab_addButtonColorPressed="@color/dirtyWhite" fab:fab_addButtonPlusIconColor="@color/dirtyWhite" fab:fab_addButtonSize = "normal" fab:fab_labelStyle="@style/menu_labels_style" fab:fab_labelsPosition="left" app:layout_anchor="@id/viewpager" app:layout_anchorGravity="bottom|end"> <com.getbase.floatingactionbutton.FloatingActionButton android:id="@+id/createPlanBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" fab:fab_colorNormal="@color/blood_orange" fab:fab_title="Create a plan" fab:fab_size="normal" app:fab_icon="@drawable/ic_event_white_48dp" fab:fab_colorPressed="@color/dirtyWhite"/> <com.getbase.floatingactionbutton.FloatingActionButton android:id="@+id/changeStatusBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" fab:fab_colorNormal="@color/blood_orange" fab:fab_size="normal" app:fab_icon="@drawable/ic_textsms_white_48dp" fab:fab_title="Change status" fab:fab_colorPressed="@color/dirtyWhite"/> </com.getbase.floatingactionbutton.FloatingActionsMenu> </android.support.design.widget.CoordinatorLayout> to prevent the removal of the component at the beginning of the text pane. Check out: How to make part of a JTextField uneditable for an example of this approach. In this case the label represents a single character so the prefix length would be set to 1. Or maybe you can just use the prefix concept itself and don't even use the JLabel.

Otherwise, you might be able to create a custom NavigationFilter. Check out the section from the Swing tutorial on Implementing a DocumentFilter for the basics.

So you would need to track the offset off the location of the component. Then in the DocumentFilter method of the filter you would need to check if you are removing data in the range of your offset. If so you would ignore the remove.

Of course the offset can dynamically change if you add or remove text before the label so you would need to manage that as well.

Or you can check out the Protected Text Component which attempts to manage all of that for you.

答案 1 :(得分:1)

Why not just put your title label outside the text area? That seems more intuitive.

It looks like there's no real way to avoid this while still allowing the textarea to be editable. You could place the label above the text frame so that it occupies the same space, or above the text frame so that it behaves like a proper title.

Unfortunately, the nature of the textarea is that all of its subcomponents are editable or none of them are.