Sunday, September 18, 2011

How to create custom JLabel using java graphics

The first step is to extend the JLabel. We may have our own constructor to initialize variables which will impact the custom jlabel to be created. CalendarDateLabel.java source code provided below is the custom JLabel which will display a round corner JLabel with border and with a dark background:

Source: test.CalendarDateLabel.java


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package test;

import java.awt.AlphaComposite;
import java.awt.event.MouseEvent;
import org.jps.ui.customcomponent.*;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.color.ColorSpace;
import java.awt.event.MouseListener;
import javax.swing.JComponent;
import javax.swing.JLabel;

/**
* Custom JLabel which displayes gray background with round corners.
* @author JoyP
*/
public class CalendarDateLabel extends JLabel implements MouseListener{

private String lblText = ""; //default text
private Color color_bg = Color.BLACK; //default bg color
private Color color_fg = Color.WHITE; //default text color
//private Color color_border = Color.BLUE; //default border color
private Color color_border = Color.LIGHT_GRAY; //default border color
private int arc = 3; //default to arc - 0 means sharp edges
private int x = 0; //x where label starts getting painted
private int y = 0; //y where label starts getting painted
private int w = 0; //width of the label
private int h = 0; //height of the label
private float border = 0f; //border of the label
private float alpha = 1.0f;
private boolean isMouseEntered = false;



public CalendarDateLabel(){
super();
super.setOpaque(false);

addMouseListener(this);


}

public CalendarDateLabel(String _text){
super();
super.setOpaque(false);

this.lblText = _text;

addMouseListener(this);


}


@Override
protected void paintComponent(Graphics g){
x = 3;
y = 3;
w = getWidth()-6;
h = getHeight()-6;
arc = 5;

Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setComposite(AlphaComposite.SrcOver.derive(alpha));

if(isMouseEntered){
//fill the label with color_bg
g2.setColor(color_bg);
g2.fillRoundRect(x, y, w, h, arc, arc);

//draw a round rectangle at the edge of the label with the arc value
g2.setStroke(new BasicStroke(border));
g2.setColor(color_border);
g2.drawRoundRect(x, y, w, h, arc, arc);
}




g2.setStroke(new BasicStroke(3f));
g2.setColor(color_fg);
g2.drawString(lblText, x+(Math.abs(w/4)), y+(Math.abs(h/2)));

g2.dispose();
}

@Override
public void mouseClicked(MouseEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}

@Override
public void mousePressed(MouseEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}

@Override
public void mouseReleased(MouseEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}

@Override
public void mouseEntered(MouseEvent e) {
isMouseEntered = true;


System.out.println("mouse entered");
color_bg = Color.GRAY;
border = 2f;

updateUI();


}

@Override
public void mouseExited(MouseEvent e) {
isMouseEntered = false;


System.out.println("mouse exited");
color_bg = Color.BLACK;

updateUI();


}


}




The above class may be instantiated in a JFrame as provided in source code below:

Source: test.TestFrame.java




/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/*
* TestFrame.java
*
* Created on Apr 27, 2010, 9:53:16 PM
*/

package test;



/**
* JFrame creating instances of custom JLabel
* @author JoyP
*/
public class TestFrame extends javax.swing.JFrame {

/** Creates new form TestFrame */
public TestFrame() {
initComponents();
}

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
//
private void initComponents() {

jPanel1 = new javax.swing.JPanel();
jLabel2 = new test.CalendarDateLabel("TESTING");
jLabel1 = new test.CalendarDateLabel("TESTING");
jLabel3 = new test.CalendarDateLabel("TESTING");

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(255, 255, 255));

jPanel1.setBackground(new java.awt.Color(89, 89, 89));

jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("1");

jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("2");

jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setText("3");

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(41, 41, 41)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(121, Short.MAX_VALUE))
);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(62, Short.MAX_VALUE))
);

pack();
}//


/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TestFrame().setVisible(true);
}
});
}

// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
// End of variables declaration

}





Running TestFrame.java will result in three custom JLabel which is highlighted on mouseover.

No comments: