Why my program works on JFrame but not on JApplet? - java

I've got a project in Java (developped with Eclipse), in which I use some Swing components. At the start, I worked with JFrame : I created a new class herited from JPanel (PanelTr), added in it my JLabels, JTextField and JButton with an ActionListener on my button, and added an object PanelTr to my JFrame-herited class. Here's a piece of my code :
package gui;
public class PanelTr extends JPanel implements ActionListener {
// Here I instantiate my JTextField and JButton used by ActionListener
private JTextField textCap = new JTextField(20);
private JButton submitButton = new JButton("Submit");
public PanelTr() {
// Here I add my JLabels and my layout manager
submitButton.addActionListener(this);
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource()==submitButton)
{
JOptionPane.showMessageDialog(null,"DEBUG"); // Just to see if it is displayed
String err = Analyzer.process(textCap.getText().toString()); // An analyzing process I use in my program
if (err=="")
{
JOptionPane.showMessageDialog(null,"OK");
}
else
{
JOptionPane.showMessageDialog(null,err,"Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}
And my JFrame :
package gui;
public class FrameTr extends JFrame
{
public FrameTr()
{
PanelFils ctn = new PanelFils(); //Conteneur
setContentPane(ctn);
ctn.setBackground(new Color(0,255,255));
setTitle("Project");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String args[])
{
new FrameTr();
}
}
In my Analyzer class, I use several Excel files located in the root folder of my project.
So with this code, my program runs well, on Eclipse and when I export it into a runnable jar (I place my Excel files in the same folder of my .jar file).
But now I need to make an Applet which allows the program to run on a web browser. So I created a new JApplet-based class with just this code :
package gui;
public class TestApplet extends JApplet{
public void init()
{
PanelTr ctn = new PanelTr();
setContentPane(ctn);
}
}
When I run this class on Eclipse, my debug JOptionPane is displayed, but in the analyzing process I get a FileNotFoundException on my first Excel File. I tried to move it to the src folder, to the gui folder, even to the analyse folder (package of my Analyzer class), but still this FileNotFoundException...
I also tried to run my program in a webpage, so I exported as a runnable jar (Note : I couldn't choose TestApplet in my launch configuration since it doesn't have a main(), so I choosed FrameTr). I used the tag :
<applet archive="app.jar" width="700" height="100" code="gui/TestApplet.class"/>
My pane is displayed, but when I click on my button, the debug JOptionPane doesn't pop out !
So first, how can I solve the FileNotFound problem ? And then, why my JOptionPane isn't displayed on my web browser ?

Applets are restricted and can't access File System (with exception for signed applets).
If the files inside your jar you can use them as resource. Instead of using e.g. FileInputStream use this.getClass().getResourceAsStream("/Countries.xlsx") (the Countries.xlsx should be in the root)

The Java Applet is executed client side - it runs on the computer of the person using the website. It does not run on the web server.
If you have files in the server then the client will not be able to access them unless you serve them up from your web server and access them via HTTP(S).
If the value in the files are constants then you should put the files inside your JAR and distribute them as part of the Applet.

Related

Java Swing Icon wont show up [duplicate]

I tried this way, but it didnt changed?
ImageIcon icon = new ImageIcon("C:\\Documents and Settings\\Desktop\\favicon(1).ico");
frame.setIconImage(icon.getImage());
Better use a .png file; .ico is Windows specific. And better to not use a file, but a class resource (can be packed in the jar of the application).
URL iconURL = getClass().getResource("/some/package/favicon.png");
// iconURL is null when not found
ImageIcon icon = new ImageIcon(iconURL);
frame.setIconImage(icon.getImage());
Though you might even think of using setIconImages for the icon in several sizes.
Try putting your images in a separate folder outside of your src folder. Then, use ImageIO to load your images. It should look like this:
frame.setIconImage(ImageIO.read(new File("res/icon.png")));
Finally I found the main issue in setting the jframe icon. Here is my code. It is similar to other codes but here are few things to mind the game.
this.setIconImage(new ImageIcon(getClass().getResource("Icon.png")).getImage());
1) Put this code in jframe WindowOpened event
2) Put Image in main folder where all of your form and java files are created e.g.
src\ myproject\ myFrame.form
src\ myproject\ myFrame.java
src\ myproject\ OtherFrame.form
src\ myproject\ OtherFrame.java
src\ myproject\ Icon.png
3) And most important that name of file is case sensitive that is icon.png won't work but Icon.png.
this way your icon will be there even after finally building your project.
This works for me.
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(".\\res\\icon.png"));
For the export jar file, you need to configure the build path to include the res folder and use the following codes.
URL url = Main.class.getResource("/icon.png");
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(url));
Yon can try following way,
myFrame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));
Here is the code I use to set the Icon of a JFrame
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
try{
setIconImage(ImageIO.read(new File("res/images/icons/appIcon_Black.png")));
}
catch (IOException e){
e.printStackTrace();
}
Just copy these few lines of code in your code and replace "imgURL" with Image(you want to set as jframe icon) location.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create the frame.
JFrame frame = new JFrame("A window");
//Set the frame icon to an image loaded from a file.
frame.setIconImage(new ImageIcon(imgURL).getImage());
I'm using the following utility class to set the icon for JFrame and JDialog instances:
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Scanner;
public class WindowUtilities
{
public static void setIconImage(Window window)
{
window.setIconImage(Toolkit.getDefaultToolkit().getImage(WindowUtilities.class.getResource("/Icon.jpg")));
}
public static String resourceToString(String filePath) throws IOException, URISyntaxException
{
InputStream inputStream = WindowUtilities.class.getClassLoader().getResourceAsStream(filePath);
return toString(inputStream);
}
// http://stackoverflow.com/a/5445161/3764804
private static String toString(InputStream inputStream)
{
try (Scanner scanner = new Scanner(inputStream, "UTF-8").useDelimiter("\\A"))
{
return scanner.hasNext() ? scanner.next() : "";
}
}
}
So using this becomes as simple as calling
WindowUtilities.setIconImage(this);
somewhere inside your class extending a JFrame.
The Icon.jpg has to be located in myproject\src\main\resources when using Maven for instance.
I use Maven and have the structure of the project, which was created by entering the command:
mvn archetype:generate
The required file icon.png must be put in the src/main/resources folder of your maven project.
Then you can use the next lines inside your project:
ImageIcon img = new ImageIcon(getClass().getClassLoader().getResource("./icon.png"));
setIconImage(img.getImage());
My project code is as below:
private void setIcon() {
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/slip/images/cage_settings.png")));
}
frame.setIconImage(new ImageIcon(URL).getImage());
/*
frame is JFrame
setIcon method, set a new icon at your frame
new ImageIcon make a new instance of class (so you can get a new icon from the url that you give)
at last getImage returns the icon you need
it is a "fast" way to make an icon, for me it is helpful because it is one line of code
*/
public FaceDetection() {
initComponents();
//Adding Frame Icon
try {
this.setIconImage(ImageIO.read(new File("WASP.png")));
} catch (IOException ex) {
Logger.getLogger(FaceDetection.class.getName()).log(Level.SEVERE, null, ex);
}
}'
this works for me.

