Different button shapes in swing

Make a class that extends JButton and in its constructor write following [Following code is common for all shapes]:

super(label);
Dimension size = getPreferredSize();
size.width = size.height = Math.max(size.width, size.height);
setPreferredSize(size);
setContentAreaFilled(false);
  • Round [Circular] buttons:

Circular Button

protected void paintComponent(Graphics g) {
     if (getModel().isArmed()) {
           g.setColor(Color.lightGray);
     } else {
          g.setColor(getBackground());
     }
     g.fillOval(0, 0, getSize().width-1, getSize().height-1);
     super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
     g.setColor(getForeground());
     g.drawOval(0, 0, getSize().width-1, getSize().height-1);
}
Shape shape;
public boolean contains(int x, int y) {
     if (shape == null || !shape.getBounds().equals(getBounds())) {
          shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
     }
     return shape.contains(x, y);
}
  • Triangle buttons:

Triangle button

protected void paintComponent(Graphics g) {
     if (getModel().isArmed()) {
          g.setColor(Color.lightGray);
     } else {
          g.setColor(getBackground());
     }
     int xPoints[] = {getSize().width/2, 0, getSize().width};
     int yPoints[] = {0, getSize().height, getSize().height};
     g.fillPolygon(x3Points, y3Points, xPoints.length);
     super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
     g.setColor(getForeground());
     int xPoints[] = {getSize().width/2, 0, getSize().width};
     int yPoints[] = {0, getSize().height, getSize().height};
     g.drawPolygon(xPoints, yPoints, xPoints.length);
}
Polygon polygon;
public boolean contains(int x, int y) {
     if (polygon == null || !polygon.getBounds().equals(getBounds())) {
          int xPoints[] = {getSize().width/2, 0, getSize().width};
          int yPoints[] = {0, getSize().height, getSize().height};
          polygon = new Polygon(xPoints,yPoints, xPoints.length);
     }
     return polygon.contains(x, y);
}
  • Oval buttons:

Oval button

protected void paintComponent(Graphics g) {
     if (getModel().isArmed()) {
          g.setColor(Color.lightGray);
     } else {
          g.setColor(getBackground());
     }
     g.fillOval(0, getHeight()/8, getWidth(), getHeight()-(getHeight()/4));
     super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
     g.setColor(getForeground());
     g.drawOval(0, getHeight()/8, getWidth(), getHeight()-(getHeight()/4));
}
Shape shape;
public boolean contains(int x, int y) {
     if (shape == null || !shape.getBounds().equals(getBounds())) {
          shape = new Ellipse2D.Float(0, getHeight()/8, getWidth(), getHeight()-getHeight()/4));
     }
     return shape.contains(x, y);
}
  • RoundRect buttons

RoundRect Button

protected void paintComponent(Graphics g) {
     if (getModel().isArmed()) {
          g.setColor(Color.lightGray);
     } else {
          g.setColor(getBackground());
     }
     g.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15);
     super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
     g.setColor(getForeground());
     g.drawRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15);
}
Shape shape;
public boolean contains(int x, int y) {
     if (shape == null || !shape.getBounds().equals(getBounds())) {
          shape = new RoundRectangle2D.Float(0, 0, getWidth()-1, getHeight()-1, 15, 15);
     }
     return shape.contains(x, y);
}
  • Star buttons:

Star button

public static Shape makeStarDesign(int arms, Point center, double r_out, double r_in) {
     double angle = Math.PI / arms;
     GeneralPath path = new GeneralPath();
     for (int i = 0; i < 2 * arms; i++) {
          double r = (i & 1) == 0 ? r_out : r_in;
          Point2D.Double p = new Point2D.Double(center.x + Math.cos(i * angle) * r, center.y + Math.sin(i * angle) * r);
          if (i == 0) path.moveTo(p.getX(), p.getY());
          else path.lineTo(p.getX(), p.getY());
     }
     path.closePath();
     return path;
}
protected void paintComponent(Graphics g) {
     if (getModel().isArmed()) {
          g.setColor(Color.lightGray);
     } else {
          g.setColor(getBackground());
     }
     Graphics2D graphics2d = (Graphics2D) g;
     graphics2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
     graphics2d.fill(makeStarDesign(5, new Point(50,50), 50, 30));
     super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
     g.setColor(getForeground());
     Graphics2D graphics2d = (Graphics2D) g;
     graphics2d.draw(makeStarDesign(5, new Point(50,50), 50, 30));
}
Shape shape;
public boolean contains(int x, int y) {
     if (shape == null || !shape.getBounds().equals(getBounds())) {
          shape = new Area(makeStarDesign(5, new Point(50,50), 50, 30));
     }
     return shape.contains(x, y);
}

More star buttons

Just change the first argument of makeStarDesign to number of arrows you want in star and it will try to draw it for you. 🙂

  • Play buttons:

Play button

      protected void paintComponent(Graphics g) {
		if (getModel().isArmed()) {
			g.setColor(Color.lightGray);
		} else {
			g.setColor(getBackground());
		}
		int xPoints[] = {0, 0, getWidth()};
		int yPoints[] = {0, getHeight(), getHeight()/2};
		g.fillPolygon(xPoints, yPoints, xPoints.length);
		super.paintComponent(g);
	}

	protected void paintBorder(Graphics g) {
		g.setColor(getForeground());
		int xPoints[] = {0, 0, getWidth()};
		int yPoints[] = {0, getHeight(), getHeight()/2};
		g.drawPolygon(xPoints, yPoints, xPoints.length);
	}

	Polygon polygon;
	public boolean contains(int x, int y) {
		if (polygon == null ||
				!polygon.getBounds().equals(getBounds())) {
			int xPoints[] = {0, 0, getWidth()};
			int yPoints[] = {0, getHeight(), getHeight()/2};
			polygon = new Polygon(xPoints,yPoints,xPoints.length);
		}
		return polygon.contains(x, y);
	}
  • Pentagon buttons:

Pentagon button

	int n=5;
	int x[]= new int[n];
	int y[]= new int[n];
	double angle = 2*Math.PI/n;
	protected void paintComponent(Graphics g) {
		if (getModel().isArmed()) {
			g.setColor(Color.lightGray);
		} else {
			g.setColor(getBackground());
		}
		int x0 = getSize().width/2;
		int y0 = getSize().height/2;
		for(int i=0; i<n; i++) {
			double v = i*angle;
			x[i] = x0 + (int)Math.round((getWidth()/2)*Math.cos(v));
			y[i] = y0 + (int)Math.round((getHeight()/2)*Math.sin(v));
		}
		g.fillPolygon(x, y, n);
		super.paintComponent(g);
	}

	protected void paintBorder(Graphics g) {
		g.setColor(getForeground());
		int x0 = getSize().width/2;
		int y0 = getSize().height/2;
		for(int i=0; i<n; i++) {
			double v = i*angle;
			x[i] = x0 + (int)Math.round((getWidth()/2)*Math.cos(v));
			y[i] = y0 + (int)Math.round((getHeight()/2)*Math.sin(v));
		}
		g.drawPolygon(x, y, n);
	}

	Polygon polygon;
	public boolean contains(int x1, int y1) {
		if (polygon == null ||
				!polygon.getBounds().equals(getBounds())) {
			int x0 = getSize().width/2;
			int y0 = getSize().height/2;
			for(int i=0; i<n; i++) {
				double v = i*angle;
				x[i] = x0 + (int)Math.round((getWidth()/2)*Math.cos(v));
				y[i] = y0 + (int)Math.round((getHeight()/2)*Math.sin(v));
			}
			polygon = new Polygon(x,y,n);
		}
		return polygon.contains(x1, y1);
	}
  • Diamond button:

Diamond button

Just change value of n in above code to 4.
  • Hexagon button:

Just change value of n in above code to 6.
By changing value of n you will get different shapes like follow:
Different pentagon shapes
  • More buttons:

You just have to change the code for shape everything else is same. So try it yourself…. 😉
Advertisements

Lightbox Jar

LightBox.jar
--- Jar that helps you providing light box like effect in your desktop 
 application built in swing.

 You may have seen light box effects on a website but very rarely have seen light box effect in a desktop application specifically in applications that are built in java swing.  This jar helps you put light box like effect into your swing application. So now you can also give same light box effect as on your website to your desktop application made in swing.

