package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
public class WindowTaskbarFlash extends JFrame {
private WindowTaskbarFlash() throws HeadlessException {
initUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
() -> new WindowTaskbarFlash().setVisible(true));
}
private void initUI() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
pack();
setSize(200, 200);
setState(Frame.ICONIFIED);
// Demonstrate flashes the application window task bar
// by calling the toFront method every 5 seconds.
Timer timer = new Timer(5000, e -> toFront());
timer.start();
}
}
Category Archives: Java
How do I change JFrame state programmatically?
In the following code snippet you’ll learn how to programmatically change the frame state of a JFrame component in a Swing application. The JFrame states are represented as a bitwise masks. You can minimize, maximize or make the JFrame state to normal, using the JFrame.setExtendedState() method.
You can pass the following values as the parameter to the method:
Frame.NORMALFrame.ICONIFIEDFrame.MAXIMIZED_HORIZFrame.MAXIMIZED_VERTFrame.MAXIMIZED_BOTH
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
public class SwingFrameState extends JFrame {
public SwingFrameState() throws HeadlessException {
initUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
() -> new SwingFrameState().setVisible(true));
}
private void initUI() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
final JButton minimize = new JButton("Minimize");
final JButton maximize = new JButton("Maximize");
final JButton normal = new JButton("Normal");
add(normal);
add(minimize);
add(maximize);
pack();
setSize(500, 200);
ActionListener listener = e -> {
if (e.getSource() == normal) {
setExtendedState(Frame.NORMAL);
} else if (e.getSource() == minimize) {
setExtendedState(Frame.ICONIFIED);
} else if (e.getSource() == maximize) {
setExtendedState(Frame.MAXIMIZED_BOTH);
}
};
minimize.addActionListener(listener);
maximize.addActionListener(listener);
normal.addActionListener(listener);
}
}
The screenshot of the output from the code snippet above is:
How do I obtain ServletContext of another application?
The ServletContext.getContext(String uripath) enable us to access servlet context of another web application deployed on the same application server. A configuration need to be added to enable this feature.
In the example below we will forward the request from the current application to the /otherapp/hello.jsp page. We place a string in the request object attribute of the current application and going to show it in the hello.jsp page.
package org.kodejava.servlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = {"/context"})
public class GetAnotherContextServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get ServletContext of another application on the same Servlet
// container. This allows us to forward request to another application
// on the same application server.
ServletContext ctx = request.getServletContext().getContext("/otherapp");
// Set a request attribute and forward to hello.jsp page on another
// context.
request.setAttribute("MESSAGE", "Hello There!");
RequestDispatcher dispatcher = ctx.getRequestDispatcher("/hello.jsp");
dispatcher.forward(request, response);
}
}
To enable this feature in Tomcat we need to enable the crossContext attribute by setting the value to true, the default value is false. Update the server.xml file to add the following configuration inside the <Host> node.
<Context path="/webapp" debug="0" reloadable="true" crossContext="true"/>
Maven dependencies
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
How do I define a filter using @WebFilter annotation?
The following example show you how to create a servlet filter using the @WebFilter annotation. We will create a simple filter that will check whether an attribute is exists in the http session object. If no attribute found this filter will redirect user into a login page.
package org.kodejava.filter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(urlPatterns = "/*", description = "Session Checker Filter")
public class SessionCheckerFilter implements Filter {
private FilterConfig config = null;
public void init(FilterConfig config) throws ServletException {
this.config = config;
config.getServletContext().log("Initializing SessionCheckerFilter");
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain)
throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
//
// Check to see if user's session attribute contains an attribute
// named AUTHENTICATED. If the attribute is not exists redirect
// user to the login page.
//
if (!request.getRequestURI().endsWith("login.jsp") &&
request.getSession().getAttribute("AUTHENTICATED") == null) {
response.sendRedirect(request.getContextPath() + "/login.jsp");
}
chain.doFilter(req, res);
}
public void destroy() {
config.getServletContext().log("Destroying SessionCheckerFilter");
}
}
Before the birth of @WebFilter annotation as defined in the Servlet 3.0 Specification. To make the filter functional we must register it in the web.xml file by using the filter and the filter-mapping element. And once it active it will collaborate with the other filters in the filter chain for the current servlet context.
Maven dependencies
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
How do I draw a vertical text in Java 2D?
To draw a text / string vertically we need to do a transform on the Graphics2D object. First, create an instance of AffineTransform and set the rotation using the setToRotation() method. And then pass this transform object into g2.setTransform() method.
package org.kodejava.awt.geom;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
public class DrawVerticalText extends JPanel {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Draw Vertical Text Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(new DrawVerticalText());
frame.pack();
frame.setSize(420, 350);
frame.setVisible(true);
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
// Define rendering hint, font name, font style and font size
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(new Font("Segoe Script", Font.BOLD, 22));
g2.setColor(Color.RED);
// Rotate 90 degree to make a vertical text
AffineTransform at = new AffineTransform();
at.setToRotation(Math.toRadians(90), 80, 100);
g2.setTransform(at);
g2.drawString("This is a vertical text", 10, 10);
}
}
Run the snippet, and you’ll see the following screen:
How do I define a servlet with @WebServlet annotation?
Annotations is one new feature introduces in the Servlet 3.0 Specification. Previously to declare servlets, listeners or filters we must do it in the web.xml file. Now, with the new annotations feature we can just annotate servlet classes using the @WebServlet annotation.
package org.kodejava.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(
name = "HelloAnnotationServlet",
urlPatterns = {"/hello", "/helloanno"},
asyncSupported = false,
initParams = {
@WebInitParam(name = "name", value = "admin"),
@WebInitParam(name = "param1", value = "value1"),
@WebInitParam(name = "param2", value = "value2")
}
)
public class HelloAnnotationServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head><title>WebServlet Annotation</title></head>");
out.write("<body>");
out.write("<h1>Servlet Hello Annotation</h1>");
out.write("<hr/>");
out.write("Welcome " + getServletConfig().getInitParameter("name"));
out.write("</body></html>");
out.close();
}
}
After you’ve deploy the servlet you’ll be able to access it either using the /hello or /helloanno url.
The table below give brief information about the attributes accepted by the @WebServlet annotation and their purposes.
| ATTRIBUTE | DESCRIPTION |
|---|---|
name |
The servlet name, this attribute is optional. |
description |
The servlet description and it is an optional attribute. |
displayName |
The servlet display name, this attribute is optional. |
urlPatterns |
An array of url patterns use for accessing the servlet, this attribute is required and should at least register one url pattern. |
asyncSupported |
Specifies whether the servlet supports asynchronous processing or not, the value can be true or false. |
initParams |
An array of @WebInitParam, that can be used to pass servlet configuration parameters. This attribute is optional. |
loadOnStartup |
An integer value that indicates servlet initialization order, this attribute is optional. |
smallIcon |
A small icon image for the servlet, this attribute is optional. |
largeIcon |
A large icon image for the servlet, this attribute is optional. |
Maven dependencies
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
How do I draw a string in Java 2D?
The code snippet below show you how to draw a string using Graphics2D. The drawString() method accept the string to be drawn and their x and y coordinate. Here you can also see how to set the antialiasing mode using the setRenderingHint() method.
package org.kodejava.awt.geom;
import javax.swing.*;
import java.awt.*;
public class DrawString extends JPanel {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Draw String Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(new DrawString());
frame.pack();
frame.setSize(420, 300);
frame.setVisible(true);
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
// Define rendering hint, font name, font style and font size
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(new Font("Segoe Script", Font.BOLD + Font.ITALIC, 40));
g2.setPaint(Color.ORANGE);
// Draw Hello World String
g2.drawString("Hello World!", 50, 100);
}
}
Run the snippet, and you’ll see the following screen:
How do I create a gradient paint in Java 2D?
To change the color of a graphics shape we can use the setPaint() method. For a simple coloring we can pass the color object into this method, such as Color.RED or Color.GREEN.
If you want to paint with a gradient paint you can use the GradientPaint class. This class provides a way to fill a shape with a linear color gradient pattern. To create a gradient color pattern you can pass the following parameter to the object constructor.
x1: x coordinate of the first specified point in user spacey1: y coordinate of the first specified point in user spacecolor1: color at the first specified pointx2: x coordinate of the second specified point in user spacey2: y coordinate of the second specified point in user spacecolor2: color at the second specified point
package org.kodejava.awt.geom;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
public class GradientPaintDemo extends JComponent {
public static void main(String[] args) {
JFrame frame = new JFrame("Gradient Paint Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new GradientPaintDemo());
frame.pack();
frame.setSize(new Dimension(420, 350));
frame.setVisible(true);
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
GradientPaint blackToGray = new GradientPaint(50, 50, Color.BLACK,
300, 100, Color.LIGHT_GRAY);
g2.setPaint(blackToGray);
g2.fill(new Rectangle2D.Double(50, 50, 300, 100));
GradientPaint blueToBlack = new GradientPaint(0, 0, Color.BLUE,
400, 400, Color.BLACK);
g2.setPaint(blueToBlack);
g2.fill(new Rectangle2D.Double(50, 160, 300, 100));
}
}
This code snippet produce the following output:
How do I define stroke when drawing a shape in Java 2D?
package org.kodejava.awt.geom;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Line2D;
public class DrawStrokeDemo extends JComponent {
public static void main(String[] args) {
JFrame frame = new JFrame("Draw Stroke Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new DrawStrokeDemo());
frame.pack();
frame.setSize(new Dimension(420, 200));
frame.setVisible(true);
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
float[] strokes = {1, 2, 3, 4, 5, 6};
for (float stroke : strokes) {
g2.setStroke(new BasicStroke(stroke));
g2.draw(new Line2D.Float(50, stroke * 20, 350, stroke * 20));
}
}
}
This code snippet produce the following output:
How do I create a dashed stroke in Java 2D?
package org.kodejava.awt.geom;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
public class DrawDashedStroke extends JComponent {
public static void main(String[] args) {
JFrame frame = new JFrame("Draw Dashed Stroke Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new DrawDashedStroke());
frame.pack();
frame.setSize(new Dimension(420, 250));
frame.setVisible(true);
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
float[] dash = {10.0f, 5.0f, 3.0f};
// Creates a dashed stroke
Stroke dashed = new BasicStroke(2.0f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f);
g2.setStroke(dashed);
g2.setPaint(Color.RED);
g2.draw(new RoundRectangle2D.Double(50, 50, 300, 100, 10, 10));
}
}
This code snippet produce the following output:






