I am try to open a javadoc html file with my new application, however I can not get the javadoc file to open, I have a class name OpenUri, which when called is supposed to open the javadoc:
package gui;
import java.awt.Desktop;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import javax.swing.JFrame;
public class OpenUri extends JFrame {
public static void openWebpage(URI uri) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
try {
desktop.browse(uri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void openWebpage(URL url) {
try {
openWebpage(url.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
I am then calling and using this class from another class called Menu, where the help button has an action listener, etc. However when I run the code and press the help button, no javadoc appears, ie, it doesn't open the document, ie, nothing happens, no window, nothing ?
The only way I can open it is manually, by clicking on it in eclipse, here is the specific code from the Menu class I am Using:
//Help
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic(KeyEvent.VK_H);
helpMenu.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
try {
URI uri = new URI("file:///C:/Users/howhowhows/workspace/OPTICS_DROP_MENU/doc/index.html");
OpenUri.openWebpage(uri);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
});
If anyone has any ideas as to what I am doing wrong, ie what I need to add/change, it would be greatly appreciated.
Have you downloaded and tried the demo code from the Swing tutorial on How to Integrate With the Desktop Class.
When I used that code and pasted your URI into the text field no window is displayed and I get a "System cannot find the file" message as expected.
When I then enter a simple URI that I know exists: "c:/java/a.html" the browser opens as expected.
So I suggest you start with known working code and see if your URI works. If it does work then the problem is your code, so compare the working code to your code to see what the difference is. If it doesn't work then the problem is the URI.
If you still have problems then post a proper SSCCE that demonstrates the problem. Given that your OPenURI class extends JFrame for no reason we don't know what other strange things you might be doing in your code.
Related
So, what I am looking is a way to call the values that I saved to preferences class that can be called up with the clicking of a radio button after the user has defined and saved their inputs.
Class File used for saving and then trying to recall the saved data.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class CustomConfig
{
public static Properties prop = new Properties();
public void saveProp(String title, boolean value)
{
try
{
prop.setProperty(title,String.valueOf(value));
prop.store(new FileOutputStream("config.radiobutton"),"");
}
catch(IOException e)
{
}
}
public String getProp(String title)
{
String value = title;
try
{
prop.load(new FileInputStream("config.radiobutton"));
value = prop.getProperty(title);
}
catch(IOException e)
{
}
return value;
}
I am then using the following code to try to call the radio button(s) that have been defined by the user.
private void CustomRadioMouseReleased(java.awt.event.MouseEvent evt) {
con.getProp(CalabrioRadio.getText());
System.out.println(con.getProp(CalabrioRadio.getText()));
}
For good measure here is the text as it was saved initially to the config file...
#
#Sun Mar 05 16:09:26 CST 2017
Calabrio=true
CTIOS\ Soft\ Phone=false
Account\ Services=false
Appease=false
Sales\ Ads\ (VMAG)=false
Place\ Order/Oracle=false
Outlook=false
Order\ Status=false
Kronos=false
Collections\ Account\ Services=false
Daily\ Specials=false
HOD\ /\ CCD=false
Intranet\ (AAFES\ Web\ Portal)=false
MyECP.com=false
ShopMyExchange.com=false
The issue that I am currently having it, that with the above code, I can't seem to actually call the values back in to change the Selected state of my radio buttons. When I run the System.out.Println it will however show the correct information. I am at a loss for what to do at this point as far as getting the buttons to show per the info selected by the user and then saved. Any help on what to do at this point would be greatly appreciated.
Please let me know if any further information is needed.
Okay... So I think I finally managed to stumble through to my own answer. I am going to go ahead and post it just in case anyone is having this issue as well.
So, I am going to re-post everything in the order in which it was originally posted, and will comment out where the changes were made.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class CustomConfig
{
public static Properties prop = new Properties();
public void saveProp(String title, boolean value)
{
try
{
prop.setProperty(title,String.valueOf(value));
prop.store(new FileOutputStream("config.radiobutton"),"");
}
catch(IOException e)
{
}
}
public static boolean getProp(String title) // Modified from Original
{
String value = title;
try
{
prop.load(new FileInputStream("config.radiobutton"));
value = prop.getProperty(title);
}
catch(IOException e)
{
}
return Boolean.parseBoolean(value); // Modified from Original
}
}
Next portion will once again be commented on the modified portions.
private void CustomRadioMouseReleased(java.awt.event.MouseEvent evt) {
CalabrioRadio.setSelected(con.getProp(CalabrioRadio.getText()));
// The above line was changed
System.out.println(con.getProp(CalabrioRadio.getText()));
}
With that said, this is working for me now. So, if anyone else is having this issue, I hope this helps in some way.
I need to write a Java program that opens a PDF file at a named destination. The file test.pdf contains the named destination "DestinationX" on page 2. The program opens the PDF file but does not go to the named destination. How do I get to the named destination?
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class MyLauncher {
static void openFileAtNamedDest(){
if (Desktop.isDesktopSupported()) {
try {
URI myURI = new URI("file:///C:/test.pdf#nameddest=DestinationX");
Desktop.getDesktop().browse( myURI );
} catch (IOException e) {
e.printStackTrace();
}
catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
openFileAtNamedDest();
}
}
According to the spec, the format of your URL is correct. The only question is what application you are actually launching via browse(). I think it acts the same way as if you had double-clicked the file's icon on your desktop: it will launch whatever application is registered as the default handler for PDFs.
Acrobat should be able to handle a URL with a named destination, but other PDF viewers may not support it.
I have been searching everywhere on how to set the icon image in Java, and it always ends up not working or it gives me errors. Here, in my main method is where I put the code:
public static void main(String[] args) {
Game game = new Game();
// This right here!
game.frame.setIconImage(new ImageIcon("/Icon.png").getImage());
game.frame.setResizable(false);
game.frame.setTitle(title);
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
}
My path for the image is "%PROJECT%/res/Image.png" and I just use /Image.png to go ahead and access my res folder (as I have done in other parts of my project) I have even converted it into an icon file, and tried that, but all it decides is to use the default Java icon.
Your problem is often due to looking in the wrong place for the image, or if your classes and images are in a jar file, then looking for files where files don't exist. I suggest that you use resources to get rid of the second problem.
e.g.,
// the path must be relative to your *class* files
String imagePath = "res/Image.png";
InputStream imgStream = Game.class.getResourceAsStream(imagePath );
BufferedImage myImg = ImageIO.read(imgStream);
// ImageIcon icon = new ImageIcon(myImg);
// use icon here
game.frame.setIconImage(myImg);
Use Default toolkit for this
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));
I use this:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
public class IconImageUtilities
{
public static void setIconImage(Window window)
{
try
{
InputStream imageInputStream = window.getClass().getResourceAsStream("/Icon.png");
BufferedImage bufferedImage = ImageIO.read(imageInputStream);
window.setIconImage(bufferedImage);
} catch (IOException exception)
{
exception.printStackTrace();
}
}
}
Just place your image called Icon.png in the resources folder and call the above method with itself as parameter inside a class extending a class from the Window family such as JFrame or JDialog:
IconImageUtilities.setIconImage(this);
The below method works well on Java 7 and above.
JFrame frame = new JFrame("MyAPP");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
frame.setIconImage(ImageIO.read(YourClass.class.getResourceAsStream("/icon.png")));
} catch (IOException ex) {
ex.printStackTrace();
}
frame.setVisible(true);
Park your icon.png image file to /src/main/resources.
I have a Java JApplet that functions perfectly when eclipse runs it but dissapoints in a browser.
The applet is working fine in the browser up to the point at which the only JButton is pressed. At which point, something should happen, but, in the browser, nothing happens at all apart from the button shows it has been pressed. This doesn't happen when eclipse runs it.
Here is the code:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JTextArea;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
public class OverviewGenerator extends JApplet {
int state = 0;
JTextArea label = new JTextArea();
JButton button = new JButton();
String pluginYML;
YamlConfiguration yml = new YamlConfiguration();
String page;
public ActionListener buttonListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(state == 0) {
try {
pluginYML = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
} catch (HeadlessException e1) {
e1.printStackTrace();
} catch (UnsupportedFlavorException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
yml.loadFromString(pluginYML);
} catch (InvalidConfigurationException e1) {
e1.printStackTrace();
}
state = 1;
}else {
generatePage();
Toolkit toolkit = Toolkit.getDefaultToolkit();
Clipboard clipboard = toolkit.getSystemClipboard();
StringSelection strSel = new StringSelection(page);
clipboard.setContents(strSel, null);
state = 0;
}
refreshComponents();
}
};
/**
*
*/
private static final long serialVersionUID = 3470279389867972761L;
public void init() {
makeGui();
}
private void makeGui() {
label.setWrapStyleWord(true);
label.setLineWrap(true);
label.setBackground(Color.CYAN);
label.setEditable(false);
GridLayout layout = new GridLayout();
layout.setRows(2);
layout.setColumns(1);
getContentPane().setLayout(layout);
refreshComponents();
getContentPane().add(label);
getContentPane().add(button);
button.addActionListener(buttonListener);
}
private void refreshComponents() {
if(state==0) {
label.setText("Copy your plugin.yml into the clipboard then press done!");
button.setText("Done");
}else if(state == 1) {
label.setText("Now press the button to copy your template BukkitDev overview into your clipboard!");
button.setText("Copy");
}
}
private void generatePage() {
page = "";
page += "== "+yml.getString("name")+" ==\n";
if(yml.contains("description")) {
page += "\n//"+yml.getString("description")+"//\n\n\n";
}
if(yml.contains("commands")) {
page += "== Commands ==\n";
for(String command : yml.getConfigurationSection("commands").getKeys(false)) {
page += "\n=== "+command+" ===\n\n";
if(yml.contains("commands."+command+".description")) {
page += "//"+yml.getString("commands."+command+".description")+"//\n";
}
if(yml.contains("commands."+command+".usage")) {
page += "Usage: "+yml.getString("commands."+command+".usage")+"\n";
}
}
page += "\n";
}
if(yml.contains("permissions")) {
YamlConfiguration editedYml = new YamlConfiguration();
try {
editedYml.loadFromString(pluginYML.replace(".", "≠"));
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
ConfigurationSection permissions = editedYml.getConfigurationSection("permissions");
page += "== Permissions ==\n";
for(String permission : permissions.getKeys(false)) {
page += "\n=== "+permission.replace('≠', '.')+" ===\n\n";
if(editedYml.contains("permissions."+permission+".description")) {
page += "//"+editedYml.getString("permissions."+permission+".description").replace('≠', '.')+"//\n";
}
}
page += "\n\n\n";
}
page += "//Got any suggestions?//";
}
}
The code above is slightly outdated, I have added in the 'invoke later' code now! I am having trouble showing the Java console but I believe the error may be when the clipboard is accessed.
For security reasons, there are two ways that an applet can access the clip-board.
The applet is digitally signed by the developer, and trusted by the end user.
The applet uses the services of the JNLP API to access the clipboard. That is available in more recent JREs, Sun's 1.6.0_10+, for example.
There is potentially a 3rd way to get data to the applet that involves
having the user paste directly into an HTML form field
then use JS to transfer the data to the applet.
That could be done in a sand-boxed applet, and before the JRE that supports the JNLP API services. OTOH that would mean more clicks for the user, and more setting up.
//Got any suggestions?//
Beyond 'ask a more specific question' I might also suggest:
Enable the Java Console. That information is vital for debugging applets.
Read Copy in sand-boxed app. in 1.6.0_24+ for more details of the problem with clipboard access in applets, and strategies to copy data out of an applet using JS and other techniques.
Oracle released Java 6 Update 24 in February 2011 to remedy 21 vulnerabilities. As part of this security release, the ability to copy & paste from a computer's clipboard into a Java applet has been disabled.
To fix this issue there are 2 solutions:
Create a digital signature for the applet.
Work around: If you do not want to work with the digital signature, add to your java.policy file the following line: permission java.awt.AWTPermission "accessClipboard"
If you want to see an example of Java Applet working with a signed certificate you can looke here (the applet accepts paste action from clipboard which is not allowed to unsigned applets) : http://sqlinform.com/free_online_sw.html
import java.awt.*;
import java.applet.*;
import java.net.*;
/*<applet code=CodeBase width=300 height=300>
</applet>*/
public class CodeBase extends Applet
{
String sn,br;
URL url;
public void start()
{
AppletContext ac=getAppletContext();
url=getCodeBase();
try{
ac.showDocument(new URL(url+"a.html"));
System.out.println("Hello");
// ac.showDocument(new URL("D:Java Programs//Applet//a.html"));
}
catch(MalformedURLException e)
{
showStatus("Url not found");
}
}
}
This code does not show the document of the a.html in applet. When we use AppletContext.showDocument() method then it display the document at the specified URL, but it not worked.
As a first suggestion, change:
ac.showDocument(new URL(url+"a.html"));
To:
ac.showDocument(new URL(url,"a.html"));
But even better, add some sanity checking to the before/after. Something like:
URL urlPlus = new URL(url+"a.html");
System.out.println(urlPlus);
URL urlComma = new URL(url,"a.html");
System.out.println(urlComma);
// ...
That last part is what I refer to as 'sanity check debugging'. It is easier to inspect with an IDE that has a debugger, but failing that use the principle "When in doubt, print out!"