Is it possible to use a FileDialog from inside an Intellij Plugin?

Similar to this answer, when using a file dialog, you need to pass in a JFrame.
I have a button on a JPanel inside a ConfigurableUI Menu, and would like to open a file dialog when clicking it. This file dialog needs to load in a file or directory outside of the project and plugins resource folders... e.g /root/path/to/file.xyz
I've tried to go to the root pane like so, but it returns a Window object instead.
public class MyConfigurableUI implements ConfigurableUi<MyPlugin> {
JPanel panel;
...
public void pressButtonAction(){
//This doesnt work
//JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(panel);
FileDialog fd = new FileDialog(panel, "Choose a file", FileDialog.LOAD);
//How do I get the JFrame to pass in?
}
#NotNull
#Override
public JComponent getComponent() {
return panel;
}
}
I have looked in the code samples and have not found an example using a file dialog.
**Edit:**
Using the answer below I was able to open a file with the following code:
FileChooserDescriptor fcDesc = new FileChooserDescriptor(true,false,false,false,false,false);
FileChooserDialog fcDial = FileChooserFactory.getInstance().createFileChooser(fcDesc, null, null);
VirtualFile[] files = fcDial.choose(null);
//do something with the path
doSomething(files[0].getPath());
Please use builtin com.intellij.openapi.fileChooser.FileChooserFactory

Jpanel does not display what it supposes to

I have created a class that extends JPanel using eclipse, now i added this class to netbeans through creating a new JFrame and dragging this class to the Jframe using the Netbeans designer. now at run time, the Camera stream do not show on the jpanel despite the same code was runnning in eclipse.
is there any attribute i ahve to modify its value in the netbeans designer to get the jpanel working?
Code:
private static class CamThreadRun implements Runnable {
#Override
public void run() {
camStream();
}
}
private static void camStream() {
while(vidCap.grab()) {
grappedMat = new Mat();
vidCap.retrieve(grappedMat);
if (!grappedMat.empty()) {
BufferedImage buffImg = mat2BufferedImage(grappedMat);
if (buffImg != null) {
facePanel.setFace(buffImg);
facePanel.repaint();
}
}
}
}
Can't remember exactly but Netbeans creates some kind of .form file that doesn't get recognised in eclipse. It's best to design it yourself with the code as it will work on both IDEs instead of using Netbeans GUI designer which works best for Netbeans.

Method called in constructor is not working after built in java netbeans

