Showing posts with label Swing. Show all posts
Showing posts with label Swing. Show all posts

August 8, 2012

Right align tabs in JTabbedPane

Some useful tips for aligning tabs in JTabbedPane :-

Align tabs to right
Place tabs on right of the JTabbedPane


August 7, 2012

Java Swing UI Settings

To set global UI settings in Java Swing, use UIManager and set the properties as needed. All components have their respective keys and default values. For a complete list of properties, refer

These settings should be done before creating the JFrame where all these components are put into.

Example :
UIManager.put("Button.background", Color.RED);
UIManager.put("Button.font", new FontUIResource(new Font("Arial", Font.BOLD, 12)));

June 29, 2012

JFileChooser - Useful Tips

Set Starting Directory
JFileChooser fileSaver = new JFileChooser();
String cpath = "C:/MWork/Test1/script/";
File f1 = new File(cpath);

File Filter
FileNameExtensionFilter filter = new FileNameExtensionFilter("eXtensible Markup Language file (*.xml) ", "xml");
fileSaver .setFileFilter(filter);

Default File Save Name
jFileChooser.setSelectedFile(new File("untitled.xml"));

June 22, 2012

Get Frame of a Component

In order to find the frame that contains a component, it is necessary to walk up the component's parents until the frame is encountered. SwingUtilities.getRoot() is a convenience method that finds the frame.

This example implements an action that finds and hides the frame of the component that triggered the action. See also Creating a JButton Component.

// Create an action
Action action = new AbstractAction("Action Label") {
    // This method is called when the action is triggered
    public void actionPerformed(ActionEvent evt) {
        Component c = (Component)evt.getSource();

        // Get the frame
        Component frame = SwingUtilities.getRoot(c);

        // Hide the frame

May 25, 2012

JTextBox Select all on Click

Following code will select all the content from the text box at click on it, if the textbox content is "<comment>".

Use focus listener - JTextArea does not have ActionListener like JTextField

public static JScrollPane getCommentBox() {

    final JTextArea txtComment = new JTextArea();

    FocusListener fl = new FocusListener() {
       public void focusLost(FocusEvent arg0) {
          System.out.println("not typing....");

       public void focusGained(FocusEvent arg0) {
          if (txtComment.getText().equals(Constants.COMMENTS)) {

    JScrollPane jScrollPane1 = new JScrollPane();

    return jScrollPane1;

Fixed size text area with scroll

JTextArea txtArea = new JTextArea();
JScrollPane jScrollPane1 = new JScrollPane();