Light box effect

Light box effect

It’s very simple and easy to use this jar. You just have to create a instance of LightBox class and then call createLightBoxEffect() method on it with desired parameters and have a light box effect in your frame with a JPanel as popup.


This jar contains following 4 classes:

LightBox.java

  • Main class that helps in providing light box like effect using JFrame and JPanel.

LightBoxUtil.java

  • Light box utility class that contains utility methods like giving buzz effect to frame, blinking frame on taskbar, making beep sound, etc.

LightBoxMouseListener.java

  • If light box is modal then this listener will be added to light box so that all mouse clicks and other mouse events comes in this class and not get passed to underlying components. This is the simplest way I thought about making light box effect modal.

LightBoxException.java

  • Exception class for Light box effect jar.

Following is the description of constructor and methods of the class used to provide light box effect in this jar:

Constructors:

public LightBox()

Creates new LightBox instance. By default the lightbox effect is modal.


public LightBox(boolean modal)

Create new LightBox instance. If modal then all components under light box effect will be not able to generate any event until light box panel is closed.

Parameters:

          modal – Whether to make light box effect modal or not.


 Methods:

public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel)

To give a light box effect.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 int panelLocX,
                                 int panelLocY)

To give a light box effect and show pop up panel on specified location.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          panelLocX – X value of location of panel.

          panelLocY – Y value of location of panel.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 boolean blink,
                                 boolean makeSound,
                                 boolean buzzFrame)

To give a light box effect with blinking of window on task bar, plays a beep sound and gives buzz effect to frame.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          blink – Whether to blink frame on taskbar or not.

          makeSound – Whether to make beep sound or not.

          buzzFrame – Whether to give buzz effect to frame or not.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 int panelLocX,
                                 int panelLocY,
                                 boolean blink,
                                 boolean makeSound,
                                 boolean buzzFrame)

To give a light box effect with blinking of window on task bar, plays a beep sound and gives buzz effect to frame. Also shows pop up panel on specified location.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          panelLocX – X value of location of panel.

          panelLocY – Y value of location of panel.

          blink – Whether to blink frame on task bar or not.

          makeSound – Whether to make beep sound or not.

          buzzFrame – Whether to give buzz effect to frame or not.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 int panelLocX,
                                 int panelLocY,
                                 java.awt.Dimension size)
                          throws LightBoxException

To give light box effect with specified size of light box shade panel and pop up panel’s location.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          panelLocX – X value of location of panel.

          panelLocY – Y value of location of panel.

          size – Size of the light box shade panel.

Throws:

           LightBoxException – If given size of shade panel is not proper then this exception will be raised.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 java.awt.Dimension size)
                          throws LightBoxException

To give light box effect with specified size of light box shade panel.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          size – Size of the light box shade panel.

Throws:

           LightBoxException – If given size of shade panel is not proper then this exception will be raised.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 int panelLocX,
                                 int panelLocY,
                                 boolean blink,
                                 boolean makeSound,
                                 boolean buzzFrame,
                                 java.awt.Dimension size)
                          throws LightBoxException

 To give light box effect with specified size of light box shade panel with additional property flags like playing a beep sound, buzz frame, blink frame on taskbar.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          panelLocX – X value of location of panel.

          panelLocY – Y value of location of panel.

          blink – Whether to blink frame on task bar or not.

          makeSound – Whether to make beep sound or not.

          buzzFrame – Whether to give buzz effect to frame or not.

          size – Size of the light box shade panel.

Throws:

         LightBoxException – If given size of shade panel is not proper then this exception will be raised.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 boolean blink,
                                 boolean makeSound,
                                 boolean buzzFrame,
                                 java.awt.Dimension size)
                          throws LightBoxException

 To give light box effect with specified size of light box shade panel with additional property flags like playing a beep sound, buzz frame, blink frame on taskbar.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          blink – Whether to blink frame on task bar or not.

          makeSound – Whether to make beep sound or not.

          buzzFrame – Whether to give buzz effect to frame or not.

          size – Size of the light box shade panel.

Throws:

        LightBoxException – If given size of shade panel is not proper then this exception will be raised.


 public void closeLightBox( javax.swing.JFrame jFrame,
                                           javax.swing.JPanel jPanel)

Exist light box effect.

Parameters:

          jFrame – Frame on which light box effect has taken place.

          jPanel – Panel that is shown as a pop up in light box effect.


 Links:

  1. Swing light box source code and test class are shared here.

Feel free to comment for any query or information regarding this jar on this site.

Make JFrame transparent

How to create a slider for JFrame transparency and make JFrame transparent accordingly?

First create a frame that has a slider in it which will be used to set transparency amount.

import javax.swing.JFrame;
import javax.swing.JSlider;

public class TransparentFrame extends JFrame {
     public TransparentFrame() {
         setTitle("Transparent Frame");
         setSize(400,400);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         JSlider slider = new JSlider(JSlider.HORIZONTAL);
         add(slider);
         setVisible(true);
     }
     public static void main(String[] args) {
         new TransparentFrame();
     }
}

Output of this will be:

Now add a change listener to slider so we can monitor it.


slider.addChangeListener(new ChangeListener() {
       @Override
       public void stateChanged(ChangeEvent e) {
       }
});

Now we will write our transparency logic in this method but before we do that first let’s see how to make a JFrame transparent.

To make a JFrame transparent java has a built in utility class that is AWTUtilities. By using methods provided in this class we can make our JFrame transparent. Following is the code for that:

       AWTUtilities.setWindowOpacity(window, floatOpacity);

Arguments:

                  Window – Your frame/window object.

                  floatOpactity – between 0 to 1.  1 for no opacity and 0 for fully transparent.

So now we know that we have to add this logic to slider change event and give sliders value as floatOpacity value. So for that change stateChanged() method with following:

@Override
public void stateChanged(ChangeEvent e) {
      JSlider slider = (JSlider) e.getSource();
      if(!slider.getValueIsAdjusting()){
            AWTUtilities.setWindowOpacity(TransparentFrame.this, slider.getValue());
      }
}

Think it’s done. No we still have to make sure that opacity value doesn’t go beyond its limit that is 0.0f to 1.0f. So for that we have to limit our slider to these values. As slider don’t supports point values we will take values in multiple of 10 and then divide them by 100 to get desired value. For this we will change JSlider declaration and stateChanged like follow:


JSlider slider = new JSlider(JSlider.HORIZONTAL, 10, 100, 100);

Change following line in stateChanged method:


AWTUtilities.setWindowOpacity(TransparentFrame.this, slider.getValue()/100f);

So now when we run this program we see a frame with a slider in it which is set to end. And when we change slider the frame accordingly change its transparency.

Output:-

Note:-

To use AWTUtilities class in eclipse you need to change preference setting or you may have error for accessing restricted classes. To change settings do as follows:

  1. Right click on your project. Select properties.
  2. Select Java compiler and expand it.
  3. Select Errors/Warnings.
  4. Enable project specific settings.
  5. In Deprecated and Restricted API you will find Forbidden References (access rules.) Change it to Warning or Ignore.
Reference:

Also take a look take: Transparent JFrame using JNA

Create new message notification pop up in Java.

This article is about “How to create new message notification pop up in java?

Example:-

Pop up example

This image is taken from internet.

First create JFrame to work as pop up. Add some JLabels in it to contain information and assign them at proper location to look like a notification message.  A sample code is given below:

String message = "You got a new notification message. Isn't it awesome to have such a notification message.";
String header = "This is header of notification message";
JFrame frame = new JFrame();
frame.setSize(300,125);
frame.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1.0f;
constraints.weighty = 1.0f;
constraints.insets = new Insets(5, 5, 5, 5);
constraints.fill = GridBagConstraints.BOTH;
JLabel headingLabel = new JLabel(header);
headingLabel .setIcon(headingIcon); // --- use image icon you want to be as heading image.
headingLabel.setOpaque(false);
frame.add(headingLabel, constraints);
constraints.gridx++;
constraints.weightx = 0f;
constraints.weighty = 0f;
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.NORTH;
JButton cloesButton = new JButton("X");
cloesButton.setMargin(new Insets(1, 4, 1, 4));
cloesButton.setFocusable(false);
frame.add(cloesButton, constraints);
constraints.gridx = 0;
constraints.gridy++;
constraints.weightx = 1.0f;
constraints.weighty = 1.0f;
constraints.insets = new Insets(5, 5, 5, 5);
constraints.fill = GridBagConstraints.BOTH;
JLabel messageLabel = new JLabel("<HtMl>"+message);
frame.add(messageLabel, constraints);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);

