Jun 30

By default menus added to a JMenuBar will be left aligned. Often we want to shift some item to the right (for example a Help menu is often displayed to the right).

To right align a JMenu you can add some ‘glue’ to push subsequently added menus to the right. The ‘glue’ component will take up any available space, effectively pushing subsequent items to the right.

JMenuBar menubar = new JMenuBar();

// These menus will be left aligned by default

menubar.add(new JMenu("File"));
menubar.add(new JMenu("Edit"));

// add some glue so subsequent menus are pushed to the right

menubar.add(Box.createHorizontalGlue());

// This Help button will be right aligned

menubar.add(new JMenu("Help"));

written by objects \\ tags: , , ,

Jun 11

Many developers use the toURL() method of the File class to convert a File to a URL. This method however does not handle correctly escaping characters that are illegal in URL’s (such as spaces) and has been deprecated.

To convert a File to a URL you should instead first use the toURI() method to convert the file path to a URI. The URI class has a toURL() method that can then be used to convert the URI to a URL.

File file = new File(path);
URI uri = file.toURI();
URL url = uri.toURL();

// or alternatively in one line

URL url = file.toURI().toURL();

written by objects \\ tags: , , ,

Jun 11

You can tell the parseInt() method what base number system is used by the String that is being parsed.


String hex = "01001101";
int n = Integer.parseInt(hex, 2);

written by objects \\ tags: , , , , ,