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
Related
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);
});
}
}
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);
I am making a java application that includes a JWindow. I want to be able to track the mouse without the user having to click the window after going to another window.
Your question is little vague on why you want to continue processing the mouse once it's left the JWindow...but
You have two (basic) choices when it comes to mointoring the mouse outside of your application, you can use a JNI/JNA solution or you can poll MouseInfo.
The following demonstrates the latter, using MouseInfo and a javax.swing.Timer to update a label...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.MouseInfo;
import java.awt.PointerInfo;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MouseWindow {
public static void main(String[] args) {
new MouseWindow();
}
public MouseWindow() {
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 {
private JLabel label;
public TestPane() {
setLayout(new BorderLayout());
label = new JLabel();
label.setFont(label.getFont().deriveFont(48f));
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
add(label);
updateMouseInfo();
Timer timer = new Timer(250, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
updateMouseInfo();
}
});
timer.start();
}
protected void updateMouseInfo() {
PointerInfo pi = MouseInfo.getPointerInfo();
label.setText(pi.getLocation().x + "x" + pi.getLocation().y);
}
}
}
Updated
You may also find Window#setAlwaysOnTop of help to keep the window ontop of the others, if support for the platform
Well I'm writing an IRC client in Java and I was wondering if there was a way to make my app's icon bounce in the dock when a nickalert is triggered (or any other relevant notification).
If Windows also has some sort of notification system I'd like to know about it as well.
Under the MacOS, try using something like Application#requestUserAttention(boolean)
import com.apple.eawt.Application;
...
Application application = Application.getApplication();
application.requestUserAttention(false);
nb- I've not tried this my self - sorry.
Updated with example
From the JavaDocs
Requests user attention to this application (usually through bouncing
the Dock icon). Critical requests will continue to bounce the Dock
icon until the app is activated. An already active application
requesting attention does nothing.
That means, that if the application has focus, then the method will do nothing.
Test on Mac OSX 10.7.5, Java 1.7.0_07
import com.apple.eawt.Application;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestMacIcon {
public static void main(String[] args) {
new TestMacIcon();
}
public TestMacIcon() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
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() {
final Application application = Application.getApplication();
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
System.out.println("clicked");
application.requestUserAttention(true);
application.setDockIconImage(ImageIO.read(getClass().getResource("/Java.png")));
application.setDockIconBadge("Blah");
application.requestUserAttention(true);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
Timer time = new Timer(2000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!SwingUtilities.getWindowAncestor(TestPane.this).hasFocus()) {
((Timer)e.getSource()).stop();
System.out.println("Pay attention!!");
application.requestUserAttention(true);
}
}
});
time.setRepeats(true);
time.setCoalesce(true);
time.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Ps make sure that you do-focus application ;)
Well I'm writing an IRC client in Java and I was wondering if there was a way to make my app's icon bounce in the dock when a nickalert is triggered (or any other relevant notification).
If Windows also has some sort of notification system I'd like to know about it as well.
Under the MacOS, try using something like Application#requestUserAttention(boolean)
import com.apple.eawt.Application;
...
Application application = Application.getApplication();
application.requestUserAttention(false);
nb- I've not tried this my self - sorry.
Updated with example
From the JavaDocs
Requests user attention to this application (usually through bouncing
the Dock icon). Critical requests will continue to bounce the Dock
icon until the app is activated. An already active application
requesting attention does nothing.
That means, that if the application has focus, then the method will do nothing.
Test on Mac OSX 10.7.5, Java 1.7.0_07
import com.apple.eawt.Application;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestMacIcon {
public static void main(String[] args) {
new TestMacIcon();
}
public TestMacIcon() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
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() {
final Application application = Application.getApplication();
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
System.out.println("clicked");
application.requestUserAttention(true);
application.setDockIconImage(ImageIO.read(getClass().getResource("/Java.png")));
application.setDockIconBadge("Blah");
application.requestUserAttention(true);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
Timer time = new Timer(2000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!SwingUtilities.getWindowAncestor(TestPane.this).hasFocus()) {
((Timer)e.getSource()).stop();
System.out.println("Pay attention!!");
application.requestUserAttention(true);
}
}
});
time.setRepeats(true);
time.setCoalesce(true);
time.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Ps make sure that you do-focus application ;)