Skip to main content

Java Swing: JEditotPane, JScrollPane, JSplitPane & JRootPane

Java JEditorPane

JEditorPane class is used to create a simple text editor window. This class has setContentType() and setText() methods.

setContentType("text/plain"): This method is used to set the content type to be plain text.

setText(text): This method is used to set the initial text content.

Nested Classes

Modifier and TypeClassDescription
protected classJEditorPane.AccessibleJEditorPaneThis class implements accessibility support for the JEditorPane class.
protected classJEditorPane.AccessibleJEditorPaneHTMLThis class provides support for AccessibleHypertext, and is used in instances where the EditorKit installed in this JEditorPane is an instance of HTMLEditorKit.
protected classJEditorPane.JEditorPaneAccessibleHypertextSupportWhat's returned by AccessibleJEditorPaneHTML.getAccessibleText

Fields

Modifier and TypeFieldDescription
static StringHONOR_DISPLAY_PROPERTIESKey for a client property used to indicate whether the default font and foreground color from the component are used if a font or foreground color is not specified in the styled text.
static StringW3C_LENGTH_UNITSKey for a client property used to indicate whether w3c compliant length units are used for html rendering.

Constructors

ConstructorDescription
JEditorPane()It creates a new JEditorPane.
JEditorPane(String url)It creates a JEditorPane based on a string containing a URL specification.
JEditorPane(String type, String text)It creates a JEditorPane that has been initialized to the given text.
JEditorPane(URL initialPage)It creates a JEditorPane based on a specified URL for input.

Useful Methods

Modifier and TypeMethodDescription
voidaddHyperlinkListener(HyperlinkListener listener)Adds a hyperlink listener for notification of any changes, for example when a link is selected and entered.
protected EditorKitcreateDefaultEditorKit()It creates the default editor kit (PlainEditorKit) for when the component is first created.
voidsetText(String t)It sets the text of this TextComponent to the specified content, which is expected to be in the format of the content type of this editor.
voidsetContentType(String type)It sets the type of content that this editor handles.
voidsetPage(URL page)It sets the current URL being displayed.
voidread(InputStream in, Object desc)This method initializes from a stream.
voidscrollToReference(String reference)It scrolls the view to the given reference location (that is, the value returned by the UL.getRef method for the URL being displayed).
voidsetText(String t)It sets the text of this TextComponent to the specified content, which is expected to be in the format of the content type of this editor.
StringgetText()It returns the text contained in this TextComponent in terms of the content type of this editor.
voidread(InputStream in, Object desc)This method initializes from a stream.

JEditorPane Example

  1. import javax.swing.JEditorPane;  
  2. import javax.swing.JFrame;  
  3.   
  4. public class JEditorPaneExample {  
  5.     JFrame myFrame = null;  
  6.   
  7.     public static void main(String[] a) {  
  8.         (new JEditorPaneExample()).test();  
  9.     }  
  10.   
  11.     private void test() {  
  12.         myFrame = new JFrame("JEditorPane Test");  
  13.         myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  14.         myFrame.setSize(400200);  
  15.         JEditorPane myPane = new JEditorPane();  
  16.         myPane.setContentType("text/plain");  
  17.         myPane.setText("Sleeping is necessary for a healthy body."  
  18.                 + " But sleeping in unnecessary times may spoil our health, wealth and studies."  
  19.                 + " Doctors advise that the sleeping at improper timings may lead for obesity during the students days.");  
  20.         myFrame.setContentPane(myPane);  
  21.         myFrame.setVisible(true);  
  22.     }  
  23. }  

Output:

Java JEditorpane

JEditorPane Example: using HTML

  1. import javax.swing.JEditorPane;    
  2. import javax.swing.JFrame;    
  3.     
  4. public class JEditorPaneExample {    
  5.     JFrame myFrame = null;    
  6.     
  7.     public static void main(String[] a) {    
  8.         (new JEditorPaneExample()).test();    
  9.     }    
  10.     
  11.     private void test() {    
  12.         myFrame = new JFrame("JEditorPane Test");    
  13.         myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
  14.         myFrame.setSize(400200);    
  15.         JEditorPane myPane = new JEditorPane();    
  16.         myPane.setContentType("text/html");    
  17.         myPane.setText("<h1>Sleeping</h1><p>Sleeping is necessary for a healthy body."    
  18.                 + " But sleeping in unnecessary times may spoil our health, wealth and studies."    
  19.                 + " Doctors advise that the sleeping at improper timings may lead for obesity during the students days.</p>");    
  20.         myFrame.setContentPane(myPane);    
  21.         myFrame.setVisible(true);    
  22.     }    
  23. }    

Output:

Java JEditorpane 2

Java JScrollPane

A JscrollPane is used to make scrollable view of a component. When screen size is limited, we use a scroll pane to display a large component or a component whose size can change dynamically.

Constructors

ConstructorPurpose
JScrollPane()It creates a scroll pane. The Component parameter, when present, sets the scroll pane's client. The two int parameters, when present, set the vertical and horizontal scroll bar policies (respectively).
JScrollPane(Component)
JScrollPane(int, int)
JScrollPane(Component, int, int)

Useful Methods

ModifierMethodDescription
voidsetColumnHeaderView(Component)It sets the column header for the scroll pane.
voidsetRowHeaderView(Component)It sets the row header for the scroll pane.
voidsetCorner(String, Component)It sets or gets the specified corner. The int parameter specifies which corner and must be one of the following constants defined in ScrollPaneConstants: UPPER_LEFT_CORNER, UPPER_RIGHT_CORNER, LOWER_LEFT_CORNER, LOWER_RIGHT_CORNER, LOWER_LEADING_CORNER, LOWER_TRAILING_CORNER, UPPER_LEADING_CORNER, UPPER_TRAILING_CORNER.
ComponentgetCorner(String)
voidsetViewportView(Component)Set the scroll pane's client.

JScrollPane Example

  1. import java.awt.FlowLayout;  
  2. import javax.swing.JFrame;  
  3. import javax.swing.JScrollPane;  
  4. import javax.swing.JtextArea;  
  5.   
  6. public class JScrollPaneExample {  
  7.     private static final long serialVersionUID = 1L;  
  8.   
  9.     private static void createAndShowGUI() {  
  10.   
  11.         // Create and set up the window.  
  12.         final JFrame frame = new JFrame("Scroll Pane Example");  
  13.   
  14.         // Display the window.  
  15.         frame.setSize(500500);  
  16.         frame.setVisible(true);  
  17.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  18.   
  19.         // set flow layout for the frame  
  20.         frame.getContentPane().setLayout(new FlowLayout());  
  21.   
  22.         JTextArea textArea = new JTextArea(2020);  
  23.         JScrollPane scrollableTextArea = new JScrollPane(textArea);  
  24.   
  25.         scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  
  26.         scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);  
  27.   
  28.         frame.getContentPane().add(scrollableTextArea);  
  29.     }  
  30.     public static void main(String[] args) {  
  31.   
  32.   
  33.         javax.swing.SwingUtilities.invokeLater(new Runnable() {  
  34.   
  35.             public void run() {  
  36.                 createAndShowGUI();  
  37.             }  
  38.         });  
  39.     }  
  40. }  

Output:

Java JScrollpane



Java JSplitPane

JSplitPane is used to divide two components. The two components are divided based on the look and feel implementation, and they can be resized by the user. If the minimum size of the two components is greater than the size of the split pane, the divider will not allow you to resize it.

The two components in a split pane can be aligned left to right using JSplitPane.HORIZONTAL_SPLIT, or top to bottom using JSplitPane.VERTICAL_SPLIT. When the user is resizing the components the minimum size of the components is used to determine the maximum/minimum position the components can be set to.

Nested Class

Modifier and TypeClassDescription
protected classJSplitPane.AccessibleJSplitPaneThis class implements accessibility support for the JsplitPane class.

Useful Fields

Modifier and TypeFieldDescription
static StringBOTTOMIt use to add a Component below the other Component.
static StringCONTINUOUS_LAYOUT_PROPERTYBound property name for continuousLayout.
static StringDIVIDERIt uses to add a Component that will represent the divider.
static intHORIZONTAL_SPLITHorizontal split indicates the Components are split along the x axis.
protected intlastDividerLocationPrevious location of the split pane.
protected ComponentleftComponentThe left or top component.
static intVERTICAL_SPLITVertical split indicates the Components are split along the y axis.
protected ComponentrightComponentThe right or bottom component.
protected intorientationHow the views are split.

Constructors

ConstructorDescription
JSplitPane()It creates a new JsplitPane configured to arrange the child components side-by-side horizontally, using two buttons for the components.
JSplitPane(int newOrientation)It creates a new JsplitPane configured with the specified orientation.
JSplitPane(int newOrientation, boolean newContinuousLayout)It creates a new JsplitPane with the specified orientation and redrawing style.
JSplitPane(int newOrientation, boolean newContinuousLayout, Component newLeftComponent, Component newRightComponent)It creates a new JsplitPane with the specified orientation and redrawing style, and with the specified components.
JSplitPane(int newOrientation, Component newLeftComponent, Component newRightComponent)It creates a new JsplitPane with the specified orientation and the specified components.

Useful Methods

Modifier and TypeMethodDescription
protected voidaddImpl(Component comp, Object constraints, int index)It cdds the specified component to this split pane.
AccessibleContextgetAccessibleContext()It gets the AccessibleContext associated with this JSplitPane.
intgetDividerLocation()It returns the last value passed to setDividerLocation.
intgetDividerSize()It returns the size of the divider.
ComponentgetBottomComponent()It returns the component below, or to the right of the divider.
ComponentgetRightComponent()It returns the component to the right (or below) the divider.
SplitPaneUIgetUI()It returns the SplitPaneUI that is providing the current look and feel.
booleanisContinuousLayout()It gets the continuousLayout property.
booleanisOneTouchExpandable()It gets the oneTouchExpandable property.
voidsetOrientation(int orientation)It gets the orientation, or how the splitter is divided.

JSplitPane Example

  1. import java.awt.FlowLayout;  
  2. import java.awt.Panel;  
  3. import javax.swing.JComboBox;  
  4. import javax.swing.JFrame;  
  5. import javax.swing.JSplitPane;  
  6. public class JSplitPaneExample {  
  7.     private static void createAndShow() {  
  8.         // Create and set up the window.  
  9.         final JFrame frame = new JFrame("JSplitPane Example");  
  10.         // Display the window.  
  11.         frame.setSize(300300);  
  12.         frame.setVisible(true);  
  13.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  14.         // set flow layout for the frame  
  15.         frame.getContentPane().setLayout(new FlowLayout());  
  16.         String[] option1 = { "A","B","C","D","E" };  
  17.         JComboBox box1 = new JComboBox(option1);  
  18.         String[] option2 = {"1","2","3","4","5"};  
  19.         JComboBox box2 = new JComboBox(option2);  
  20.         Panel panel1 = new Panel();  
  21.         panel1.add(box1);  
  22.         Panel panel2 = new Panel();  
  23.         panel2.add(box2);  
  24.         JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panel1, panel2);  
  25.         // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,  
  26.         // panel1, panel2);  
  27.         frame.getContentPane().add(splitPane);  
  28.     }  
  29.     public static void main(String[] args) {  
  30.         // Schedule a job for the event-dispatching thread:  
  31.         // creating and showing this application's GUI.  
  32.         javax.swing.SwingUtilities.invokeLater(new Runnable() {  
  33.             public void run() {  
  34.                 createAndShow();  
  35.             }  
  36.         });  
  37.     }  
  38. }  


Java JTextPane

JTextPane is a subclass of JEditorPane class. JTextPane is used for styled document with embedded images and components. It is text component that can be marked up with attributes that are represented graphically. JTextPane uses a DefaultStyledDocument as its default model.

Constructors