Output of this will be:

First look of pop up.

Here I have created a JFrame and add two labels; first is headingLabel which is header label and second is messageLabel which will contains message information; and a close button. I have used GridBagLayout but you can use any of your choice.

Now to make this frame look like a popup we have to remove the title bar and border from this frame. For this add following line after frame.setSize(…); :

frame.setUndecorated(true);

Now the output will be:

Second look of pop up.

Note that now our frame cannot be closed as it do not have title bar close button. So to make our close button to work as frame closing button change its declaration as follows:

JButton cloesButton = new JButton(new AbstractAction("x") {
        @Override
        public void actionPerformed(final ActionEvent e) {
               frame.dispose();
        }
});

 After adding it you will get error as “Cannot refer to a non-final variable frame inside an inner class defined in a different method”.  To get rid of this error you can adopt one of following solution:

  1. Make your frame variable as final.
  2. Make your frame variable a global variable in class.
  3. Make your class extends JFrame and remove frame variable at all.

Now when you run your program it will look like same as in figure 2 but now you will be able to close your frame by clicking on closeButton.

You will notice that your frame appears at the top of screen so change to its location bottom right corner of the screen add following lines after creating frame:

Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();// size of the screen
Insets toolHeight = Toolkit.getDefaultToolkit().getScreenInsets(frame.getGraphicsConfiguration());// height of the task bar
frame.setLocation(scrSize.width - frame.getWidth(), scrSize.height - toolHeight.bottom - frame.getHeight());

Now when you run it will look like this:

Third look of pop up.

Now to make it to disappear after predefined time add following lines at the end:

new Thread(){
      @Override
      public void run() {
           try {
                  Thread.sleep(5000); // time after which pop up will be disappeared.
                  frame.dispose();
           } catch (InterruptedException e) {
                  e.printStackTrace();
           }
      };
}.start();

Up to this you have successfully created a notification pop up that will appear at bottom-right corner of screen and disappear after some time if close button is not clicked.

So as a final touch you can design it as you want by applying look and feel or by applying different colours in frame.

Also you can make it appear on top of all windows by adding:

frame.setAlwaysOnTop(true);

Some things to notice in above code blocks:

                  1.      <HtMl> tag in messageLabel. It is to make word wrap in label. But make sure you text in message does not exceed some specific amount of length. You can adjust this and height of pop up as per your need.

                   2.      “headingIcon” is not declared in code. It is the image icon you want to use instead of devil icon in screen shot as a heading title icon. A sample declaration will look like:

                       ImageIcon headingIcon = new ImageIcon(“image_url”);

                    3.      Currently a new window for our pop up is shown in task bar so if you want that no window is shown for pop up in task bar change JFrame to JDialog.

                   4.      In above code default timeout before the pop up will be disappear is taken as 5 seconds you can update it as per your need by editing following line in code:

                        Thread.sleep(5000); // time after which pop up will be disappeared.

                    5.      To make close button look like default title bar’s close button “x” is taken in his text. You can write it close if you want to.

 

Hope this helps you. Thanks and Regards.

Change default title bar in JFrame

This blog contains information about how to change the default boring title bar 
of a Java Swing Application and make your application look something like this:

Midnight Look And Feel JFrame

The magic is done by following 2 lines:
       jframe.setUndecorated(true);
       jframe.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);

After adding this 2 lines your jframe will look like:

This will still work same as title bar but now when you apply any of your look and 
feel it will become like the first image. Not the exact copy because your look and 
feel will be different from the one (Midnight Skin Look And Feel) used to take the 
first picture.

%d bloggers like this: