Using an icon image for a GUI - java

I have created the following code for a school project, a "password protector", just for fun, really. However, the problem I have is that the icon image does not appear, but instead the default java "coffee cup".
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class UserInterfaceGUI extends JFrame
{
private static final long serialVersionUID = 1;
private JLabel userNameInfo; // ... more unimportant vars.
public UserInterfaceGUI()
{
this.setLayout(new FlowLayout());
userNameInfo = new JLabel("Enter Username:"); // ... more unimportant var. declartions
this.add(userNameInfo); // ... more unimportant ".add"s
event e = new event();
submit.addActionListener(e);
}
public static void main(String[] args)
{
//This icon has a problem \/
ImageIcon img = new ImageIcon("[File Location hidden for privacy]/icon.ico");
UserInterfaceGUI gui = new UserInterfaceGUI();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(400, 140);
gui.setIconImage(img.getImage());
gui.setTitle("Password Protector");
gui.setVisible(true);
}
}
Can someone tell me why this just shows the java coffee cup at the bottom of the screen and on the bar at the top of the window?

There are two likely problems here:
Java is unlikely to support .ico files. The only types that can be relied on are GIF, PNG & JPEG. For all types supported on any specific JRE, use ImageIO.getReaderFileSuffixes() (but seriously, for app. icons stick to the 3 types with guaranteed support).
The code is trying to load an application resource as a file, when it will likely be (or become) an embedded-resource that should be accessed by URL. See the embedded resource info. page for tips on how to form the URL.

Related

Java simple web browser weird output

To learn Networking in Java, I followed a tutorial to create a new web browser in NetBeans. Here is the code in ReadFile class:
package WebBrowser;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/**
*
* #author Siddharth Venu
*
*/
public class ReadFile extends JFrame{
private JTextField addressBar;
private JEditorPane display;
//constructor
public ReadFile(){
super("Sid Browser");
addressBar=new JTextField("Enter address");
//lambda expression instead of anonymous class
addressBar.addActionListener((ActionEvent event) -> {
loadData(event.getActionCommand());
});
add(addressBar,BorderLayout.NORTH);
display = new JEditorPane();
display.setEditable(false);
display.addHyperlinkListener((HyperlinkEvent event) -> {
if(event.getEventType()==HyperlinkEvent.EventType.ACTIVATED)
loadData(event.getURL().toString());
});
add(new JScrollPane(display), BorderLayout.CENTER);
setSize(500,300);
setVisible(true);
}
//load the data to display on the screen
private void loadData(String address){
try{
display.setPage(address);
addressBar.setText(address);
}catch(Exception e){
System.out.println(e);
}
}
}
And here is the code in the Main class:
package WebBrowser;
import javax.swing.JFrame;
/**
*
* #author Siddharth Venu
*
*/
public class Main {
public static void main(String[] args){
ReadFile browser=new ReadFile();
browser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I then ran the Main class, at beginning, as it is not displaying any data from a website, it is looking good with address bar on the top. But when I enter an URL, say http://google.com, it displays weird output as in the following image.
Why exactly is this happening? The weird blue background and misaligned Google logo.
[Edit] I got to know that the setPage method can only handle HTML, plain text or RTF and not js. But it should at least display the HTML part without the weird blue screen na? PS: The blue screen is appearing in other sites like facebook too.
I've tested your browser. I'm getting the same results on pages with html5, javascript and css like google.com or facebook.com.
But when I use bare to the bones website like this it obviously works. So I must assume that the issue was the lack of support for these technologies in this simple browser.
As for the guy in the video linked he used bare html google webpage which I was unable to find or read out from the video (or made the video some time ago). People in the youtube comment section were addressing your issue as well. They were describing it as a lack of support for html5 in Swing. However some managed to make it work properly in JavaFX.

Add subtitle and basic operation panel in VLCJ # Java

Good day colleagues!
I had several trouble using VLCJ and other Java media API-s.
1) I'd add a simple *.srt file to my EmbeddedMediaPlayerCompononent, bot how is this possible?
2) Also, how can I configurate the VLC lib in an x64 Windows OS?
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:\\Program Files (x86)\\VideoLAN\\VLC");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(),libVlc.class);
This not works well.
3) How could I add basic operation interface to my EmbeddedMediaPlayerCompononent like pause/play button?
Thank you, best regards! :)
My "VideoPlayer" class
package GUI.MediaPlayer;
import java.awt.BorderLayout;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
import StreamBean.UIBean;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
public class VideoPlayer extends JFrame{
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
public VideoPlayer(String videoURL) {
String os = System.getProperty("os.name").toLowerCase();
if(os.startsWith("win")){
String registrytype = System.getProperty("sun.arch.data.model");
System.out.println("a rendszered : " +os+" - " +registrytype+ " bites");
if(registrytype.contains("32")){
//Windows 32 bites verzió
System.out.println("Belépett a 32-be");
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:\\Program Files\\VideoLAN\\VLC");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
}else if(registrytype.contains("64")){
//Windows 64 bites verzió
System.out.println("Belépett a 64-be");
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:\\Program Files (x86)\\VideoLAN\\VLC");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
}else{
JOptionPane.showMessageDialog(null, "Kérem előbb telepítse a VLC lejátszót.");
}
}
if(os.startsWith("mac")){
//Mac OSX kiadáshoz
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "/Applications/VLC.app/Contents/MacOS/lib/");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
}
this.setTitle("Aktuális videó");
this.setLayout(new BorderLayout());
mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
this.add(mediaPlayerComponent,BorderLayout.CENTER);
this.setDefaultCloseOperation(this.DISPOSE_ON_CLOSE);
//set the Jframe - this - resolution to the screen resoltuion
new UIBean().setWindowSize(this);
this.setVisible(true);
mediaPlayerComponent.getMediaPlayer().playMedia(videoURL);
}
}
To set an external subtitle file:
mediaPlayerComponent.getMediaPlayer().setSubTitleFile("whatever.srt");
How you add a pause/play button is entirely up to you, it requires standard Swing code that is not particular to vlcj. You add buttons to your user interface, and link those buttons up with the media player by using event listeners. For example, this is one way:
JButton playButton = new JButton("Play/Pause");
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
mediaPlayerComponent.getMediaPlayer.pause();
}
});
There are numerous reasons why the native library might not be found, but NativeLibrary.addSearchPath(...) certainly does work. You have to be sure you match the CPU architectures of your JVM and your VLC installation (32-bit JVM requires 32-bit VLC, 64-bit JVM requires 64-bit VLC). In most cases you should just use:
new NativeDiscovery().discover();
There are a whole bunch of step-by-step tutorials at http://capricasoftware.co.uk/#/projects/vlcj/tutorial
Focusing on the "basic operation interface" aspect of your question, note that EmbeddedMediaPlayerComponent extends Panel, an AWT component. Accordingly, the VLCJ overlay example shown here overrides paint(). This related, stand-alone example illustrates hit testing in such context.

How to convert SWT Image to data URI for use in Browser-widget

I am trying to display images inside a Browser-widget (SWT). These images can be found inside the a jar file (plug-in development). However: this is not directly possible as the browser-widget expects some kind of URL or URI information.
My idea is to turn SWT-images into data-URI values, which I could induce into the src-attribute of every given img-element. I know, that this is not a good solution from a performance point of view, but I don't mind the speed disadvantage.
I'd like to know how to turn a SWT image into a data-URI value for use in a browser-widget.
My code so far:
package editor.plugin.editors.htmlprevieweditor;
import editor.plugin.Activator;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
public class HtmlPreview extends Composite implements DisposeListener {
private final Browser content;
public HtmlPreview(final Composite parent, final int style) {
super(parent, style);
this.setLayout(new FillLayout());
content = new Browser(this, style);
final ImageData imageData = Activator.getImageDescriptor(Activator.IMAGE_ID + Activator.PREVIEW_SMALL_ID).getImageData();
content.setText("<html><body><img src=\"data:image/png;base64," + imageData + "\"/></body></html>"); // need help on changing imageData to a base64-encoded String of bytes?
this.addDisposeListener(this);
}
#Override
public void widgetDisposed(final DisposeEvent e) {
e.widget.dispose();
}
}
Any help is greatly appreciated :)!
Edit 1: I have read SWT Image to/from String , but unfortunately it does not seem to exactly cover my needs.
Edit 2: I don't know if it matters, but I am trying to load a PNG24-image with per-pixel alpha-transparency.
The question is too general if you only say "Browser in SWT". Mozzila browser supports jar URL protocol, and you can do this:
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final URL url = ShellSnippet.class.getResource("/icons/full/message_error.gif");
final Browser browser = new Browser(shell, SWT.MOZILLA);
final String html = String.format("<html><head/><body>image: <img src=\"%s\"/></body></html>", url);
browser.setText(html);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
It looks like this:
I used an image from the JFace jar to keep the snippet simple and yet work for most people out of the box. It is GIF, but I expect it to work just as well with PNG files.
If you use Internet Explorer, something I do not recommend because your application depends on OS version, this does not work. It looks like this (after changing in the snippet the style from SWT.MOZILLA to SWT.NONE):
It does however understand the file protocol and you can copy files to the temp folder and create URLs directly to the file using File.toURL(). This should work for any browser.
I cannot test the simple solution on WEBKIT broswer. If anyone can, please post the result in a comment.

browsing javascript

I want to write a simple web browser in java and here’s my code!
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class WebBrowser extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public JPanel
address_panel, window_panel;
public JLabel
address_label;
public JTextField
address_tf;
public JEditorPane
window_pane;
public JScrollPane
window_scroll;
public JButton
address_b;
private Go go = new Go();
public WebBrowser() throws IOException {
// Define address bar
address_label = new JLabel(" address: ", SwingConstants.CENTER);
address_tf = new JTextField("http://www.yahoo.com");
address_tf.addActionListener(go);
address_b = new JButton("Go");
address_b.addActionListener(go);
window_pane = new JEditorPane("http://www.yahoo.com");
window_pane.setContentType("text/html");
window_pane.setEditable(false);
address_panel = new JPanel(new BorderLayout());
window_panel = new JPanel(new BorderLayout());
address_panel.add(address_label, BorderLayout.WEST);
address_panel.add(address_tf, BorderLayout.CENTER);
address_panel.add(address_b, BorderLayout.EAST);
window_scroll = new JScrollPane(window_pane);
window_panel.add(window_scroll);
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
pane.add(address_panel, BorderLayout.NORTH);
pane.add(window_panel, BorderLayout.CENTER);
setTitle("web browser");
setSize(800,600);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public class Go implements ActionListener{
public void actionPerformed(ActionEvent ae){
try {
window_pane.setPage(address_tf.getText());
} catch (MalformedURLException e) { // new URL() failed
window_pane.setText("MalformedURLException: " + e);
} catch (IOException e) { // openConnection() failed
window_pane.setText("IOException: " + e);
}
}
}
public static void main(String args[]) throws IOException {
WebBrowser wb = new WebBrowser();
}
}
It works fine for simple html pages but it cannot load JavaScript part of the code! My problem is what should I add to the code to load the javascripts? Thank you!
Swing's default widgets only have very basic support for HTML4 and CSS, with absolutely no support for JavaScript at all (by default). You could potentially use the built-in Rhino JavaScript engine to execute the code, but that would have to be done manually and would be pretty difficult. HtmlUnit uses this tactic to parse HTML pages and execute the JavaScript, but it has generally poor compatibility and completely lacks a renderer, so you'd have to write that yourself (i.e. no display, you only get access to the page content from code).
There's a few Swing-based browser widgets floating around which embed a Gecko (Firefox) or WebKit (Chrome/Safari) renderer and would thus be able to take advantage of proper JavaScript interpreters, but they're all buggy, expensive, or unmaintained. These would all support JavaScript but they generally use very old versions of the various browser engines and have poor compatibility with modern websites, in addition to lacking cross-platform compatibility.
Eclipse's SWT project includes a browser widget that appears to be actively maintained, but has a dependence on the SWT libraries and would be somewhat more difficult to use in a Swing application, though it may be possible. SWT is an entirely different UI toolkit from AWT/Swing (which you're currently using) and in order to take advantage of its browser widget, you'd have to find a way to embed it in a Swing app, or use only the SWT toolkit.
Overall, SWT's browser is probably your best bet for getting a decent browser in Java, but it may still be troublesome to use. Good luck!

Java Combo Boxes + Image Icons

I'm trying to build a really basic program that will alternate between two pictures depending on which item from a dropdown box is selected. This is the code I'm trying to run, but I keep getting an error saying:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:181)
at Gui.<init>(Gui.java:10)
at Apples.main(Apples.java:7)
The images are in the src file.
Does anyone know what I am doing wrong??
Thanks,
Ravin
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Gui extends JFrame{
private JComboBox box;
private JLabel picture;
private static String [] filename = {"Ravinsface.png", "Wojs face.png"};
private Icon[] pics = {new ImageIcon(getClass().getResource(filename[0])), new ImageIcon(getClass().getResource(filename[1]))};
public Gui(){
super("The Title");
setLayout(new FlowLayout());
box = new JComboBox(filename);
box.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent event){
if(event.getStateChange()==ItemEvent.SELECTED);
picture.setIcon(pics[box.getSelectedIndex()]);
}
}
);
add(box);
picture = new JLabel(pics[1]);
add(picture);
}
}
Use getClass().getClassLoader().getResource(String)
/e1 I put an explanation of the different getResource(String) methods on the other answer.
It looks like one (or more) of the arguments you are passing into your ImageIcon constructor are null. This is because the resource is not being found here:
private Icon[] pics = {new ImageIcon(getClass().getResource(filename[0])), new ImageIcon(getClass().getResource(filename[1]))};
Why aren't you just using
new ImageIcon(String filename)
? I'm not 100% sure how getResource works, never having used it.
do this:
you must put your .png
beside your .class files
(in project_name/bin)
then your files path can recognize
then it will works
remember you are using class loader so if you put images beside .class files it will be correct

Categories

Resources