Prevent a JFileChooser from being resizable

JFileChooser extends from JComponent, not from JDialog. When you call JFileChooser.showXXXXDialog, it will
create a JDialog and add JFileChooser to the content pane. You don’t have access to that instance to make it not-
resizable, but it’s not difficult to make a custom one.

Displaying a menu when right clicking on a cell

Try this:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   JTable table;
   TablePopup tablePopup;
 
   public Main() {
      super("Table example, Wines from Bordeaux");
 
      Object[][] tabledata = {
            { "Chateau Meyney, St. Estephe", 	   new Integer(1994), "$18.75"},
            { "Chateau Montrose, St. Estephe", 	   new Integer(1975), "$54.25" },
            { "Chateau Gloria, St. Julien", 	   new Integer(1993), "$22.99" },
            { "Chateau Beychevelle, St. Julien",   new Integer(1970), "$61.63" },
            { "Chateau La Tour de Mons, Margeaux", new Integer(1975), "$57.03" },
            { "Chateau Brane-Cantenac, Margeaux",  new Integer(1978), "$49.92" },
      };
 
      String columnheaders[] = { "Wine", "Vintage", "Price" };
 
      table = new JTable(tabledata, columnheaders);
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
      JScrollPane scrollPane = new JScrollPane(table); 
      tablePopup = new TablePopup(table);
 
      table.addMouseListener(new MouseAdapter() {
            public void mouseReleased (MouseEvent e) {
                if (e.isPopupTrigger()) {
                   tablePopup.show (e.getComponent(), e.getX(), e.getY());
                }
            }
      });
  
      getContentPane().add(scrollPane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      pack();
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
 
   class TablePopup extends JPopupMenu {
      public TablePopup(JTable table) {
         JMenuItem itemDelete = new JMenuItem("Delete row");
         JMenuItem itemAdd = new JMenuItem("Add row");
         itemDelete.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
               System.out.println("Delete row");
            }
         });
         itemAdd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
               System.out.println("Add row");
            }
         });
 
         add(itemDelete);
         add(new JSeparator());
         add(itemAdd);
      }
   }
}

Setting the background color of a JTable inside a JScrollPane

Try the following (JDK1.3+):

   scrollPane.getViewport().setBackground(table.getBackground());

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   public Main() {
      super("Table example, Wines from Bordeaux");
 
      Object[][] tabledata = {
            { "Chateau Meyney, St. Estephe", 	   new Integer(1994), "$18.75"},
            { "Chateau Montrose, St. Estephe", 	   new Integer(1975), "$54.25" },
            { "Chateau Gloria, St. Julien", 	   new Integer(1993), "$22.99" },
            { "Chateau Beychevelle, St. Julien",   new Integer(1970), "$61.63" },
            { "Chateau La Tour de Mons, Margeaux", new Integer(1975), "$57.03" },
            { "Chateau Brane-Cantenac, Margeaux",  new Integer(1978), "$49.92" },
      };
 
      String columnheaders[] = { "Wine", "Vintage", "Price" };
 
      JTable table = new JTable(tabledata, columnheaders);
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
 
      table.setBackground(Color.red);
  
      JScrollPane scrollPane = new JScrollPane(table);
      scrollPane.getViewport().setBackground(table.getBackground());
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.CENTER, scrollPane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(550, 300);
      main.setVisible(true);
   }
}

Changing the font size of the column headers in a JTable

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   public Main() {
      super("Table example, Wines from Bordeaux");
 
      Object[][] tabledata = {
            { "Chateau Meyney, St. Estephe", 	   new Integer(1994), "$18.75"},
            { "Chateau Montrose, St. Estephe", 	   new Integer(1975), "$54.25" },
            { "Chateau Gloria, St. Julien", 	   new Integer(1993), "$22.99" },
            { "Chateau Beychevelle, St. Julien",   new Integer(1970), "$61.63" },
            { "Chateau La Tour de Mons, Margeaux", new Integer(1975), "$57.03" },
            { "Chateau Brane-Cantenac, Margeaux",  new Integer(1978), "$49.92" },
      };
 
      String columnheaders[] = { "Wine", "Vintage", "Price" };
 
      JTable table = new JTable(tabledata, columnheaders);
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
      JScrollPane scrollPane = new JScrollPane(table);
 
      // set font for headers
      Font f = new Font("Arial", Font.BOLD, 25);
      JTableHeader header = table.getTableHeader();
      header.setFont(f);

      getContentPane().add(scrollPane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      pack();
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Get started with a JTree

These sample codes will just teach you how to create a simple JTree, without worrying about how the tree is displayed. For detailed information about this, look at the other examples in this category.

DefaultMutableTreeNode

You create the simpliest JTree by constructing the hierarchy using the class DefaultMutableTreeNode. With its add method, children (of type DefaultMutableTreeNode) can be added. A child can have children as well.

Then, pass the root element to a JTree instance.

This simple example shows you how to.

Main.java:

import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
 
public class Main extends JFrame
{
   public Main() {
      DefaultMutableTreeNode root = createNodes();
      JTree tree = new JTree(root);
 
      getContentPane().add(new JScrollPane(tree));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static DefaultMutableTreeNode createNodes() {
      DefaultMutableTreeNode root = new DefaultMutableTreeNode("Java");
      
      DefaultMutableTreeNode j2se = new DefaultMutableTreeNode("J2SE");
      DefaultMutableTreeNode j2ee = new DefaultMutableTreeNode("J2EE");
      DefaultMutableTreeNode j2me = new DefaultMutableTreeNode("J2ME");
 
      j2se.add(new DefaultMutableTreeNode("http://java.sun.com/j2se/"));
      j2ee.add(new DefaultMutableTreeNode("http://java.sun.com/j2ee/"));
      j2me.add(new DefaultMutableTreeNode("http://java.sun.com/j2me/"));
 
      root.add(j2se);
      root.add(j2ee);
      root.add(j2me);
 
      return root;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Extending TreeModel

But if you already have an existing tree-based model, you want to use it directly (and not create a mirror that is a set of DefaultMutableTreeNodes). This way, your view stays in sync with your existing model.

You can reuse your tree-based datastructure by creating your own class that implements TreeModel as shown in the following example. The custom datastructure Category contains the data and a CategoryTreeModel passes it on to the view.

Category.java:

import java.util.*;
 
public class Category
{
   private String name;
   private Vector subCategories = new Vector();
   private Vector links = new Vector();
 
   public Category(String name) {
      this.name = name;
   }
 
   public void addSubCategory(Category category) {
      subCategories.addElement(category);
   }
 
   public void addLink(String link) {
      links.addElement(link);
   }
 
   public Vector getSubCategories() {
      return subCategories;
   }
 
   public Vector getLinks() {
      return links;
   } 
 
   public String toString() {
      return name;
   }
}

CategoryTree.java:

import javax.swing.*;
import javax.swing.tree.*;
 
public class CategoryTree extends JTree {
    CategoryTreeModel model;
 
    public CategoryTree(Category category) {
        super(new CategoryTreeModel(category));
    }
}

CategoryTreeModel.java:

import javax.swing.event.*;
import javax.swing.tree.*;
import java.util.*;
 
public class CategoryTreeModel implements TreeModel {
   private Category rootCategory;
   private Vector listeners = new Vector();
 
   public CategoryTreeModel(Category rootCategory) {
      this.rootCategory = rootCategory;
   }
 
   public Object getChild(Object parent, int index) {
      Category category = (Category) parent;
  
      // if the index falls in the subcategories vector
      if (index < category.getSubCategories().size()) {
         return category.getSubCategories().elementAt(index);
      }
 
      // else if the index falls in the links vector
      index -= category.getSubCategories().size();
      return category.getLinks().elementAt(index);
   }
 
   public int getChildCount(Object parent) {
      Category category = (Category) parent;
 
      return category.getSubCategories().size() +
             category.getLinks().size();
   }
 
   public int getIndexOfChild(Object parent, Object child) {
      Category category = (Category) parent;
 
      if (child instanceof Category) {
         return category.getSubCategories().indexOf(child);
      }
      else {
         return category.getLinks().indexOf(child);
      }
   }
 
   public Object getRoot() {
      return rootCategory;
   }
 
   public boolean isLeaf(Object node) {
      return node instanceof String;
   }
 
   public void addTreeModelListener(TreeModelListener l) {
      listeners.addElement(l);
   } 
 
   public void removeTreeModelListener(TreeModelListener l) {
      listeners.removeElement(l);
   }
 
   public void valueForPathChanged(TreePath path, Object newValue) {
      System.out.println("Value for path changed, " + newValue);
   }  
}

Main.java:

import java.net.*;
import java.awt.event.*;
  
public class Main extends JFrame
{
   public Main() {
      Category category = createCategory();
 
      CategoryTree tree = new CategoryTree(category);
  
      getContentPane().add(new JScrollPane(tree));
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static Category createCategory() {
      Category category = new Category("Java");
 
      Category j2se = new Category("j2se");
      j2se.addLink("http://java.sun.com/j2se/");
 
      Category j2ee = new Category("j2ee");
      j2ee.addLink("http://java.sun.com/j2ee/");
 
      Category j2me = new Category("j2me");
      j2me.addLink("http://java.sun.com/j2me/");
 
      category.addSubCategory(j2se);
      category.addSubCategory(j2ee);
      category.addSubCategory(j2me);
 
      return category;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Changing the default look and feel for all my swing apps

You could set the Look And Feel by invoking UIManager.setLookAndFeel before any components are created, but that would set the Look And Feel for only that application.

If you want the default Look And Feel to be changed for all applications, create the file swing.properties (if it doesn’t exist) in the javaHomeDirectorylib directory and in which you specify the default l&f:
c:jdk1.2.2jrelibswing.properties:

# Swing properties

swing.defaultlaf=com.sun.java.swing.plaf.motif.MotifLookAndFeel

Changing the colors of a JOptionPane

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public static void main(String []args) {
      UIManager.put("OptionPane.background", Color.blue);
      UIManager.put("Panel.background", Color.blue);
      UIManager.put("Button.background", Color.white);
 
      String value = JOptionPane.showInputDialog("Enter your name");
      System.out.println("Hello " + value); 
 
      // exit awt thread
      System.exit(1);
   }
}

Applying CSS to an HTML rendered JLabel

You can set a StyleSheet on an HTMLEditorKit. It is shared by all HTMLEditorKit instances.

This example shows you how to set the margins, colors and size of any h1 used to render HTML in your Swing components.

Main.java:

import javax.swing.text.html.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
   
public class Main extends JFrame {
   public Main(StyleSheet s) {
      getContentPane().setLayout(new FlowLayout());
  
      HTMLEditorKit kit = new HTMLEditorKit();
      kit.setStyleSheet(s);
 
      final JLabel label = new JLabel("<html><h1>Socrates</h1></html>");
      getContentPane().add(label);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(300, 300);
   }
 
   public static StyleSheet loadStyleSheet(InputStream is) throws IOException
   {
      StyleSheet s = new StyleSheet();
      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      s.loadRules(br, null);
      br.close();
  
      return s;
   }
  
   public static void main(String[] args) throws Exception {
      StyleSheet s = loadStyleSheet(new FileInputStream("default.css"));
 
      (new Main(s)).show();
   }
}

default.css:

h1 {
   font-size:	24pt;
   font-weight:	bold;
   color:	red;
   margin-top:  10;
   margin-bottom:	10
}

Showing a JFrame without taking away the focus from the current window

You will have to use JNI. The following is an example on how to do this. The JFrame contains one button. If you click it, it will be iconified for 2 seconds and restored again, but without taking away the focus from the window that currently has the focus.

I used JDK1.3.1 and cygwin to create the DLL.

1. Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.util.*; 
 
import sun.awt.windows.*;
import sun.awt.*;
 
public class Main extends JFrame implements ActionListener
{
   public static native void WindowsShowNoActivate(int hwnd);
 
   static {
      System.loadLibrary("windowNoActivate");
   }
 
   public Main()
   {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      JButton iconButton = new JButton("Iconify this Frame");
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      getContentPane().add(iconButton);
      iconButton.addActionListener(this);
   }
 
   public void actionPerformed(ActionEvent ae) {     
      this.setState(Frame.ICONIFIED);  
      try {
         Thread.sleep(2000);
      }
      catch(Exception e) { }
 
      showWindowNoActivate();
      //this.setState(Frame.NORMAL);  
      //this.toBack();
   }
 
   public int getHwnd() {
      DrawingSurfaceInfo w = (DrawingSurfaceInfo) 
        ((DrawingSurface) getPeer()).getDrawingSurfaceInfo();
      w.lock();
      WDrawingSurfaceInfo win32 = (WDrawingSurfaceInfo) w;
      int hwnd = win32.getHWnd();
      w.unlock();
     
      return hwnd;
   }
 
   public void showWindowNoActivate() {
     WindowsShowNoActivate(this.getHwnd());
   }
 
   public static void main(String args[])
   {
      Main main = new Main();
      main.setSize(300, 150);
      main.setVisible(true);
   }
}

2. Compile and run javah:

c:\> javac Main.java
c:\> javah Main

3. Create windowNoActivate.c:

#include "jni.h"
#include "Main.h"
#include <stdio.h>
#include <windows.h>

JNIEXPORT void JNICALL Java_Main_WindowsShowNoActivate(JNIEnv *env, jclass obj,
jint hwnd)
{
   SetWindowPos((HWND) hwnd, HWND_TOPMOST, 0,0,0,0, SWP_NOMOVE|SWP_NOSIZE);
   ShowWindow((HWND) hwnd, SW_SHOWNOACTIVATE);
}

4. I used Cygwin to create the DLL. There is a change that needs to be made to JDK/include/win32/jni_md.h. Add the following line:

typedef long long __int64;

5. Compile windowNoActivate.c:

$ gcc -L -DDBG -shared windowNoActivate.c -mno-cygwin 
      -I/usr/include -Ic:/jdk1.3.1/include 
      -Ic:/jdk1.3.1/include/win32 -Wl,--add-stdcall-alias -o windowNoActivate.dll

6. Put the DLL in the same directory as where your run Main from or in your path, and run it.

 

Drawing a line in Swing

Use the method drawLine that accepts the line end coordinates (x1, y1) and (x2, y2).

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
   }
 
   public void paint(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
  
      g2d.drawLine(10, 50, getSize().width-20, 15);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(100, 100);
      main.setVisible(true);
   }
}