Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Problems creating JApplet

  1. #1
    Member
    Join Date
    Nov 2013
    Posts
    34
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Problems creating JApplet

    Hello,

    Finally I have a working Java Application containing 3 classes: Connection (Connectie), GUI (KretaGUI) and DatabaseActions (Kreta).

    Everything works like a charm but now I have to make a JApplet. And that's where the trouble starts. I play around with it but I just can't get it to work. When I get some layoutstuff in the applet the .ini file can't be read (because an applet doesn't allow file operations).
    This is driving me crazy. It's just part of an exercise that doesn't even get graded but I want to learn and understand how to make a JApplet.

    This is the working code:

    Connection class:
    //Importeer bibliotheken
    import java.io.FileInputStream;
    import java.sql.*;
    import java.util.Properties;
    import javax.swing.JOptionPane;
    // ****************************
     
    public class Connectie {
    	// Definieer private variabelen benodigd voor de connectie
    	private String host;
    	private String user;
    	private String password;
    	private String databasenaam;
     
    	Connection connection;
     
    	public void displaySQLErrors(Exception e) {
    		String error;
    		error = "SQL foutmelding: " + e.getMessage();
    		JOptionPane.showMessageDialog(null, error,"foutmelding",JOptionPane.ERROR_MESSAGE);
    	}
     
    	public Connectie() {
    		// Lees het config.ini bestand in
    		this.LeesIniBestand();
     
    		try {
    			Class.forName("com.mysql.jdbc.Driver").newInstance();
    			}
    		catch(Exception e) {
    			String error = "Niet mogelijk om de driver te laden";
    			JOptionPane.showMessageDialog(null, error,"foutmelding",JOptionPane.ERROR_MESSAGE);
     
    			System.exit(1);
    		}
    		try { // Bouw de connectiestring op
    			connection = DriverManager.getConnection("jdbc:mysql://" + this.host + "/" + 
    		this.databasenaam + "?user=" + this.user + "&password=" + this.password);
    			//String succes = "Er is een connectie met de database";
    			//JOptionPane.showMessageDialog(null, succes,"succes",JOptionPane.INFORMATION_MESSAGE);
    		}
    		catch(Exception e) {
    			displaySQLErrors(e);
    		}
    	}
     
    	public void LeesIniBestand() {
    		try{
    	      Properties p = new Properties();
    	      p.load(new FileInputStream("config.ini")); //Het bestand config.ini staat in de root map van java
    	      //Vul de database variabelen met de gegevens uit het .ini bestand
    	      this.host = p.getProperty("host");
    	      this.user = p.getProperty("user");
    	      this.password = p.getProperty("password");
    	      this.databasenaam = p.getProperty("databasenaam");
     
    	      //Schrijf variabelen naar scherm ter controle
    	      System.out.println("Host = " + p.getProperty("host"));
    	      System.out.println("user = " + p.getProperty("user"));
    	      System.out.println("Password = " + p.getProperty("password"));
    	      System.out.println("databasenaam = " + p.getProperty("databasenaam"));
    	      }
    	    catch (Exception e) {
    	      System.out.println(e);
    	      }
    	    }
    }

    GUI class:
    //Importeer bibliotheken
    import javax.swing.*;
    import java.util.Vector;
    import java.awt.*;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    // ************************************
     
    public class KretaGUI {
    	// In deze class wordt de GUI en alle events (JButton en JList) opgebouwd 
    	JFrame frame;
    	JButton bNieuw;
    	JButton bToevoegen;
    	JButton bBewerken;
    	JButton bWis;
    	JTextField tId;
    	JTextField tNaam_gerecht;
    	JTextField tPrijs;
    	JTextArea tRecept;
    	JTextArea tIngredienten;
    	JLabel lId;
    	JLabel lNaam_gerecht;
    	JLabel lPrijs;
    	JLabel lRecept;
    	JLabel lIngredienten;
    	JList gerechten;
     
    	public KretaGUI(){
    		Kreta kreta = new Kreta();
    		Vector tabel;
    		tabel = kreta.leesAlleGerechten();
     
    		frame = new JFrame("Afhaalmenus");
    		bNieuw = new JButton("Nieuw");
    		bNieuw.addActionListener(new bNieuwListener());
    		bToevoegen = new JButton("Toevoegen");
    		bToevoegen.addActionListener(new bToevoegenListener());
    		bBewerken = new JButton("Bewerken");
    		bBewerken.addActionListener(new bBewerkenListener());
    		bWis = new JButton("Wissen");
    		bWis.addActionListener(new bWisListener());
    		tId = new JTextField(3);
    		tId.setEditable(false); // Het veld ID mag niet handmatig worden aangepast
    		tNaam_gerecht = new JTextField(20);
    		tPrijs = new JTextField(20);
    		tRecept = new JTextArea(5,20);
    		tIngredienten = new JTextArea(5,20);
    		lId = new JLabel("Id:");
    		lNaam_gerecht = new JLabel("Naam:");
    		lPrijs = new JLabel("Prijs:");
    		lRecept = new JLabel("Recept:");
    		lIngredienten = new JLabel("Ingredienten:");
     
    		JPanel panelA = new JPanel(new FlowLayout(FlowLayout.LEFT)); //Plaats de buttons boven in het frame links uitgelijnd
    		JPanel panelB = new JPanel();  // Verzamel de textfields en textareas
    		JPanel panelC = new JPanel(); //JList
    		panelB.setLayout(new BoxLayout(panelB, BoxLayout.Y_AXIS)); //Plaats de labels en invoervelden onder elkaar
     
    		// opmaak JTextArea
    		JScrollPane sRecept = new JScrollPane(tRecept);
    		tRecept.setLineWrap(true);
    		sRecept.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    		sRecept.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
     
    		JScrollPane sIngredienten = new JScrollPane(tIngredienten);
    		tIngredienten.setLineWrap(true);
    		sIngredienten.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    		sIngredienten.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    		// ***************************
     
    		panelA.add(bNieuw);
    		panelA.add(bToevoegen);
    		panelA.add(bBewerken);
    		panelA.add(bWis);
    		panelB.add(lId);
    		panelB.add(tId);
    		panelB.add(lNaam_gerecht);
    		panelB.add(tNaam_gerecht);
    		panelB.add(lPrijs);
    		panelB.add(tPrijs);
    		panelB.add(lRecept);
    		panelB.add(sRecept);
    		panelB.add(lIngredienten);
    		panelB.add(sIngredienten);
     
    		gerechten = new JList(tabel);
    		gerechten.addListSelectionListener(new LijstListener());
    		gerechten.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Er kan maar 1 regel geselecteerd worden in de JList 
    		gerechten.setSelectedIndex(-1); // Geen regel is geselecteerd
    		panelC.add(gerechten);
     
    		frame.getContentPane().add(BorderLayout.NORTH,panelA);
    		frame.getContentPane().add(BorderLayout.WEST,panelB);
    		frame.getContentPane().add(BorderLayout.EAST,panelC);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setSize(600,600);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setVisible(true);
    	}
     
     
    	public static void main(String[] args) {
    		KretaGUI afhaal = new KretaGUI();
    	}
     
     
    	class bNieuwListener implements ActionListener{
    		// Maak alle velden leeg en verwijder de selectie van de JList als er op nieuw wordt geklikt.
    		public void actionPerformed(ActionEvent event){
    			gerechten.clearSelection(); // Zorg ervoor dat er geen recepten meer geselecteerd zijn 
    			tId.setText("");
    			tNaam_gerecht.setText("");
    			tPrijs.setText("");
    			tIngredienten.setText("");
    			tRecept.setText("");
    			tNaam_gerecht.requestFocus(); // Zet de focus in het veld naam
    		}
    	}
     
    	class bBewerkenListener implements ActionListener{
    		public void actionPerformed(ActionEvent event){
    			int Geselecteerd;
    			Geselecteerd = gerechten.getSelectedIndex(); // Bewaar de selectedindex van de JList
    			Kreta kreta = new Kreta();
    			kreta.setNaam_Gerecht(tNaam_gerecht.getText());
    			kreta.setPrijs(tPrijs.getText());
    			kreta.setIngredienten(tIngredienten.getText());
    			kreta.setRecept(tRecept.getText());
    			kreta.bewerkGerecht(Integer.parseInt(tId.getText()));
    			gerechten.setListData(kreta.leesAlleGerechten());
    			gerechten.repaint();
    			gerechten.setSelectedIndex(Geselecteerd); // Selecteer de rij in de JList van het huidige record
    		}
    	}
     
    	class bToevoegenListener implements ActionListener{
    		// Voeg het nieuwe gerecht toe aan de database (insert)
    		public void actionPerformed(ActionEvent event){
    			Kreta kreta = new Kreta();
    			kreta.setNaam_Gerecht(tNaam_gerecht.getText());
    			kreta.setPrijs(tPrijs.getText());
    			kreta.setIngredienten(tIngredienten.getText());
    			kreta.setRecept(tRecept.getText());
    			kreta.nieuwGerecht();
    			// Toon nieuwe menu_id in JTextfield tId
    			tId.setText(kreta.getId() + "");
    			// Vul de JList gerechten met de nieuwe data
    			gerechten.setListData(kreta.leesAlleGerechten());
    			gerechten.repaint();
    			// Indien het nieuwe record aan de tabel is toegevoegd dient de nieuwe regel in de JList geselecteerd te worden
    			int lastIndex = gerechten.getModel().getSize() - 1;
    			if (lastIndex >= 0) {
    				gerechten.setSelectedIndex(lastIndex);
    				}
    		}
    	}
     
    	// Deze Klasse roept wisRecept aan 
    	class bWisListener implements ActionListener{
    		public void actionPerformed(ActionEvent event){
    			Kreta kreta = new Kreta();
    			kreta.wisGerecht(Integer.parseInt(tId.getText()));
    			gerechten.setListData(kreta.leesAlleGerechten());
    			gerechten.repaint();
    			gerechten.clearSelection(); // Zorg ervoor dat er geen recepten meer geselecteerd zijn 
    			tId.setText("");
    			tNaam_gerecht.setText("");
    			tPrijs.setText("");
    			tIngredienten.setText("");
    			tRecept.setText("");
    			tNaam_gerecht.requestFocus(); // Zet de focus in het veld naam
    			;
    		}
    	}
     
    	class LijstListener implements ListSelectionListener
        {
            public void valueChanged(ListSelectionEvent e)
            {
                if (e.getValueIsAdjusting())
                {
                	Kreta kreta = new Kreta();
                    try
                    {
                        int menu_id = Integer.parseInt(((Vector)gerechten.getSelectedValue()).elementAt(0).toString());
                        kreta.leesGerecht(menu_id);
                        //tfdMenuID.setText(getmenu_id() + "");
                        tId.setText(kreta.getId() + "");
                        tNaam_gerecht.setText(kreta.getNaam_Gerecht());
                        tPrijs.setText(kreta.getPrijs());
                        tIngredienten.setText(kreta.getIngredienten());
                        tRecept.setText(kreta.getRecept());
                    }
                    catch(Exception ex)
                    {
                        JOptionPane.showMessageDialog(null, ex.getMessage(), "Fout", JOptionPane.ERROR_MESSAGE);
                    }
                }
             }
        }
    }

    Database stuff class:
    //Importeer bibliotheken
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.util.Vector;
    import java.sql.*;
    // *********************
     
    public class Kreta {
    	// In deze class worden de database bewerkingen uitgevoerd
    	private Connectie con;
    	private Vector vec;
    	private int menu_id;
    	private String naam_gerecht;
    	private String prijs;
    	private String ingredienten;
    	private String recept;
     
    	public void setId(int id){
    		this.menu_id=menu_id;
    	}
     
    	public int getId(){
    		return this.menu_id;
    	}
     
    	public void setNaam_Gerecht(String naam_gerecht){
    		this.naam_gerecht=naam_gerecht;
    	}
     
    	public String getNaam_Gerecht(){
    		return this.naam_gerecht;
    	}
     
    	public void setPrijs(String prijs){
    		this.prijs=prijs;
    	}
     
    	public String getPrijs(){
    		return this.prijs;
    	}
     
    	public void setIngredienten(String ingredienten){
    		this.ingredienten=ingredienten;
    	}
     
    	public String getIngredienten(){
    		return this.ingredienten;
    	}
     
    	public void setRecept(String recept){
    		this.recept=recept;
    	}
     
    	public String getRecept(){
    		return this.recept;
    	}
     
    	public Kreta(){
    		con = new Connectie();
    		vec = new Vector();
    	}
     
    	public Kreta(int menu_id,String naam_gerecht,String prijs,String ingredienten,String recept){
    		this();
    		this.menu_id = menu_id;
    		this.naam_gerecht = naam_gerecht;
    		this.prijs = prijs;
    		this.ingredienten = ingredienten;
    		this.recept = recept;
    	}
     
    	public Vector leesAlleGerechten(){
    		// Maak een vector die alle records uit de tabel afhaalmenus ophaalt.
    		try {
    			Statement statement = con.connection.createStatement();
    			String gget;
    			gget = "SELECT DISTINCT menu_id,naam_gerecht,prijs FROM afhaalmenus;";
     
    			ResultSet rs = statement.executeQuery(gget);
     
    			while (rs.next()){
    				Vector vRow = new Vector<>();
    				for(int x = 1;x <=3;x++){
    					vRow.addElement(rs.getString(x));
    				}
    				vec.add(vRow);
    			}
    		} catch (Exception e) {
    			con.displaySQLErrors(e);
    		}
    		return vec;
    	}
     
    public void leesGerecht(int id){
    	// Lees een record met het meegegeven id uit de tabel afhaalmenus
    		try{
    			PreparedStatement sset = con.connection.prepareStatement("SELECT DISTINCT * FROM afhaalmenus WHERE menu_id = ? ");
    			sset.setInt(1, id);			//Eerste parameter '?' is het menu_id welke wordt toegekend in het eerste stuk van de functie. 
     
    			ResultSet rs = sset.executeQuery();
    			rs.next();
    			this.menu_id = rs.getInt(1);
    			this.naam_gerecht = rs.getString(2);
    			this.prijs = rs.getString(3);
    			this.ingredienten = rs.getString(4);
    			this.recept = rs.getString(5);
    		}catch(Exception e){
    			e.printStackTrace(); // Ik maak gebruik van de printstack om meer informatie te verkrijgen bij een exception
    		}
    	}
     
    public void wisGerecht(int id){
    	// Delete het record met het menu_id id uit de tabel afhaalmenus
    	try {
    		PreparedStatement sset = con.connection.prepareStatement("DELETE FROM afhaalmenus WHERE menu_id = ?");
    		sset.setInt(1, id);			//Eerste parameter '?' is het menu_id welke wordt toegekend in het eerste stuk van de functie. 
    		sset.executeUpdate();
    		}
    	catch (Exception e){
    		e.printStackTrace(); // Ik maak gebruik van de printstack om meer informatie te verkrijgen bij een exception
    		}
    	}
     
    public void nieuwGerecht(){
    	try {
    		// Insert statement opbouwen
    		// Ik maak gebruik van een prepared statement omdat dit veel overzichtelijker werkt
    		// Met Statement.RETURN_GENERATED_KEYS krijg ik de nieuw aangemaakte menu_id terug
    		PreparedStatement sset = con.connection.prepareStatement("INSERT INTO afhaalmenus (naam_gerecht,prijs,ingredienten,recept) VALUES (?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
    		sset.setString(1, this.naam_gerecht);	//Eerste parameter '?' is het naam_gerecht
    		sset.setString(2, this.prijs);			//Tweede parameter '?' is het prijs
    		sset.setString(3, this.ingredienten);	//Derde parameter '?' is het ingredienten
    		sset.setString(4, this.recept);			//Vierde parameter '?' is het recept
    		sset.executeUpdate();
    		ResultSet tableKeys = sset.getGeneratedKeys();
    		tableKeys.next();
    		this.menu_id = tableKeys.getInt(1);
    		}
    	catch (Exception e){
    		e.printStackTrace(); // Ik maak gebruik van de printstack om meer informatie te verkrijgen bij een exception 
    		}
    	}
     
    public void bewerkGerecht(int id) {
    	// Update het geselecteerde record in de tabel afhaalmenus
        try
        {
        	PreparedStatement sset = con.connection.prepareStatement("UPDATE afhaalmenus SET naam_gerecht = ?,prijs = ?,ingredienten = ?,recept = ? " +
        			"WHERE menu_id = ?");
    		sset.setString(1, this.naam_gerecht);	
    		sset.setString(2, this.prijs);			
    		sset.setString(3, this.ingredienten);	
    		sset.setString(4, this.recept);	
    		sset.setInt(5, id);
    		sset.executeUpdate();
        }
        catch(Exception e) 	{
        e.printStackTrace(); // Ik maak gebruik van de printstack om meer informatie te verkrijgen bij een exception
        }
        }
    }

    I would be very gratefull if you guys could show me how to make a JApplet out of this.

    Thanks in advance!!!

    This is a crosspost to Problems creating JApplet


  2. #2
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: Problems creating JApplet

    Quote Originally Posted by bodylojohn View Post
    Everything works like a charm but now I have to make a JApplet. And that's where the trouble starts. I play around with it but I just can't get it to work. When I get some layoutstuff in the applet the .ini file can't be read (because an applet doesn't allow file operations).
    First, use of JDBC in applets is more critical and requires some considerations about security and permissions. Please, read for example:
    Essentials, Part 1, Lesson 7: Database Access and Permissions

    Second:
    new FileInputStream("config.ini")

    This is a file specification on the local file-system. And more important, it's relative to the current directory. What is the directory that is "current" when the JVM, activated by browser, is launched to execute the applet? You don't know for sure ......
    And apart this, an applet can come from an host on internet .... why the applet should expect to find that configuration file on the machine of the user?

    I guess you don't know some basics about applets, so, please understand these things before continue!
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  3. #3
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Problems creating JApplet

    To simplify this part of the exercise (and all future programs you might write), it's important to separate the GUI logic from the business logic. Your business/data/GUI logic is currently very intertwined. I tried to create a simple example of what to do using your code, but separating the GUI from the rest of the rat's nest was more than I was willing to take on. Once this separation exists, coding the option to show it in a JApplet would be as simple as adding the following code:
    public class GUIToApplet extends JApplet
    {
        public void init()
        {  
            KretaGUI content = new KretaGUI();
            setContentPane(content);
        }
     
    } // end class GUIToApplet
    and running it as a JApplet or showing it in a web page. In order for the above code to work, KretaGUI would have to be a java.awt.Container, but that's easily accomplished.

    I don't know how much time you have, but to understand better the 'separation' idea I've proposed, you should study the Model-View-Controller design pattern or architecture.

    This ungraded exercise is forcing you to think in that direction, and that's a good thing, but it would have been nice if they'd have helped you down that path a bit by giving you some design guidelines before you started coding. Shaping what you have now into separable classes will take some time and might be a frustrating activity. But then, what else do you have to do?

  4. #4
    Member
    Join Date
    Nov 2013
    Posts
    34
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Problems creating JApplet

    Quote Originally Posted by GregBrannon View Post
    To simplify this part of the exercise (and all future programs you might write), it's important to separate the GUI logic from the business logic. Your business/data/GUI logic is currently very intertwined. I tried to create a simple example of what to do using your code, but separating the GUI from the rest of the rat's nest was more than I was willing to take on. Once this separation exists, coding the option to show it in a JApplet would be as simple as adding the following code:
    public class GUIToApplet extends JApplet
    {
        public void init()
        {  
            KretaGUI content = new KretaGUI();
            setContentPane(content);
        }
     
    } // end class GUIToApplet
    and running it as a JApplet or showing it in a web page. In order for the above code to work, KretaGUI would have to be a java.awt.Container, but that's easily accomplished.

    I don't know how much time you have, but to understand better the 'separation' idea I've proposed, you should study the Model-View-Controller design pattern or architecture.

    This ungraded exercise is forcing you to think in that direction, and that's a good thing, but it would have been nice if they'd have helped you down that path a bit by giving you some design guidelines before you started coding. Shaping what you have now into separable classes will take some time and might be a frustrating activity. But then, what else do you have to do?
    Dear GregBrannon.... Thank you very much for your very detailed and helpfull information.
    This thing is just killing me.

    I really thought that I separated all of the gui stuff in the KretaGUI class. Apparently not. The thing that bugs me is that I created this application and it does what it needs to do. EXCEPT the applet stuff.

    But I quess I have to start from scratch.
    I will look at the information you supplied.

    Thanks again for taking your time in helping me!

    --- Update ---

    Quote Originally Posted by andbin View Post
    First, use of JDBC in applets is more critical and requires some considerations about security and permissions. Please, read for example:
    Essentials, Part 1, Lesson 7: Database Access and Permissions

    Second:
    new FileInputStream("config.ini")

    This is a file specification on the local file-system. And more important, it's relative to the current directory. What is the directory that is "current" when the JVM, activated by browser, is launched to execute the applet? You don't know for sure ......
    And apart this, an applet can come from an host on internet .... why the applet should expect to find that configuration file on the machine of the user?

    I guess you don't know some basics about applets, so, please understand these things before continue!
    Dear andbin: Thank you for your help. I will look into this later.

  5. #5
    Member
    Join Date
    Nov 2013
    Posts
    34
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Problems creating JApplet

    GregBrannon: Could you please give me a little push in helping me to devide the code in business/data/GUI.
    Because I just don't see it.

    Thanks in advance!

    --- Update ---

    Finally...I have got my applet working...The only thing that doesnt work is reading the .ini file (java.io.FileNotFoundException: config.ini (The system cant find the file))

    However its part of the assignment to read the database settings from an .ini file.

    I hope I can finally complete mt assignement.

Similar Threads

  1. Can I set the contentPane of JF to be JApplet?
    By javapenguin in forum Java Applets
    Replies: 1
    Last Post: May 23rd, 2012, 11:07 PM
  2. NEED HELP! Beginner JApplet Problems
    By bam0792 in forum AWT / Java Swing
    Replies: 4
    Last Post: February 20th, 2012, 02:52 PM
  3. Animation in JApplet
    By Aurin in forum What's Wrong With My Code?
    Replies: 3
    Last Post: January 14th, 2012, 10:18 AM
  4. Sockets in JApplet
    By shrey.haria in forum Java Networking
    Replies: 4
    Last Post: September 5th, 2011, 09:45 AM