Skip to content

Instantly share code, notes, and snippets.

@d3ep4k
Last active August 29, 2015 14:26
Show Gist options
  • Select an option

  • Save d3ep4k/922602601201e9c6ed11 to your computer and use it in GitHub Desktop.

Select an option

Save d3ep4k/922602601201e9c6ed11 to your computer and use it in GitHub Desktop.
Custom Shaped Window
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;
public class ShapedWindow implements ActionListener{
ShapedPane pane = new ShapedPane();
final static int INTERVAL = 1000;
String[] tokens;
int counter = 0;
final Timer timer = new Timer(INTERVAL, this);
public static void main(String[] args) {
new ShapedWindow("You Are Awesome!");
}
public ShapedWindow(String sentance) {
tokens = sentance.split(" ");
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JWindow frame = new JWindow();
frame.setBackground(new Color(0, 0, 0, 0));
frame.setContentPane(pane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setAlwaysOnTop(true);
timer.start();
}
});
}
public void actionPerformed(ActionEvent evt) {
pane.setTokenText(tokens[counter++ % tokens.length ]);
pane.repaint();
}
public class ShapedPane extends JPanel {
int width, height;
String text = "";
int fontSize = 70;
int color = 0x32cd32;
public ShapedPane() {
setOpaque(false);
setLayout(new GridBagLayout());
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
width = (int)screenSize.getWidth();
height = (int)screenSize.getHeight();
}
public void setTokenSize(int fontSize){
this.fontSize = fontSize;
}
public void setTokenColor(int color){
this.color = color;
}
public void setTokenText(String text){
this.text = text;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
Graphics2D g2d = (Graphics2D) g.create();
RenderingHints hints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHints(hints);
g2d.setColor(new Color(color));
g2d.setFont(new Font("Verdana", Font.PLAIN, fontSize));
FontMetrics fm = g2d.getFontMetrics();
Rectangle2D r = fm.getStringBounds(text, g2d);
int x = (this.getWidth() - (int) r.getWidth()) / 2;
int y = (this.getHeight() - (int) r.getHeight()) / 2 + fm.getAscent();
g2d.drawString(text, x, y);
g2d.dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment