Using a custom font for a JLabel - java

I'm trying to use a special font in my JFrame, but I'm running into problems. I have a JLabel defined like this:
private JLabel lab = new JLabel("Text");
and I have a file called CUSTOMFONT-MEDIUM.TTF (TrueType font) but after writing the following:
try {
lab.setFont(Font.createFont(Font.TRUETYPE_FONT, getClass().getResource("/CUSTOMFONT-MEDIUM.TTF").openStream()));
} catch(IOException ex){
//exception handled here I suppose
} catch(FontFormatException ex2) {
//same here
}
the code compiles and the everything works right except that "lab" is not displayed so there is no text. I suppose it is because I never specified what the font size should be, but any attempt I have made to do that fails. Can someone help me out here?

#sasankad is mostly correct (+1).
Once you have created the font, it will have a default size of 1
Font font = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/CUSTOMFONT-MEDIUM.TTF"));
You then need to derive the font size and style you want.
Font biggerFont = font.deriveFont(Font.BOLD, 48f);
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestCustomFont {
public static void main(String[] args) {
new TestCustomFont();
}
public TestCustomFont() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
try {
Font font = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/Royal Chicken.ttf"));
JLabel happy = new JLabel("Happy little Miss Chicken");
happy.setFont(font.deriveFont(Font.BOLD, 48f));
add(happy);
} catch (FontFormatException | IOException ex) {
ex.printStackTrace();
}
}
}
}
Check out java.awt.Font for more details...
You may also want to take a look at Physical and Logical Fonts, Font Configuration Files

The Font you created has to be registered first in the GraphicsEnvironment to be accessible to all and derive the size of the font:
Font font = Font.createFont(Font.TRUETYPE_FONT, getClass().getResource("/CUSTOMFONT-MEDIUM.TTF").openStream());
GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
genv.registerFont(font);
// makesure to derive the size
font = font.deriveFont(12f);

Related

Java: system L&F only appearing correctly for second time

I am using this code to set up a look and feel on a program:
UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName());
I am only using the system look and feel on a JPanel (inside a JFrame) that i show during the runtime of the program. The first time i show the JPanel, the L&F is wrong (looks like it is for an older version of windows or something, not the same as i used before, on the other components). I hide the JPanel then open it agin, the L&F is now correct.
Sadly i wasn't able to produce a reproducaple example but the problem persists in the original program.
It consists of multiple classes, and has an object orientedly written UI, this is the code responsible for the problematic JPanel:
package almanah;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SeriesProperties extends JPanel {
JButton button_close = new JButton();
JPanel container = new JPanel();
JScrollPane scPane = new JScrollPane(container);
public SeriesProperties(ItemLib lib) {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
Logger.getLogger(SeriesProperties.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(SeriesProperties.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(SeriesProperties.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(SeriesProperties.class.getName()).log(Level.SEVERE, null, ex);
}
this.setLayout(new BorderLayout());
this.add(button_close, BorderLayout.EAST);
button_close.addActionListener((e) -> {
Almanah.frame.swapToTiles();
});
scPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.add(scPane, BorderLayout.CENTER);
//container
container.setBackground(Color.red);
container.setLayout(new WrapLayout());
for (int i = 0; i < 100; i++) {
JPanel panel=new JPanel();
panel.setPreferredSize(new Dimension(100, 100));
container.add(panel);
}
this.updateUI();
}
}
Solution:
Error13660, have you fixed your problem? Here is my solution to change look and feel.
And see This answer.
package snippet;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(() -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
var frame = new JFrame();
var panel = new JPanel();
{ // Button 0: onclick change theme 0
var btn = new JButton("Theme 0");
btn.addActionListener((e) -> {
System.out.println("actionPerformed: change theme 0");
Test.changeLaF(frame, "javax.swing.plaf.metal.MetalLookAndFeel");
});
panel.add(btn);
}
{ // Button 1: onclick change theme 1
var btn = new JButton("Theme 1");
btn.addActionListener((e) -> {
System.out.println("actionPerformed: change theme 1");
Test.changeLaF(frame, "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
});
panel.add(btn);
}
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
public static final void changeLaF(final JFrame frame, final String nameLookAndFeel) {
try {
UIManager.setLookAndFeel(nameLookAndFeel);
SwingUtilities.updateComponentTreeUI(frame);
frame.pack ();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Before edition of 24-02-21:
Have you tried using SwingUtilities.updateComponentTreeUI(frame);
Changing the Look and Feel After Startup: You can change the L&F with setLookAndFeel even after the program's GUI is visible. To make existing components reflect the new L&F, invoke the SwingUtilities updateComponentTreeUI method once per top-level container. Then you might wish to resize each top-level container to reflect the new sizes of its contained components. For example:
see: lookandfeel/plaf#Dynamic
UIManager.setLookAndFeel(lnfName);
SwingUtilities.updateComponentTreeUI(frame);
frame.pack();
Update:
/!\ if successful loaded L&F, all components use that L&F. lookandfeel/plaf#Steps
Establish the look and feel state BEFORE you create ANY UI elements. The ability to switch the L&F at runtime is actually a side effect and is generally discouraged as it was never a feature of the system.
Instead, probably in your main method, set the look and feel and then build your UI after it.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame();
// I don't know what ItemLib, as the source is incomplete
frame.add(new SeriesProperties(...));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class SeriesProperties extends JPanel {
JButton button_close = new JButton();
JPanel container = new JPanel();
JScrollPane scPane = new JScrollPane(container);
public SeriesProperties(ItemLib lib) {
this.setLayout(new BorderLayout());
this.add(button_close, BorderLayout.EAST);
button_close.addActionListener((e) -> {
// This seems like a bad idea
// You should consider using a observer/delegate
// pattern instead, reducing the coupling of your code
Almanah.frame.swapToTiles();
});
scPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.add(scPane, BorderLayout.CENTER);
//container
container.setBackground(Color.red);
container.setLayout(new WrapLayout());
for (int i = 0; i < 100; i++) {
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(100, 100));
container.add(panel);
}
//this.updateUI();
}
}
}

Swing UIManager.put doesn't seem to work right all the time. Bug or not?

I've been using UIManger.put to change the font of labels globally, but it seems like it works inconsistently. Sometimes does, sometimes doesn't.
UIManager does indeed save the new value on it's map.
For example, if you use:
final Font labelFont = new Font("Source Sans Pro", 0, 24);
UIManager.put("Label.font", labelFont);
And you use before/after creating the label:
System.out.println(UIManager.get("Label.font"));
it returns
java.awt.Font[family=Source Sans Pro,name=Source Sans Pro,style=plain,size=24]
But the label's font isn't changed always. Whats is wrong?
I've tried to change the property on the dispatch thread and out of it, but the result is the same.
Working right:
Working wrong:
The next both examples have the same problem.
Here is an example, try it many times and you will see, unless I'm the one I have something bugged on my computer (I tried it like 30 times, no exaggeration, without any problems, but it did happen after that):
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.lang.reflect.InvocationTargetException;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public final class ElVecino {
private JFrame frame;
public ElVecino() {
Locale.setDefault(Locale.forLanguageTag("es-CL"));
}
public static void main(String[] args) {
final ElVecino application = new ElVecino();
application.setLookAndFeel();
try {
SwingUtilities.invokeAndWait(() -> {
application.createAndShowGUI();
});
} catch (InterruptedException | InvocationTargetException exception) {
Logger.getLogger(ElVecino.class.getName()).log(Level.SEVERE, null, exception);
}
}
public void createAndShowGUI() {
frame = new JFrame("testApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel contentPane = (JPanel)frame.getContentPane();
System.out.println(UIManager.get("Label.font"));
final JLabel label = new JLabel("Cargando...");
contentPane.add(label, BorderLayout.CENTER);
frame.setPreferredSize(new Dimension(800, 600));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
System.out.println(UIManager.get("Label.font"));
}
/**
*
*/
public void setLookAndFeel() {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException exception) {
Logger.getLogger(ElVecino.class.getName()).log(Level.SEVERE, null, exception);
}
final Font labelFont = new Font("Source Sans Pro", 0, 24);
UIManager.put("Label.font", labelFont);
}
}
Here is another example putting every GUI method on the dispatch thread, also gives me the same problem, just try it many times
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.lang.reflect.InvocationTargetException;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public final class ElVecino {
private JFrame frame;
public ElVecino() {
Locale.setDefault(Locale.forLanguageTag("es-CL"));
}
public static void main(String[] args) {
final ElVecino application = new ElVecino();
SwingUtilities.invokeLater(() -> {
application.setLookAndFeel();
application.createAndShowGUI();
});
}
public void createAndShowGUI() {
frame = new JFrame("testApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel contentPane = (JPanel)frame.getContentPane();
final JLabel label = new JLabel("Cargando...");
contentPane.add(label, BorderLayout.CENTER);
frame.setPreferredSize(new Dimension(800, 600));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
/**
*
*/
public void setLookAndFeel() {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException exception) {
Logger.getLogger(ElVecino.class.getName()).log(Level.SEVERE, null, exception);
}
final Font labelFont = new Font("Source Sans Pro", 0, 24);
final Font textFieldFont = new Font("Source Code Pro", 0, 24);
UIManager.put("Label.font", labelFont);
UIManager.put("TextField.font", textFieldFont);
UIManager.put("TextArea.font", textFieldFont);
UIManager.put("ProgressBar.font", labelFont);
}
}
I think there must be some information about using UIManger.put that I don't know
Not about UIManager, but about Swing in general:
Swing components should be created on the Event Dispatch Thread. Read the section from the Swing tutorial on Concurrency for more information. So I would set the UIManager defaults in the EDT as well.
The Swing tutorial recommends to use invokeLater(...), not InvokeAndWait(...). See the LabelDemo example code from How to Use Labels for an example on how to structure your code.
Once you set swing properties, you need to call SwingUtilities.updateComponentTreeUi()

Set background image in JEditorPane from local file

I am using JEditorPane to set background image on my JFrame. The reason why I use this component, is that I want to set small image and be able to repeat it according to size of the frame. Similar to CSS analogue of background-repeat. The problem which I have is, I am not able to load image from my local folder.
background.setContentType("text/html");
background.setText("<html><body style=\"background-image: url(http://hq-wallpapers.ru/wallpapers/8/hq-wallpapers_ru_abstraction3d_39318_1920x1200.jpg);\"></body></html>");
this.setContentPane(background);
What I tried is to use: url(../image.jpg); but it doesn't work.
If can offer better way of doing this task, I will appreciate it.
P.S.: And I am not allowed to use JFrameForm, because of requirements of my project.
../image.jpg isn't a valid URL, as the JEditorPane has no "code base" from which to access where the "reference" should be loaded from.
Instead, you could use a File to generate a URL (or if it's an embedded resource, Class#getResource), for example...
File background = new File("../image.jpg");
URL url = background.toURI().toURL();
ep.setContentType("text/html");
ep.setText("<html><body style='color: #ffffff; background-image: url(" + url.toString() + ");'>Boo</body></html>");
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
try {
setLayout(new BorderLayout());
JEditorPane ep = new JEditorPane();
File background = new File("/Volumes/Disk02/Dropbox/MegaTokyo/Aqua/aria_fanart_by_imskeptical-d5xbvgz.jpg");
URL url = background.toURI().toURL();
ep.setContentType("text/html");
ep.setText("<html><body style='color: #ffffff; background-image: url(" + url.toString() + ");'>Boo</body></html>");
add(new JScrollPane(ep));
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Now if URL url = background.toURI().toURL(); doesn't work, you might need to use URL url = background.getCanonicalFile().toURI().toURL(); instead

Can't add JLabel to JPanel

I have this code:
ImageIcon ii = new ImageIcon("https://c1.staticflickr.com/9/8384/8682624224_4e44bf947d_h.jpg");
subStream.add(new JLabel(ii));
It's meant to add JLabel with photo to JPanel called subStream.
But it doesn't work, no errors or anything. Why so?
Image is supposed to appear in 3rd JPanel, just above Buttons.
Things to be aware of...
ImageIcon can fail silently...annoying I know...this is because...
ImageIcon uses a background thread to load the images, this is because it was designed to allow for slow sources (dial up networks) which might need time to fully realise the image.
You should use ImageIO.read to test the URL to discount potential issues with downloading the image. This will throw an IOException if the image can't be loaded for some reason and will block until the image is fully loaded, so beware of that
See Reading/Loading an Image for more details
For example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
try {
BufferedImage img = ImageIO.read(new URL("https://c1.staticflickr.com/9/8384/8682624224_4e44bf947d_h.jpg"));
JLabel label = new JLabel(new ImageIcon(img));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(label);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException exp) {
exp.printStackTrace();
}
}
});
}
}
So, this discounts the image and web server as the potential problem (at least from within my network), there must be something else wrong with your code. Consider providing a runnable example which demonstrates your problem. This will result in less confusion and better responses
You are invoking ImageIcon(String filename) constructor. Try with the URL one:
ImageIcon icon = new ImageIcon(new URL("your URL"));
// Imports
// ...
public class MyFrame extends JFrame
{
public MyFrame()
{
super("Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
try
{
URL url = new URL("http://upload.wikimedia.org/wikipedia/it/0/0b/Vegeta_-_Sigla_Iniziale_Dragon_Ball_Kai.jpg");
getContentPane().add(new JLabel(new ImageIcon(url)));
}
catch(Exception ex)
{
ex.printStackTrace();
}
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(() ->
{
new MyFrame().setVisible(true);
});
}
}

How do I draw an image in the shape of a parallelogram?

So, I know that images can be cropped, shrunk, and expanded, but can you adapt an image into the shape of a parallelogram? I'm using Java Swing to draw images. I was thinking maybe some class or some method of BufferedImage might do the trick, but I couldn't find anything. I have also searched Google for a while, but I cannot find an answer. Does anyone know of a way I could do this, or a webpage that explains it? Thanks in advance.
You could use AffineTransform.getShearInstance.
This example uses a AffineTransformOp to "filter" the original image
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SkewImage {
public static void main(String[] args) {
new SkewImage();
}
public SkewImage() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridLayout(1, 2));
try {
BufferedImage original = ImageIO.read(new File("C:\\hold\\thumbnails\\Megatokyo_707___Torn_by_crusaderky.jpg"));
BufferedImage skew = new BufferedImage(original.getWidth(), original.getHeight(), BufferedImage.TYPE_INT_ARGB);
// Adjust the image width if we use a negative skew...
double skewX = 0.3d;
double x = (skewX < 0) ? -skewX * original.getHeight() : 0;
AffineTransform at = AffineTransform.getTranslateInstance(x, 0);
at.shear(skewX, 0);
AffineTransformOp op = new AffineTransformOp(at,
new RenderingHints(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC));
skew = op.filter(original, null);
add(new JLabel(new ImageIcon(original)));
add(new JLabel(new ImageIcon(skew)));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Just an example using a Java image processing framework.
Output:
public class SkewExample extends JFrame{
MarvinImagePlugin skew = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.transform.skew");
public SkewExample(){
super("Skew Example");
// Layout
setLayout(new GridLayout(6,1));
// Load Image
MarvinImage image = MarvinImageIO.loadImage("./res/chamaleon.jpg");
skew.setAttribute("skew", "Horizontal");
// Process the image multiple times with different angle.
for(int i=1; i<=6; i++){
add(new JLabel(new ImageIcon(skew(image, i*7).getBufferedImage())));
}
setSize(340,880);
setVisible(true);
}
private MarvinImage skew(MarvinImage imageIn, int angle){
skew.setAttribute("SkewAngle", angle);
MarvinImage ret = new MarvinImage(imageIn.getWidth(),imageIn.getHeight());
ret.fillRect(0, 0,imageIn.getWidth(),imageIn.getHeight(), new Color(238,238,238));
ret.update();
skew.process(imageIn, ret);
ret.update();
return ret;
}
public static void main(String[] args) {
new SkewExample().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Categories

Resources