center

An Android method to center text when using Canvas drawText

I’m not an expert on this subject just yet, but if you want the source code for an Android method to center text that you want to use with the drawText method of the Canvas class, I know that this code works in two places in my current Android app:

How to center elements in an Android LinearLayout (horizontally)

I was just working on centering some components in an Android LinearLayout and came upon this helpful advice:

android:gravity takes care of its children,
android:layout_gravity takes care of itself

So, in my case, where I wanted to center two buttons horizontally in a LinearLayout, I used android:gravity="center".

How to center a window/frame with Scala Swing alvin June 12, 2013 - 9:39pm

To center a window/frame in a Scala Swing application, add this line to your frame definition:

peer.setLocationRelativeTo(null)

Here’s what this looks like in the top method definition inside a SimpleSwingApplication:

How to center a Java JDialog

Java/Swing FAQ: How do I center a JDialog?

Answer: The answer here really depends on what you mean by "center". If you really want to center a JDialog on screen, you can use code like this:

// center a jdialog on screen
JDialog d = new JDialog();
d.setSize(400, 300);
d.setLocationRelativeTo(null);
d.setVisible(true);

By calling setLocationRelativeTo with null, the JDialog will be centered.

How to center a JFrame on screen

I'm often asked, "How do I center a JFrame on screen?", or, "Is there a method to center a JFrame?"

I always center my initial JFrame on screen using the setLocationRelativeTo method, and pass it a null reference. As the Javadoc for setLocationRelativeTo method states:

Java JFrame: How to create, center, and display a JFrame alvin June 7, 2009 - 1:46pm

Java JFrame FAQ: How do I properly create and display a JFrame? While you're at it, how do I center a JFrame?

In this Java tutorial I'll demonstrate how to create and display a JFrame Other than the comments in the source code, I'm going to keep the code as simple as possible, so I can demonstrate how this works.