ConstructorDescription
JTextPane()It creates a new JTextPane.
JtextPane(StyledDocument doc)It creates a new JTextPane, with a specified document model.

Useful Methods

Modifier and TypeMethodDescription
StyleaddStyle(String nm, Style parent)It adds a new style into the logical style hierarchy.
AttributeSetgetCharacterAttributes()It fetches the character attributes in effect at the current location of the caret, or null.
StyledDocumentgetStyledDocument()It fetches the model associated with the editor.
voidsetDocument(Document doc)It associates the editor with a text document.
voidsetCharacterAttributes(AttributeSet attr, boolean replace)It applies the given attributes to character content.
voidremoveStyle(String nm)It removes a named non-null style previously added to the document.
voidsetEditorKit(EditorKit kit)It sets the currently installed kit for handling content.
voidsetStyledDocument(StyledDocument doc)It associates the editor with a text document.

JTextPane Example

  1. import java.awt.BorderLayout;  
  2. import java.awt.Color;  
  3. import java.awt.Container;  
  4. import javax.swing.JFrame;  
  5. import javax.swing.JScrollPane;  
  6. import javax.swing.JTextPane;  
  7. import javax.swing.text.BadLocationException;  
  8. import javax.swing.text.Document;  
  9. import javax.swing.text.SimpleAttributeSet;  
  10. import javax.swing.text.StyleConstants;  
  11. public class JTextPaneExample {  
  12.     public static void main(String args[]) throws BadLocationException {  
  13.         JFrame frame = new JFrame("JTextPane Example");  
  14.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  15.         Container cp = frame.getContentPane();  
  16.         JTextPane pane = new JTextPane();  
  17.         SimpleAttributeSet attributeSet = new SimpleAttributeSet();  
  18.         StyleConstants.setBold(attributeSet, true);  
  19.   
  20.         // Set the attributes before adding text  
  21.         pane.setCharacterAttributes(attributeSet, true);  
  22.         pane.setText("Welcome");  
  23.   
  24.         attributeSet = new SimpleAttributeSet();  
  25.         StyleConstants.setItalic(attributeSet, true);  
  26.         StyleConstants.setForeground(attributeSet, Color.red);  
  27.         StyleConstants.setBackground(attributeSet, Color.blue);  
  28.   
  29.         Document doc = pane.getStyledDocument();  
  30.         doc.insertString(doc.getLength(), "To Java ", attributeSet);  
  31.   
  32.         attributeSet = new SimpleAttributeSet();  
  33.         doc.insertString(doc.getLength(), "World", attributeSet);  
  34.   
  35.         JScrollPane scrollPane = new JScrollPane(pane);  
  36.         cp.add(scrollPane, BorderLayout.CENTER);  
  37.   
  38.         frame.setSize(400300);  
  39.         frame.setVisible(true);  
  40.       }  
  41. }  

Output

Java JTextpane


Java JRootPane

JRootPane is a lightweight container used behind the scenes by JFrame, JDialog, JWindow, JApplet, and JInternalFrame.

Nested Classes

Modifier and TypeClassDescription
protected classJRootPane.AccessibleJRootPaneThis class implements accessibility support for the JRootPane class.
protected classJRootPane.RootLayoutA custom layout manager that is responsible for the layout of layeredPane, glassPane, and menuBar.

Fields

Modifier and TypeFieldDescription
static intCOLOR_CHOOSER_DIALOGConstant used for the windowDecorationStyle property.
protected JButtoncontentPaneThe content pane.
protected ContainerdefaultButtonThe button that gets activated when the pane has the focus and a UI-specific action like pressing the Enter key occurs.
protected JMenuBarmenuBarThe menu bar.
protected ComponentglassPaneThe glass pane that overlays the menu bar and content pane, so it can intercept mouse movements and such.
static intERROR_DIALOGConstant used for the windowDecorationStyle property.

Constructor

ConstructorDescription
JRootPane()Creates a JRootPane, setting up its glassPane, layeredPane, and contentPane.

Useful Methods

Modifier and TypeMethodDescription
protected voidaddImpl(Component comp, Object constraints, int index)Overridden to enforce the position of the glass component as the zero child.
voidaddNotify()Notifies this component that it now has a parent component.
protected ContainercreateContentPane()It is called by the constructor methods to create the default contentPane.
protected ComponentcreateGlassPane()It called by the constructor methods to create the default glassPane.
AccessibleContextgetAccessibleContext()It gets the AccessibleContext associated with this JRootPane.
JButtongetDefaultButton()It returns the value of the defaultButton property.
voidsetContentPane(Container content)It sets the content pane -- the container that holds the components parented by the root pane.
voidsetDefaultButton(JButton defaultButton)It sets the defaultButton property, which determines the current default button for this JRootPane.
voidsetJMenuBar(JMenuBar menu)It adds or changes the menu bar used in the layered pane.

JRootPane Example

  1. import javax.swing.JButton;  
  2. import javax.swing.JFrame;  
  3. import javax.swing.JMenu;  
  4. import javax.swing.JMenuBar;  
  5. import javax.swing.JRootPane;  
  6.   
  7. public class JRootPaneExample {  
  8.      public static void main(String[] args) {  
  9.             JFrame f = new JFrame();  
  10.             f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  11.             JRootPane root = f.getRootPane();  
  12.   
  13.             // Create a menu bar  
  14.             JMenuBar bar = new JMenuBar();  
  15.             JMenu menu = new JMenu("File");  
  16.             bar.add(menu);  
  17.             menu.add("Open");  
  18.             menu.add("Close");  
  19.             root.setJMenuBar(bar);  
  20.   
  21.             // Add a button to the content pane  
  22.             root.getContentPane().add(new JButton("Press Me"));  
  23.   
  24.             // Display the UI  
  25.             f.pack();  
  26.             f.setVisible(true);  
  27.           }  
  28. }  

Output

Java JRootpane



Anurag Rana Educator CSE/IT

Comments

Popular posts from this blog

JAVA Scrollbar, MenuItem and Menu, PopupMenu

ava AWT Scrollbar The  object  of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a  GUI  component allows us to see invisible number of rows and columns. AWT Scrollbar class declaration public   class  Scrollbar  extends  Component  implements  Adjustable, Accessible   Java AWT Scrollbar Example import  java.awt.*;   class  ScrollbarExample{   ScrollbarExample(){               Frame f=  new  Frame( "Scrollbar Example" );               Scrollbar s= new  Scrollbar();               s.setBounds( 100 , 100 ,  50 , 100 );               f.add(s);               f.setSize( 400 , 400 );               f.setLayout( null );               f.setVisible( true );   }   public   static   void  main(String args[]){           new  ScrollbarExample();   }   }   Output: Java AWT Scrollbar Example with AdjustmentListener import  java.awt.*;   import  java.awt.event.*;   class  ScrollbarExample{        ScrollbarExample(){               Frame f=  new  Frame( "Scro

Difference between net platform and dot net framework...

Difference between net platform and dot net framework... .net platform supports programming languages that are .net compatible. It is the platform using which we can build and develop the applications. .net framework is the engine inside the .net platform which actually compiles and produces the executable code. .net framework contains CLR(Common Language Runtime) and FCL(Framework Class Library) using which it produces the platform independent codes. What is the .NET Framework? The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class librari

C++ this Pointer, static, struct and Enumeration

C++ this Pointer In C++ programming,  this  is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++. It can be used  to pass current object as a parameter to another method. It can be used  to refer current class instance variable. It can be used  to declare indexers. C++ this Pointer Example Let's see the example of this keyword in C++ that refers to the fields of current class. #include <iostream>    using   namespace  std;   class  Employee {       public :           int  id;  //data member (also instance variable)               string name;  //data member(also instance variable)            float  salary;          Employee( int  id, string name,  float  salary)             {                   this ->id = id;                  this ->name = name;                  this ->salary = salary;            }             void  display()             {                 cout<<id<< "  " <<name<&