Here while I run java project in netbeans all things are working okay. But after they are built there is not any item added in combobox as it works during netbeans run. The sample code is given below.
First Login JFrame
public class Login_Frame extends javax.swing.JFrame {
welcome w = new welcome();
public Login_Frame() {
initComponents();
}
//button action perform event for dispose this window and open new welcome window
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
.
.
w.setVisible(true);
this.dispose();
.
.
}
}
Second JFrame
public final class welcome extends javax.swing.JFrame {
// comboitem is class in which method for adding item in combobox from sqlite
db is declared
comboitem c = new comboitem();
// textclass is class in which method for changing lowercase text entered in
text to uppercase is declared
textclass tc = new textclass();
public welcome() {
// while I try to run the project using netbeans run project option
// logincall() method initialized and work fine.
Problem
After project built when I try to run the jar file from the cmd. it runs without any
error but logincall() method doesn't work or may be not initialized.
initComponents();
logincall();
.
.
}
public void logincall(){
//Remarks
//tc.uppercase() method is working fine after built. But other c.but_stn() like
// doen't.while during running project through netbeans all thing working fine.
c.bus_stn();
c.bus_trl();
c.inq_stn();
c.editframe();
c.userlist();
c.editTrainStation();
c.editFlightStation();
c.flightFlight();
c.pickupstand();
tc.uppercase();
}
I didn't know what is wrong with it. I searched on google but didn't find any proper answer.
There also any error showing up in netbeans. Please fill free to ask any questions if more information is needed. I appreciate all your replies.
This is my Welcome Main class's main method.
public static void main(String args[]) {
...
look and feel auto generated code
....
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new welcome().setVisible(true);
}
});
}
A couple of things that might be an issue here:
1) Are you running your GUI on the EventDispatchThread? this is mandatory for java swing GUI to be able to work properly. The main reason for this is concurrency. Details here.
2) Are you re-rendering your combobox? it is important that you do this because changes to GUI elements may not be immediately shown.
3) What Database are you using? in order to determine if the fault lies in the code or the DB you could write a test using static data, if it loads in the IDE and outside of it chances are that your code is correct but the DB isn't

combobox selection won't load/initialize class in a new window

SEE UPDATE AT THE BOTTOM!!
I've tried to figured out how to do this for a couple of days but so far I have had no luck.
Basically what I want to do is have a combobox, which when an option is selected loads an applet, and passes a value to the applet.
Here is the code for the ComboBox class, which is supposed to open the other class in a new window. The other class is the main class for an applet. They are both in the same project but in different packages. I know that there aren't any errors with the rest of the code.
//where I evaluate the selection and then open SteadyStateFusionDemo
// more selections just showing one code block
combo.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
String str = (String)combo.getSelectedItem();
if (str.equals("NSTX")) {
machine = "A";
JFrame frame = new JFrame ("MyPanel2");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
SteadyStateFusionDemo d = new SteadyStateFusionDemo();
frame.getContentPane().add (new SteadyStateFusionDemo());
d.init();
frame.pack();
frame.setVisible (true);
And just to cover everything here is the beginning of the init() method of SteadyStateFusionDemo as well as the main method in the class. Too much code to post otherwise. There are several different privates before the init method.
//method that initializes Applet or SteadyStateFusionDemo class
public void init() {
//main method of the SteadyStateFusionDemo class
public static void main (String[] args) {
JFrame frame = new JFrame ("MyPanel");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new SteadyStateFusionDemo());
frame.pack();
frame.setVisible (true);
What am I doing wrong? Why doesn't my class load?
UPDATED: Changed the code so that a JFrame opens and then the JApplet loads inside. I have successfully done this in a test Java applet but for some odd reason it won't work with this Applet. I even set up the test in a similar way (The code for this is virtually the same, except with different class names, and of course a much, much shorter init() method). Can someone help me figure out why this isn't working? Also, a JFrame will open if I delete the lines referring to SteadyStateFusionDemo, but once I reference it won't work. Why does this happen?
UPDATE:
Based on your feedback, it seems you are trying to achieve the following:
Use the code of an existing Applet (found here) in a Desktop application (i.e. in a JFrame).
Converting an Applet to a Desktop application is an "undertakable" task, the complexity of which depends on how much "Applet-specific" stuff is used by the Applet. It can be as simple as creating a JFrame and adding myFrame.setContentPane(new myApplet().getContentPane()); or as complex as...hell.
This tutorial might be a good place to start.
After taking a look at the Applet at hand, it seems to be fairly easy to convert it. The only complicating factor is the use Applet's methods getCodeBase() and getImage(URL) (somewhere in the code). These two methods result in a NullPointerException if the Applet is not deployed as...an Applet.
So, what you can do is override those two methods in order to return the intended values (without the exception). The code could look like this:
/* Import the necessary Applet entry-point */
import ssfd.SteadyStateFusionDemo;
/* Subclass SSFD to override "problematic" methods */
SteadyStateFusionDemo ssfd = new SteadyStateFusionDemo() {
#Override
public URL getCodeBase() {
/* We don't care about the code-base any more */
return null;
}
#Override
public Image getImage(URL codeBase, String imgPath) {
/* Load and return the specified image */
return Toolkit.getDefaultToolkit().getImage(
this.getClass().getResource("/" + imgPath));
}
};
ssfd.init();
/* Create a JFrame and set the Applet as its ContentPane */
JFrame frame = new JFrame();
frame.setContentPane(ssfd);
/* Configure and show the JFrame */
...
The complete code for an example JFrame Class can be found here.
Of course, you need to have all Classes from the original Applet accessible to your new Class (e.g. put the original Applet in your classpath).

Categories