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:


