Results 1 to 14 of 14
  1. #1
    maik89 is offline Member
    Join Date
    Nov 2015
    Posts
    6
    Rep Power
    0

    Question How to refresh JPanel to see new Data from DB?

    Hi Guys

    This is my first post to I'd like to say "Hello World"!
    As above how to refresh JPanel? I'm getting data from DB and after I add new entry in DB every time i want to see new entry in JComboBox or JCheckBox ect. i need to close and open again my Jar.
    Is it way to refresh automatically after adding new DB entry or by "refresh button"?
    I don't add any code cause this is general question, but if code needed I will add just say what u need.

    Thx in advance!
    Maik
    Last edited by maik89; 11-22-2015 at 02:28 PM.

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: How to refresh JPanel to see new Data from DBl?

    Did you update the JPanel on the EDT?
    Did you call the repaint() method?
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    maik89 is offline Member
    Join Date
    Nov 2015
    Posts
    6
    Rep Power
    0

    Default Re: How to refresh JPanel to see new Data from DBl?

    I'm beginner and don't even know what EDT is :P

    repaint() or revalidate() don't work.

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: How to refresh JPanel to see new Data from DBl?

    Do an internet search on EDT (event dispatch thread).
    See the tutorial: The Event Dispatch Thread (The Java™ Tutorials > Creating a GUI With JFC/Swing > Concurrency in Swing)


    There are also lots of ways for a program to fail doing what you want or expect. Without seeing the code it isn't possible to see what the problem is.
    Last edited by Norm; 11-22-2015 at 04:56 PM.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    maik89 is offline Member
    Join Date
    Nov 2015
    Posts
    6
    Rep Power
    0

    Default Re: How to refresh JPanel to see new Data from DBl?

    Quote Originally Posted by Norm View Post
    Do an internet search on EDT (event dispatch thread).
    See the tutorial: The Event Dispatch Thread (The Java™ Tutorials > Creating a GUI With JFC/Swing > Concurrency in Swing)


    There are also lots of ways for a program to fail doing what you want or expect. Without seeing the code it isn't possible to see what the problem is.
    I think i know where the problem is, correct me if I'm wrong...

    In my main public class i got declared
    Java Code:
    public class Feeder extends JFrame implements ActionListener{
    		DB data= new DB("Products");
    and JComboBox
    Java Code:
    JCheckBox cpos[] = new JCheckBox[data.howManyRecords()];
    And after that i use this "data" object to add new JComboBox. What I'm thinking data and cpos[] are unchanged till next reload. Is it correct?

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: How to refresh JPanel to see new Data from DBl?

    Sorry, those 2 lines of code don't show what the problem is.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    maik89 is offline Member
    Join Date
    Nov 2015
    Posts
    6
    Rep Power
    0

    Default Re: How to refresh JPanel to see new Data from DBl?

    Quote Originally Posted by Norm View Post
    Sorry, those 2 lines of code don't show what the problem is.
    I'm just learning so don't expect much...
    Here is code... Unfortunately it is not in English ( i know i make mistake and i gonna sort it later on ... )

    Here there is as well runnable JAR


    DB
    Java Code:
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Random;
    
    
    public class DBtest {
    
    private Connection con;
    private Statement st;
    private ResultSet rs;
    	
    	public DBtest(String whichDataBase){
    	try {
    		Class.forName("com.mysql.jdbc.Driver");
    //			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+whichDataBase+"?characterEncoding=UTF-8","monty","some_pass");
    			con = DriverManager.getConnection("jdbc:mysql://109.157.79.228/"+whichDataBase+"?characterEncoding=UTF-8","monty","some_pass");
    		st = con.createStatement();
    	} catch (Exception e) {
    		e.printStackTrace(); 
    	}
    	
    }
    	
    	
    	public Produkt wybierzProdukt(int id){	
    		Produkt Wynik=null;
    		try {
    			String query="select * from  produkt WHERE id="+id;
    			rs=st.executeQuery(query);
    			
    			while(rs.next()){
    				
    				Wynik=new Produkt(rs.getString("NazwaProduktu"),rs.getDouble("Kalorycznosc"),rs.getDouble("ZawBialka"),rs.getDouble("ZawTluszczu"),rs.getDouble("ZawWeglowodanow"),rs.getDouble("ZawBlonnika"),0,0,0);
    			}
    		} catch (Exception e) {
    			System.out.println("Nie udało sie pobrac produktu. "+e);
    		}
    		return Wynik;
    	}	
    	
    	
    	
    	public int policzWiersze(String jakaTabela, String jakaKolumna) {
    		 int sizeDataPredicted = 0;
    		try {
    			String query="SELECT COUNT(*) AS "+jakaKolumna+" FROM "+jakaTabela;
    			rs=st.executeQuery(query);
    			
    			  while (rs.next()){
    	                sizeDataPredicted = rs.getInt(jakaKolumna);
    	                
    			}
    		} catch (Exception e) {
    			System.out.println("Nie udało sie policzyc elementow "+e);
    		}
    		return  sizeDataPredicted;
    	}
    	
    
    	public int[] wyborPosilku(int ile_elementow,int id_posilku) {
    	int tb[]= new int[ile_elementow];
    		try {
    			String query="SELECT * FROM posilki"+ile_elementow+" WHERE id_posilku='"+id_posilku+"'";
    			rs=st.executeQuery(query);
    			  while (rs.next()){
    				  for (int i = 0; i < tb.length; i++) {
    					tb[i]=rs.getInt("Sklad"+Integer.toString(i+1)); 
    				}
    			}
    		} catch (Exception e) {
    			System.out.println("Nie udało sie wybrac posiłku "+e);
    		}
    		return tb;
    	}
    	
    	public int[][] wyborPosilku(int ile_elementow) {
    		int tb[][]= new int[this.ilePosilkow(ile_elementow)][ile_elementow];
    			try {
    				String query="SELECT * FROM posilki"+ile_elementow;
    				rs=st.executeQuery(query);
    				int j=0;
    				  while (rs.next()){
    					  for (int i = 0; i < tb[j].length; i++) {
    						tb[j][i]=rs.getInt("Sklad"+Integer.toString(i+1)); 
    					  }
    					  j++;
    					  }
    			} catch (Exception e) {
    				System.out.println("Nie udało sie wybrac posiłku "+e);
    			}
    			return tb;
    		}	
    
    
    	public void dodajProdukt(Produkt tabela[]) {
    	
    	for (int i = 0; i < tabela.length; i++) {
    	    String  sql = "INSERT INTO `posilki`.`produkt` (`id`, `NazwaProduktu`, `Kalorycznosc`, `ZawBialka`, `ZawTluszczu`, `ZawWeglowodanow`, `ZawBlonnika`, `WagaMin`, `WagaMax`, `WagaSkok`) VALUES (NULL, "+
    	"'"+tabela[i].nazwaProduktu+"',"+
    	"'"+tabela[i].kaloryczność+"',"+
    	"'"+tabela[i].zawartośćBiałka+"',"+
    	"'"+tabela[i].zawartośćTłuszczu+"',"+
    	"'"+tabela[i].zawartośćWęglowodanw+"',"+
    	"'"+tabela[i].zawartośćBłonnika+"',"+
    	"'"+tabela[i].wagaMin+"',"+
    	"'"+tabela[i].wagaMax+"',"+
    	"'"+tabela[i].wagaSkok+"');";
    	      try {
    			st.executeUpdate(sql);
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	      System.out.println("Dodano "+tabela[i].nazwaProduktu);
    	}
    	}
    	
    	public void dodajProdukt(Produkt nowy) {
    		
    			String  sql = "INSERT INTO `posilki`.`produkt` (`id`, `NazwaProduktu`, `Kalorycznosc`, `ZawBialka`, `ZawTluszczu`, `ZawWeglowodanow`, `ZawBlonnika`, `WagaMin`, `WagaMax`, `WagaSkok`) VALUES (NULL, "+
    					"'"+nowy.nazwaProduktu+"',"+
    					"'"+nowy.kaloryczność+"',"+
    					"'"+nowy.zawartośćBiałka+"',"+
    					"'"+nowy.zawartośćTłuszczu+"',"+
    					"'"+nowy.zawartośćWęglowodanw+"',"+
    					"'"+nowy.zawartośćBłonnika+"',"+
    					"'"+nowy.wagaMin+"',"+
    					"'"+nowy.wagaMax+"',"+
    					"'"+nowy.wagaSkok+"');";
    			try {
    				st.executeUpdate(sql);
    			} catch (SQLException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			System.out.println("Dodano "+nowy.nazwaProduktu);
    	
    }
    
    	public void dodajPosilki(int s1, int s2, int s3, int s4, int s5, int s6, int s7) {
    String sql="INSERT INTO `posilki`.`posilki7` (`id_posilku`, `Sklad1`, `Sklad2`, `Sklad3`, `Sklad4`, `Sklad5`, `Sklad6`, `Sklad7`) VALUES (NULL, '"+
    s1+"', '"+s2+"', '"+s3+"', '"+s4+"', '"+s5+"', '"+s6+"', '"+s7+"')";
    try {
    	st.executeUpdate(sql);
    } catch (SQLException e) {
    	// TODO Auto-generated catch block
    	e.printStackTrace();
    }
    	
    	
    }
    
    	public void dodajPosilki(int s1, int s2, int s3, int s4, int s5, int s6) {
    String sql="INSERT INTO `posilki`.`posilki6` (`id_posilku`, `Sklad1`, `Sklad2`, `Sklad3`, `Sklad4`, `Sklad5`, `Sklad6`) VALUES (NULL, '"+
    s1+"', '"+s2+"', '"+s3+"', '"+s4+"', '"+s5+"', '"+s6+"')";
    try {
    	st.executeUpdate(sql);
    } catch (SQLException e) {
    	// TODO Auto-generated catch block
    	e.printStackTrace();
    }
    
    }
    
    	public void dodajPosilki(int s1, int s2, int s3, int s4, int s5) {
    String sql="INSERT INTO `posilki`.`posilki5` (`id_posilku`, `Sklad1`, `Sklad2`, `Sklad3`, `Sklad4`, `Sklad5`) VALUES (NULL, '"+
    s1+"', '"+s2+"', '"+s3+"', '"+s4+"', '"+s5+"')";
    try {
    	st.executeUpdate(sql);
    } catch (SQLException e) {
    	// TODO Auto-generated catch block
    	e.printStackTrace();
    }
    }
    
    	public void dodajPosilki(int s1, int s2, int s3, int s4) {
    String sql="INSERT INTO `posilki`.`posilki4` (`id_posilku`, `Sklad1`, `Sklad2`, `Sklad3`, `Sklad4`) VALUES (NULL, '"+
    s1+"', '"+s2+"', '"+s3+"', '"+s4+"')";
    try {
    	st.executeUpdate(sql);
    } catch (SQLException e) {
    	// TODO Auto-generated catch block
    	e.printStackTrace();
    }
    }
    
    	public void usunPosilek(int ile_elementow, int id) {
    		String sql="DELETE FROM `posilki`.`posilki"+ile_elementow+"` WHERE `posilki"+ile_elementow+"`.`id_posilku` ="+id;
    		try {
    			st.executeUpdate(sql);
    			System.out.println("Usunięto");
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		}
    	
    
    	
    	public Posilek[] pobierzPosilek(int tablica[][]){		
    		Produkt tab[][] = new Produkt[tablica.length][7];
    		try {
    			int licznik=0;
    			for (int j = 0; j < tablica.length; j++) {
    			for (int i = 0; i < tablica[j].length; i++) {
    			String query="select * from  produkt WHERE id="+tablica[j][i];
    			rs=st.executeQuery(query);
    			while(rs.next()){
    				tab[j][i] = new Produkt(rs.getString("NazwaProduktu"),
    										rs.getDouble("Kalorycznosc"), 
    										rs.getDouble("ZawBialka"), 
    										rs.getDouble("ZawTluszczu"), 
    										rs.getDouble("ZawWeglowodanow"), 
    										rs.getDouble("ZawBlonnika"), 
    										rs.getDouble("WagaMin"), 
    										rs.getDouble("WagaMax"), 
    										rs.getDouble("WagaSkok"));
    			licznik++;
    			}
    			}
    			}
    		} catch (Exception e) {
    			System.out.println("Nie udało sie pobrac posilku. "+e);
    		}
    		Posilek ret[]=new Posilek[tablica.length];
    				
    				for (int i = 0; i < ret.length; i++) {
    					ret[i]= new Posilek(tab[i]);
    				} 
    		return ret;
    	}
    
    	public int ilePosilkow(){
    			 int sizeDataPredicted = 0;
    				try {
    					for (int i = 4; i <= 7; i++) {
    					String query="SELECT COUNT(*) AS posilki FROM posilki"+i;
    					rs=st.executeQuery(query);
    					int ile=0;
    					  while (rs.next()){
    			                ile = rs.getInt("posilki");
    					}
    					  sizeDataPredicted+=ile;}
    				} catch (Exception e) {
    					System.out.println("Nie udało sie policzyc elementow "+e);
    				}
    				return  sizeDataPredicted;
    		}
    	
    	public int ilePosilkow(int ile_elementow){
    		int sizeDataPredicted=0;
    		try {
    				String query="SELECT COUNT(*) AS posilki FROM posilki"+ile_elementow;
    				rs=st.executeQuery(query);
    				while (rs.next()){
    					sizeDataPredicted = rs.getInt("posilki");
    				}
    		} catch (Exception e) {
    			System.out.println("Nie udało sie policzyc elementow "+e);
    		}
    		return  sizeDataPredicted;
    	}
    	
    	
    		
    
    }
    main
    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Button;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.sql.SQLException;
    import java.sql.Time;
    
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.ButtonGroup;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JScrollPane;
    import javax.swing.JSlider;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    import javax.swing.UIManager;
    import javax.swing.UIManager.LookAndFeelInfo;
    import javax.swing.border.TitledBorder;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    
    	public class Feed extends JFrame implements ActionListener{
    		DBtest baza = new DBtest("posilki");
    		
    		JPanel jp1,jp2,jp3,jp4,jp5,jp6,jp7,jp8,jp9,pon,wt,sr,czw,pt,sob,niedz,posileczki;
    		
    		JScrollPane scrollPane1,scrollPane2,scrollPane3,scrollPane4,scrollPane5,scrollPane6,scrollPane7;
    		
    		Posilek pos[] = new Posilek[baza.ilePosilkow()];
    		
    		JCheckBox cpos[] = new JCheckBox[baza.ilePosilkow()];
    		
    		JButton przycisk,przyciskDieta, przyciskUstawienia,dodajPosilek, dodajProdukt,dodajSkładnik,usunSkładnik;
    		
    		JCheckBox rd[] = new JCheckBox[baza.policzWiersze("produkt", "id")];
    		
    		JTextField	dodajBiałko,dodajWęglowodany,dodajTłuszcze,dodajKaloryczność, dodajBłonnik,
    					dodajWagaMin,dodajWagaMax,dodajWagaProg,dodajNazwaProduktu;
    		
    		JComboBox skł1,skł2,skł3,skł4,skł5,skł6,skł7;
    		
    		Posilek wybrane[]= new Posilek[20]; 
    		
    		JTabbedPane tydzien, zakladki;
    		
    		static int licznik=0;
    		int komponent=0;
    		Object font=new Font("Time New Roman", Font.BOLD, 20);
    		
    		public Feed(String title){
    			this.setTitle(title);
    		}
    		public Feed(){
    			setSize(675,710);
    			setTitle("Feed !");
    			
    			zakladki = new JTabbedPane();
    			zakladki.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
    			 getContentPane().add(zakladki, BorderLayout.CENTER );
    			 
    		
    			 tworzZakladke3();
    			 tworzZakladke4();
    			 
    			 
    			 tydzien = new JTabbedPane();
    			 tydzien.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
    				zakladki.addTab("Dodaj Posiłki/Produkty", scrollPane3);
    				zakladki.addTab("Posiłki", scrollPane4);
    		
    		}
    
    		public void tworzZakladke3() {
    			
    			JPanel keeper = new JPanel();
    			keeper.setLayout(new BoxLayout(keeper, BoxLayout.Y_AXIS));
    			keeper.setBorder(BorderFactory.createTitledBorder(null, "  ", TitledBorder.CENTER, TitledBorder.TOP, new Font("times new roman",Font.PLAIN,22), Color.BLACK));
    			jp3 = new JPanel();
    			jp3.setBorder(BorderFactory.createTitledBorder(null, " Tutaj możesz dodać swoje posiłki lub produkty ", TitledBorder.CENTER, TitledBorder.TOP, new Font("times new roman",Font.PLAIN,22), Color.BLACK));
    			jp3.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
    			jp3.add(keeper);
    			dodajProdukt = new JButton("Dodaj produkt do bazy");
    			dodajProdukt.addActionListener(this);
    			dodajPosilek = new JButton("Dodaj posiłek do bazy");
    			dodajPosilek.addActionListener(this);
    			dodajBiałko = new JTextField();
    			dodajKaloryczność = new JTextField();
    			dodajTłuszcze = new JTextField();
    			dodajWęglowodany = new JTextField();
    			dodajBłonnik = new JTextField();
    			dodajWagaMax = new JTextField();
    			dodajWagaMin = new JTextField();
    			dodajWagaProg = new JTextField();
    			dodajNazwaProduktu = new JTextField();
    			keeper.add(new JLabel("Nazwa Produktu"));
    			keeper.add(dodajNazwaProduktu);
    			keeper.add(new JLabel("Kaloryczność"));
    			keeper.add(dodajKaloryczność);
    			keeper.add(new JLabel("Białko"));
    			keeper.add(dodajBiałko);
    			keeper.add(new JLabel("Węglowodany"));
    			keeper.add(dodajWęglowodany);
    			keeper.add(new JLabel("Tłuszcze"));
    			keeper.add(dodajTłuszcze);
    			keeper.add(new JLabel("Błonnik"));
    			keeper.add(dodajBłonnik);
    			keeper.add(new JLabel("Waga min. produktu"));
    			keeper.add(dodajWagaMin);
    			keeper.add(new JLabel("Waga maks. produktu"));
    			keeper.add(dodajWagaMax);
    			keeper.add(new JLabel("Wzrost wagi w posiłku"));
    			keeper.add(dodajWagaProg);
    			keeper.add(new JLabel());
    			keeper.add(dodajProdukt);
    			String [] data = new String[baza.policzWiersze("produkt", "id")+1];
    			data[0]="";
    			for (int i = 1; i < data.length; i++) {
    				data[i]=baza.wybierzProdukt(i).nazwaProduktu;
    			}
    			posileczki = new JPanel();
    			posileczki.setBorder(BorderFactory.createTitledBorder(null, "  ", TitledBorder.CENTER, TitledBorder.TOP, new Font("times new roman",Font.PLAIN,22), Color.BLACK));
    			posileczki.setLayout(new BoxLayout(posileczki, BoxLayout.Y_AXIS));
    			skł1= new JComboBox<String>(data);
    			skł1.setSelectedItem("");
    			skł1.addActionListener(this);
    			skł2= new JComboBox<String>(data);
    			skł2.addActionListener(this);
    			skł3= new JComboBox<String>(data);
    			skł3.addActionListener(this);
    			skł4= new JComboBox<String>(data);
    			skł4.addActionListener(this);
    			skł5= new JComboBox<String>(data);
    			skł5.addActionListener(this);
    			skł6= new JComboBox<String>(data);
    			skł6.addActionListener(this);
    			skł7= new JComboBox<String>(data);
    			skł7.addActionListener(this);
    			posileczki.add(new JLabel("Składnik 1 : "));
    			posileczki.add(skł1);
    			posileczki.add(new JLabel("Składnik 2 : "));
    			posileczki.add(skł2);
    			posileczki.add(new JLabel("Składnik 3 : "));
    			posileczki.add(skł3);
    			posileczki.add(new JLabel("Składnik 4 : "));
    			posileczki.add(skł4);
    			dodajSkładnik = new JButton("Dodaj kolejny składnik");
    			dodajSkładnik.addActionListener(this);
    			usunSkładnik = new JButton("Usuń składnik");
    			usunSkładnik.addActionListener(this);
    			usunSkładnik.setVisible(false);
    			JPanel buttonPane = new JPanel();
    			buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
    			buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
    			buttonPane.add(Box.createHorizontalGlue());
    			buttonPane.add(usunSkładnik);
    			buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
    			buttonPane.add(dodajSkładnik);
    			posileczki.add(buttonPane);
    			jp3.add(posileczki);
    			posileczki.add(dodajPosilek);
    			
    			scrollPane3 = new JScrollPane(jp3);
            	scrollPane3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            	scrollPane3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    		}
    		
    		private void tworzZakladke4() {
    			jp4 = new JPanel();
    			jp4.setBorder(BorderFactory.createTitledBorder(null, " Lista przykładowych posiłkw ", TitledBorder.CENTER, TitledBorder.TOP, new Font("times new roman",Font.PLAIN,22), Color.BLACK));
    			jp4.setLayout(new GridLayout(0,1));
    			int sumator=0;
    				for (int k = 4; k <= 7; k++) {
    					JLabel separator= new JLabel();
    					JLabel info = new JLabel("Posiłki "+k+"-składnikowe ");
    					JLabel separator2= new JLabel();
    					if (k!=4) jp4.add(separator);
    					jp4.add(info);
    					jp4.add(separator2);
    					Posilek jj[];
    					jj=baza.pobierzPosilek(baza.wyborPosilku(k));
    					for (int i = 0; i < jj.length; i++) {
    						pos[sumator]=jj[i];
    						cpos[sumator]=new JCheckBox("<html><p width=\"500\">"+pos[sumator].lista()+"</html></p>");
    						cpos[sumator].addActionListener(this);
    						cpos[sumator].setForeground(Color.black);
    						jp4.add(cpos[sumator]);
    						sumator++;
    					}
    				}
    			
    			scrollPane4 = new JScrollPane(jp4);
    			scrollPane4.getVerticalScrollBar().setUnitIncrement(25);
            	scrollPane4.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            	scrollPane4.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
            	
    		}
    		
    		
    		public double trans(JTextField j) {
    			double a;
    						a= Double.parseDouble(j.getText());
    						return a;
    				}
    		
    		public static double zaok(double cyfra){
    			cyfra*=100;
    			cyfra=Math.floor(cyfra);
    			cyfra/=100;
    			
    			return cyfra;
    		}
    		
    		public static double zaok(double cyfra, int ile){
    			for (int i = 0; i < ile; ++i) {
    				cyfra*=10;
    			}
    			double rzad=1;
    			for (int i = 0; i < ile; ++i) {
    				rzad/=10;
    			}
    			return Math.floor(cyfra)*rzad;
    		}
    		
    		
    		public static void main(String[] args) throws SQLException {
    			try {
    			    for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
    			        if ("Nimbus".equals(info.getName())) {
    			            UIManager.setLookAndFeel(info.getClassName());
    			            break;
    			        }
    			    }
    			} catch (Exception e) {
    			}
    			Feed okno = new  Feed();
    			okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    			okno.setVisible(true);
    	        
    }
    
    		@Override
    		public void actionPerformed(ActionEvent e) {
    			Object event = e.getSource();
    			for (int i = 0; i < rd.length; i++) {
    				if (event == rd[i]){
    					if (rd[i].isSelected()) rd[i].setForeground(Color.black);
    					else rd[i].setForeground(Color.red);
    				}
    			}
    				for (int i = 0; i < cpos.length; i++) {
    					if (event == cpos[i]){
    						if (cpos[i].isSelected()){ 
    							if (wybrane.equals(pos[i])) ; 
    								else{
    						wybrane[licznik]=pos[i];
    						licznik++;
    						}
    				} else {
    					wybrane[licznik-1]=null;
    					licznik--;
    				}
    					}
    					}
    				if (licznik==wybrane.length){
    					for (int i = 0; i < cpos.length; i++) {
    						if (cpos[i] != null && cpos[i].isSelected()==false) cpos[i].setEnabled(true); ;
    					}
    				}
    				 if (event==dodajProdukt){
    					baza.dodajProdukt(new Produkt(
    							dodajNazwaProduktu.getText(),
    							trans(dodajKaloryczność),trans(dodajBiałko),
    							trans(dodajTłuszcze),trans(dodajWęglowodany),
    							trans(dodajBłonnik),trans(dodajWagaMin),
    							trans(dodajWagaMax),trans(dodajWagaProg)));
    				}
    				
    				else if (event==dodajPosilek){
    					if (skł1.getSelectedIndex()!=0 && 
    						skł2.getSelectedIndex()!=0 && 
    						skł3.getSelectedIndex()!=0 && 
    						skł4.getSelectedIndex()!=0){
    					switch (komponent) {
    					case 0:
    						baza.dodajPosilki(
    								skł1.getSelectedIndex(), 
    								skł2.getSelectedIndex(), 
    								skł3.getSelectedIndex(), 
    								skł4.getSelectedIndex());
    						break;
    					case 1:
    						if (skł5.getSelectedIndex()!=0)
    						baza.dodajPosilki(
    								skł1.getSelectedIndex(), 
    								skł2.getSelectedIndex(), 
    								skł3.getSelectedIndex(), 
    								skł4.getSelectedIndex(), 
    								skł5.getSelectedIndex()); 
    						break;
    					case 2:
    						if (skł6.getSelectedIndex()!=0 && skł5.getSelectedIndex()!=0) 
    						baza.dodajPosilki(
    								skł1.getSelectedIndex(), 
    								skł2.getSelectedIndex(), 
    								skł3.getSelectedIndex(), 
    								skł4.getSelectedIndex(), 
    								skł5.getSelectedIndex(), 
    								skł6.getSelectedIndex());
    						break;
    					case 3:
    						if (skł7.getSelectedIndex()!=0 && skł6.getSelectedIndex()!=0 && skł5.getSelectedIndex()!=0)
    						baza.dodajPosilki(
    							skł1.getSelectedIndex(), 
    							skł2.getSelectedIndex(), 
    							skł3.getSelectedIndex(), 
    							skł4.getSelectedIndex(), 
    							skł5.getSelectedIndex(), 
    							skł6.getSelectedIndex(), 
    							skł7.getSelectedIndex());
    						break;
    					}
    				}}
    				
    				else if (event==usunSkładnik){
    					if (komponent==3){
    						posileczki.remove(12);
    						posileczki.remove(12);
    						dodajSkładnik.setVisible(true);
    					}
    					if (komponent==2){
    						posileczki.remove(10);
    						posileczki.remove(10);
    						}
    					if (komponent==1){
    						posileczki.remove(8);
    						posileczki.remove(8);
    						usunSkładnik.setVisible(false);
    					}
    					repaint();
    					if (komponent>=1 && komponent<=3){
    						--komponent;
    					}
    				}
    				
    				else if (event==dodajSkładnik){
    					if (komponent==0){
    					usunSkładnik.setVisible(true);
    					posileczki.add(new JLabel("Składnik 5 : "),8);
    					posileczki.add(skł5,9);
    					}
    					if (komponent==1){
    					posileczki.add(new JLabel("Składnik 6 : "),10);
    					posileczki.add(skł6,11);
    					}
    					if (komponent==2){
    						dodajSkładnik.setVisible(false);
    					posileczki.add(new JLabel("Składnik 7 : "),12);
    					posileczki.add(skł7,13);
    					}
    					repaint();
    					if (komponent>=0 && komponent<=2){
    						++komponent;
    					}
    				}
    				
    				
    				
    			}
    		}

  8. #8
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: How to refresh JPanel to see new Data from DBl?

    Thanks for the code. However it is too much to work with. Can you make a smaller, simpler test program the compiles, executes and shows the problem.
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    maik89 is offline Member
    Join Date
    Nov 2015
    Posts
    6
    Rep Power
    0

    Default Re: How to refresh JPanel to see new Data from DBl?

    Quote Originally Posted by Norm View Post
    Thanks for the code. However it is too much to work with. Can you make a smaller, simpler test program the compiles, executes and shows the problem.
    Link to Jar

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.sql.SQLException;
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    import javax.swing.UIManager;
    import javax.swing.UIManager.LookAndFeelInfo;
    import javax.swing.border.TitledBorder;
    
    	public class Feed extends JFrame implements ActionListener{
    		DBtest baza = new DBtest("test");
    		
    		JPanel jp3,posileczki;
    		
    		JScrollPane scrollPane3;
    		
    		JButton  addProduct;
    		
    		JTextField	addPorductName;
    		
    		JComboBox skł1;
    		
    		JTabbedPane tydzien, zakladki;
    		
    		Object font=new Font("Time New Roman", Font.BOLD, 20);
    		public Feed(){
    			setSize(675,710);
    			setTitle("Feed !");
    			
    			zakladki = new JTabbedPane();
    			zakladki.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
    			 getContentPane().add(zakladki, BorderLayout.CENTER );
    			 
    		
    			 tworzZakladke3();
    			 
    			 tydzien = new JTabbedPane();
    			 tydzien.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
    				zakladki.addTab("Dodaj Posiłki/Produkty", scrollPane3);
    		
    		}
    
    		public void tworzZakladke3() {
    			
    			JPanel keeper = new JPanel();
    			keeper.setLayout(new BoxLayout(keeper, BoxLayout.Y_AXIS));
    			keeper.setBorder(BorderFactory.createTitledBorder(null, "  ", TitledBorder.CENTER, TitledBorder.TOP, new Font("times new roman",Font.PLAIN,22), Color.BLACK));
    			jp3 = new JPanel();
    			jp3.setBorder(BorderFactory.createTitledBorder(null, " Just add someth ", TitledBorder.CENTER, TitledBorder.TOP, new Font("times new roman",Font.PLAIN,22), Color.BLACK));
    			jp3.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
    			jp3.add(keeper);
    			addProduct = new JButton("Add to DB");
    			addProduct.addActionListener(this);
    			addPorductName = new JTextField();
    			keeper.add(new JLabel("type something here "));
    			keeper.add(addPorductName);
    			keeper.add(new JLabel());
    			keeper.add(addProduct);
    			String [] data = new String[baza.count("test2", "id")+1];
    			data[0]="";
    			for (int i = 1; i < data.length; i++) {
    				data[i]=baza.chooseProduct(i).nazwaProduktu;
    			}
    			posileczki = new JPanel();
    			posileczki.setBorder(BorderFactory.createTitledBorder(null, "  ", TitledBorder.CENTER, TitledBorder.TOP, new Font("times new roman",Font.PLAIN,22), Color.BLACK));
    			posileczki.setLayout(new BoxLayout(posileczki, BoxLayout.Y_AXIS));
    			skł1= new JComboBox<String>(data);
    			skł1.setSelectedItem("");
    			skł1.addActionListener(this);
    			posileczki.add(new JLabel("Składnik 1 : "));
    			posileczki.add(skł1);
    			JPanel buttonPane = new JPanel();
    			buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
    			buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
    			buttonPane.add(Box.createHorizontalGlue());
    			buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
    			posileczki.add(buttonPane);
    			jp3.add(posileczki);
    			
    			scrollPane3 = new JScrollPane(jp3);
            	scrollPane3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            	scrollPane3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    		}
    		
    		
    		public static void main(String[] args) throws SQLException {
    			try {
    			    for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
    			        if ("Nimbus".equals(info.getName())) {
    			            UIManager.setLookAndFeel(info.getClassName());
    			            break;
    			        }
    			    }
    			} catch (Exception e) {
    			}
    			Feed okno = new  Feed();
    			okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    			okno.setVisible(true);
    	        
    }
    
    		@Override
    		public void actionPerformed(ActionEvent e) {
    			Object event = e.getSource();
    				 if (event==addProduct){
    					baza.addProduct(new Produkt(
    							addPorductName.getText(),
    							
    									0, 
    									0, 
    									0, 
    									0, 
    									0, 
    									0, 
    									0, 
    									0));
    							
    				}
    				
    			}
    		}
    Java Code:
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    
    public class DBtest {
    
    private Connection con;
    private Statement st;
    private ResultSet rs;
    	
    	public DBtest(String whichDataBase){
    	try {
    		Class.forName("com.mysql.jdbc.Driver");
    //			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+whichDataBase+"?characterEncoding=UTF-8","monty","some_pass");
    			con = DriverManager.getConnection("jdbc:mysql://109.157.79.228/"+whichDataBase+"?characterEncoding=UTF-8","monty","some_pass");
    		st = con.createStatement();
    	} catch (Exception e) {
    		e.printStackTrace(); 
    	}
    	
    }
    	
    	public Produkt chooseProduct(int id){	
    		Produkt result=null;
    		try {
    			String query="select * from  test2 WHERE id="+id;
    			rs=st.executeQuery(query);
    			
    			while(rs.next()){
    				
    				result=new Produkt(rs.getString("NazwaProduktu"),0,0,0,0,0,0,0,0);
    			}
    		} catch (Exception e) {
    			System.out.println("unable to download fgrom db"+e);
    		}
    		return result;
    	}	
    	
    	
    	
    	public int count(String whichTable, String whichColumn) {
    		 int sizeDataPredicted = 0;
    		try {
    			String query="SELECT COUNT(*) AS "+whichColumn+" FROM "+whichTable;
    			rs=st.executeQuery(query);
    			
    			  while (rs.next()){
    	                sizeDataPredicted = rs.getInt(whichColumn);
    	                
    			}
    		} catch (Exception e) {
    			System.out.println("unable to count "+e);
    		}
    		return  sizeDataPredicted;
    	}
    	
    
    	
    
    	
    	public void addProduct(Produkt nowy) {
    		
    			String  sql = "INSERT INTO `test`.`test2` (`id`, `NazwaProduktu`) VALUES (NULL, "+
    					"'"+nowy.nazwaProduktu+"');";
    			try {
    				st.executeUpdate(sql);
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    			System.out.println("added "+nowy.nazwaProduktu);
    	
    	}
    	
    
    	public int ilePosilkow(){
    			 int sizeDataPredicted = 0;
    				try {
    					for (int i = 4; i <= 7; i++) {
    					String query="SELECT COUNT(*) AS test FROM test2";
    					rs=st.executeQuery(query);
    					int ile=0;
    					  while (rs.next()){
    			                ile = rs.getInt("posilki");
    					}
    					  sizeDataPredicted+=ile;}
    				} catch (Exception e) {
    					System.out.println("Nie udało sie policzyc elementow "+e);
    				}
    				return  sizeDataPredicted;
    		}
    	
    	
    	
    		
    
    }

  10. #10
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: How to refresh JPanel to see new Data from DBl?

    The posted code won't compile because it is missing some classes.

    Please rewrite the code to make it smaller and simpler for testing.
    If you don't understand my response, don't ignore it, ask a question.

  11. #11
    maik89 is offline Member
    Join Date
    Nov 2015
    Posts
    6
    Rep Power
    0

    Default Re: How to refresh JPanel to see new Data from DBl?

    Indeed its missing Product class
    Java Code:
    public class Produkt{
    public String nazwaProduktu;
    		
    	 	
    	 	Produkt(String _nazwaProduktu, double k, double bl, double t, double w, double b, double w, double wa, double p) 
     		{		
     			
     	  nazwaProduktu= _nazwaProduktu;
     	  
     		}
    	 
    	 	  
    }
    Sorry for that but i can't really think how make it easier :P

  12. #12
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: How to refresh JPanel to see new Data from DBl?

    Ok, it compiles. However it needs a DB to execute. You need to write a special testing version that does NOT need anything outside of the code to execute.
    I do not want a DB for testing. That makes it too complicated.
    If you don't understand my response, don't ignore it, ask a question.

  13. #13
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: How to refresh JPanel to see new Data from DBl?

    how to refresh JPanel?
    What is the name of the JPanel variable? Where is the code that is trying to refresh it?
    If you don't understand my response, don't ignore it, ask a question.

  14. #14
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: How to refresh JPanel to see new Data from DBl?

    The simplest thing is, can you write a GUI that has an add button, which adds a value in basic text field to a List<String>, which is held in your DB class?

    That's part 1, and represents your addition of Products code.

    Part 2 is, when the add() code is called, you need to then pass back to the GUI code to add an item to the JComboBox.

    If you can get that to work (and there should be very little code involved) then that is, essentially, the same logic you need for you Products.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. JPanel - Refresh Problem
    By galliva in forum AWT / Swing
    Replies: 2
    Last Post: 04-19-2011, 01:32 PM
  2. Replies: 1
    Last Post: 11-09-2010, 09:28 AM
  3. Jpanel won't refresh
    By alon2580 in forum AWT / Swing
    Replies: 3
    Last Post: 08-22-2008, 05:26 PM
  4. Can't refresh a JPanel/text
    By nickbeacroft in forum AWT / Swing
    Replies: 8
    Last Post: 06-23-2008, 05:23 PM
  5. refresh JPanel
    By olesja in forum AWT / Swing
    Replies: 1
    Last Post: 04-16-2008, 03:58 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •