Getting the number of days in a month in Java

You can set the Calendar instance with the highest number possible for months. If the actual number of days in that month is smaller than that maximum, the Calendar instance will automatically change the month (so for example if you would say “the 40th of January 2000″, Calendar will change this to “the 9th of February 2000″). So roll back the Calendar by one day every time until the member month of calendar turns out to be the month you are looking for.

Main.java:

import java.util.*;
 
public class Main {
   public static void main(String args[]) throws Exception {
      Calendar calendar = Calendar.getInstance();
      calendar.set(2002, Calendar.FEBRUARY, calendar.getMaximum(Calendar.DAY_OF_MONTH));
 
      while (calendar.get(Calendar.MONTH) != Calendar.FEBRUARY) {
         calendar.add(Calendar.DAY_OF_MONTH, -1);
      }
 
      System.out.println("Number of days: " + calendar.get(Calendar.DAY_OF_MONTH));
   }
}

outputs:

Number of days: 28

Creating a java.util.logging.LogRecord

Main.java:

import java.util.logging.*;
import java.io.*;
 
public class Main
{
   public static void main(String argv[]){
      Logger logger = Logger.getLogger("main");
      logger.setUseParentHandlers(false);
      ConsoleHandler ch = new ConsoleHandler();
      ch.setLevel(Level.ALL);
      logger.addHandler(ch);
 
      ch.setFormatter(new XMLFormatter());

      LogRecord logRecord = new LogRecord(Level.SEVERE, "Something went seriously wrong");
      logRecord.setMillis(1000);
      logRecord.setParameters(new Object[] { "param1", "param2" });
      logRecord.setSequenceNumber(123456);
      logRecord.setSourceClassName(Main.class.getName());
      logRecord.setSourceMethodName("main");

      logger.log(logRecord); 
   }
}

outputs:

<? xml version="1.0" encoding="windows-1252" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
  <date>1969-12-31T16:00:01</date>
  <millis>1000</millis>
  <sequence>123456</sequence>
  <level>SEVERE</level>
  <class>Main</class>
  <method>main</method>
  <thread>10</thread>
  <message>Something went seriously wrong</message>
</record>

Listing all System properties in Java

import java.util.*;
 
public class Main
{
   public static void main(String[] args) {
      Properties props = System.getProperties();
      
      Enumeration enum = props.propertyNames();
      while (enum.hasMoreElements()) {
         String prop = (String) enum.nextElement();
         printInColumn(prop, 40);
         printInColumn(System.getProperty(prop), 39);
         System.out.println();
      }
   }
 
   public static void printInColumn(String s, int col) {
      if (s.length() > col-2) s = s.substring(0, col-2);
      System.out.print(s);
      for (int i=s.length(); i<col; ++i)
         System.out.print(" ");
   }
}

outputs:

java.specification.name                 Java Platform API Specification        
awt.toolkit                             sun.awt.windows.WToolkit               
java.version                            1.2.2                                  
java.awt.graphicsenv                    sun.awt.Win32GraphicsEnvironment       
user.timezone                           Europe/Paris                           
java.specification.version              1.2                                    
java.vm.vendor                          Sun Microsystems Inc.                  
user.home                               C:WINDOWS                             
java.vm.specification.version           1.0                                    
os.arch                                 x86                                    
java.awt.fonts                                                                 
java.vendor.url                         http://java.sun.com/                   
user.region                             US                                     
file.encoding.pkg                       sun.io                                 
java.home                               C:JDK1.2.2JRE                        
java.class.path                         ;c:java  
line.separator                          
                                     
java.ext.dirs                           C:JDK1.2.2JRElibext                
java.io.tmpdir                          c:windowsTEMP                       
os.name                                 Windows 95                             
java.vendor                             Sun Microsystems Inc.                  
java.awt.printerjob                     sun.awt.windows.WPrinterJob            
java.library.path                       C:JDK1.2.2BIN;.;C:WINDOWSSYSTEM;C  
java.vm.specification.vendor            Sun Microsystems Inc.                  
sun.io.unicode.encoding                 UnicodeLittle                          
file.encoding                           Cp1252                                 
java.specification.vendor               Sun Microsystems Inc.                  
user.language                           en                                     
user.name                               joris                                  
java.vendor.url.bug                     http://java.sun.com/cgi-bin/bugreport  
java.vm.name                            Classic VM                             
java.class.version                      46.0                                   
java.vm.specification.name              Java Virtual Machine Specification     
sun.boot.library.path                   C:JDK1.2.2JREbin                    
os.version                              4.10                                   
java.vm.version                         1.2.2                                  
java.vm.info                            build JDK-1.2.2_005, native threads,   
java.compiler                           symcjit                                
path.separator                          ;                                      
file.separator                                                                
user.dir                                C:My DocumentsVisual Studio Project  
sun.boot.class.path                     C:JDK1.2.2JRElibrt.jar;C:JDK1.2.  

Listing the files that are contained in a Zip file

Extremely simple! Create an instance of ZipFile and enumerate its ZipEntries:

import java.io.*;
import java.util.*;
import java.util.zip.*;
 
public class Main
{
   public static void main(String[] args) throws IOException 
   {
      if (args.length != 1) {
         System.out.println("Usage: java Main <file.zip>");
         System.exit(1);
      }
 
      listContents(args[0]);
   }
 
   public static void listContents(String zipfilename) throws IOException {
      ZipFile zip = new ZipFile(zipfilename);
 
      for (Enumeration e=zip.entries(); e.hasMoreElements(); ) {
         ZipEntry ze = (ZipEntry) e.nextElement();
         System.out.println(ze.getName());
      }
   }
}

Sample output of esustools.zip:

com/
com/esus/
com/esus/security/
com/esus/security/DES.java
com/esus/security/MD5.java
com/esus/security/MD5.class
com/esus/security/KeyUtils.java
com/esus/security/KeyUtils.class
com/esus/security/DES.class
com/esus/security/CryptException.java
com/esus/security/CryptException.class
...

Retrieving the links in an HTML document in Java

You can use the HTMLEditorKit that includes an HTML parser. Have it parse your HTML and then enumerate the href attribute of all the “A” tags:

import javax.swing.text.html.*;
import javax.swing.text.*;
import java.util.*;
import java.net.*;
import java.io.*;
     
public class Main
{ 
   public static void main(String[] args) throws Exception {
      Vector v = getLinks(new URL("http://www.google.com"));
 
      for (int i=0; i<v.size(); i++) {
         System.out.println(v.elementAt(i));
      }
 
      System.exit(0);
   }
 
   public static Vector getLinks(URL url) throws Exception {
      Vector v = new Vector();
 
      URLConnection conn = url.openConnection();
      Reader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      HTMLEditorKit editorKit = new HTMLEditorKit();
      Document doc = editorKit.createDefaultDocument();
 
      // The Document class does not yet handle charset's properly.
      doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
 
      try {
         editorKit.read(r, doc, 0);
 
         // loop through the HTML A tag elements 
         ElementIterator it = new ElementIterator(doc);
         Element elem;
         while ((elem = it.next()) != null) {
            SimpleAttributeSet s = (SimpleAttributeSet) elem.getAttributes().getAttribute(HTML.Tag.A);
            if (s != null) {
               v.addElement(s.getAttribute(HTML.Attribute.HREF));
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
 
      return v;
   }
}

Creating a Menu for a JFrame

This example creates a JFrame, and puts a raised menubar on it, and menu items on the menubar. It also applies acclerators and mnemonics to the menu items and assigns listeners.

MyFrame.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.border.*;
import javax.swing.KeyStroke;
import javax.swing.JOptionPane;
import java.awt.Component;
 
public class MyFrame extends JFrame {
 
   public static void main(String args[]) {
 
      MyFrame main = new MyFrame();
 
      // center frame on screen
      Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
      main.setBounds(d.width/2-100, d.height/2-75, 200, 150);
 
      main.pack();
      main.setSize(200, 150); //set frame size
           
      main.setVisible(true);     
   } 
 
   public MyFrame() {
      super("Menu Example");
 
      this.addWindowListener(new WindowEventHandler()); 
         
      Container container = this.getContentPane();
 
      JMenu filemenu = new JMenu("Document");
      filemenu.setMnemonic(KeyEvent.VK_D);
 
      JMenuBar bar = new JMenuBar();
      bar.setBorder(new BevelBorder(BevelBorder.RAISED));
      container.add(bar);
      setJMenuBar(bar);
 
      JMenuItem connect = new JMenuItem("Open");
      connect.addActionListener(new openListener());
      connect.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, 
                                         Event.CTRL_MASK, false));
      connect.setMnemonic('O');
 
      JMenuItem exit = new JMenuItem("Exit");
      exit.addActionListener(new exitListener());
      exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, 
                                         Event.CTRL_MASK, false));
      exit.setMnemonic('X');
 
