Draw Text in Center of a Component in Java

Here is how you draw a String inside a Java Component based on it’s height and width:


String s;
int width, height;
Graphics g;

FontMetrics fm = getFontMetrics(ftDefault);
Rectangle2D textsize = fm.getStringBounds(s, g);
int xPos = (width - textsize.getWidth()) / 2;
int yPos = (height - textsize.getHeight()) / 2 + fm.getAscent();

g.drawString(s, xPos, yPos);
Advertisements

Hiding JTable Grid Lines

I’ve been using JTable on most of my projects and sometimes, there is a need to hide the grid lines. Grid lines are the visible horizontal and vertical lines in a table which clearly display the cells of each row and column. At first, I thought that settings the setShowGrid() property to false¬†will do the trick, but doesn’t really. One property that is needed to be adjusted as well is the setIntercellSpacing(). Here is what you need to set:

table.setShowGrid(false);
table.setIntercellSpacing(new Dimension(0, 0));

Adding Custom Fonts on your Swing Application

Just a while ago I was doing a Java Module, which, based from the mock-up screen, uses a Custom font. I realized that I needed to put this in because many times I might be using this solution, here is goes.


InputStream is = ThisClass.class.getResourceAsStream("/fonts/CaviarDreams.ttf");
Font myfont = Font.createFont(Font.TRUETYPE_FONT, is);

the font that you have loaded has no initial settings on it, so:


myfont = myfont.deriveFont(36.0f);
component.sentFont(myfont);

BTW, I put the TTF Font inside the resources file of my Java Project.

Returning records from previous months to current month

I was into this issue wherein I had to query for some records from the previous 3 months on MySQL. After some searching (I chose to search for existing answers first before using my brain to process such logic :D), here is what I was able to come up with:

select * from attendance where MONTH(attendance_date) >= MONTH(CURDATE()-INTERVAL 3 MONTH);

on the part were I have to state 3 as an interval, you can change it to how many months you would want to cover.

It’s 2014

2013 has passed, now its 2014, and what do you know, I wasn’t even able to post a single post here last year. It was such a busy year here at the office. Having been into several company projects (Software Development of course), I was able to improve my coding skills. Much cleaner, and well thought of, unlike during my first years in Java.

Anyways, I decided to keep this blog site alive. So from time to time, I will be posting things like, new things I have learned, some interesting topics I have seen on the web, other off topic discussions not relation to Linux or Software Development, and more.