      filemenu.add(connect);
      filemenu.add(exit);
      bar.add(filemenu);
   }
 
   class WindowEventHandler extends WindowAdapter {
      public void windowClosing(WindowEvent evt) {          
         System.exit(0);
      }
   }
 
   class exitListener implements ActionListener {
      public void actionPerformed(ActionEvent l){
         System.exit(0);
      } 
   } 
 
   class openListener implements ActionListener {
      JFrame f = new JFrame();
 
      public void actionPerformed(ActionEvent l){
         JOptionPane.showMessageDialog(f, "OPEN");
      }
   }
}

Force the scrollbars to be there even when they’re not needed

   int hPolicy = JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS;
   int vPolicy = JScrollPane.VERTICAL_SCROLLBAR_ALWAYS;
 
   JPanel drawSurface = new JPanel();
   JScrollPane editorField;

= = = = = = = = = = = = =
(in constructor….)

   editorField = new JScrollPane(drawSurface);
   editorField.setHorizontalScrollBarPolicy(hPolicy);
   editorField.setVerticalScrollBarPolicy(vPolicy);

= = = = = = = = = = = = = = = = = = = = =
in essence all you need to do is set the individual scroll
bar policies to the constants defined in JScrollPane.

Changing the color of the selected tab of a JTabbedPane


With UIManager.put, change the “TabbedPane.selected” property to the desired color as shown in following example.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame implements ActionListener {
   JTabbedPane tabbedPane;
   int ntabs = 0;
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
 
      UIManager.put("TabbedPane.selected", Color.red);
 
      tabbedPane = new JTabbedPane();
      createTab();
 
      getContentPane().add(BorderLayout.CENTER, tabbedPane);
      setJMenuBar(createMenuBar());
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      setTitle("JTabbedPane Selected Color Demonstration");
      setSize(new Dimension(400, 400));
   }
 
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();
 
      JMenu menu1 = new JMenu("JTabbedPane");
      JMenuItem menuItem1 = new JMenuItem("Create new tab");
      menuItem1.addActionListener(this);
      menu1.add(menuItem1);
      menuBar.add(menu1);
 
      return menuBar;
   }
 
   public void actionPerformed(ActionEvent e) {
      if (e.getActionCommand().equals("Create new tab")) {
         createTab();
      }
   }
  
   protected void createTab() {
      ntabs++;
      tabbedPane.addTab("Tab #" + ntabs, new JLabel("Tab #" + ntabs));
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Setting a background image for a JDesktop

A JDesktopPane extends is a JLayeredPane. This container adds the notion of depth, allowing components to overlap each other. You specify the depth with an integer value, where higher-valued components sit on top of lower-valued components. To create a background image, just place it at the lowest layer: eg. the MIN_VALUE of an integer object. All other components must be layed out on top of this one.
Here’s an example, look at the method setBackgroundImage().

import java.awt.image.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;

public class Main extends JFrame
{
   JDesktopPane desktop;
 
   public Main() {
      desktop = new JDesktopPane(); 
      setContentPane(desktop);
      setBackgroundImage();
      createInternalFrame();
      setSize(new Dimension(500, 300));
      setLocation(100, 100);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0); 
         }
      });
   }
 
   protected void setBackgroundImage() {
      try {
         ImageIcon icon = new ImageIcon(new URL("http://www.esus.com/images/mong.jpg"));
         JLabel label = new JLabel(icon);
         label.setBounds(0, 0, icon.getIconWidth(), icon.getIconHeight());
  
         desktop.add(label, new Integer(Integer.MIN_VALUE));
      } catch(MalformedURLException e) {
         System.out.println(e);
      }
   }
  
   protected void createInternalFrame() {
      JInternalFrame frame = new JInternalFrame("InternalFrame", 
         true,    // resizable
         true,    // closable
         true,    // maximizable
         true);   // iconifiable
      frame.setVisible(true); 
      desktop.add(frame);
      frame.setSize(200, 200);
      try {
         frame.setSelected(true);
      } catch (java.beans.PropertyVetoException e) {}
   }
 
   public static void main(String []args) throws Exception {
      Main main = new Main();
      main.show();      
   }
}