Wypełnianie tablicy przez GUI

0

Witam,
mam taki problem, gdyż potrzebuję uzupełniać tablicę dwuwymiarową za pomocą GUI w Netbeans, lecz kompletnie nie wiem jak podpiąć tabelę z gui pod tą tablicę.

Tablica znajduje się w paczce Wyznacznik, klasie Client i metodzie main, a jTable w paczce gui w klasie GUI_Client.

W jaki sposób mogę się odwołać tej tablicy by uzupełniając kolejne komórki w jTable były uzupełniane odpowiednie pola w tablicy.

Z góry wielkie dzięki za pomoc ;)

0

ort! jakiś kod nikt nie jest wróżką. Jak tworzysz to JTable? Pewnie w metodzie main klasy Client tworzysz oba obiekty Client i GUI_Client? Jeśli tak to możesz napisać sobie jakieś metody typu getValuesFromTable i zwracać jest do tej tablicy w main.

0

GUI_Client.java:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import Wyznacznik.Client;

/**
 *
 * @author Rafał
 */
public class GUI_Client extends javax.swing.JFrame {

    /**
     * Creates new form GUI_Client
     */
    public GUI_Client() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "", "", "", "", ""
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTable2KeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(jTable2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(479, 479, 479))
            .addGroup(layout.createSequentialGroup()
                .addGap(89, 89, 89)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(14, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(113, 113, 113)
                .addComponent(jButton1)
                .addGap(51, 51, 51))
        );

        pack();
    }// </editor-fold>                        

    private void jTable2KeyPressed(java.awt.event.KeyEvent evt) {                                   
        
        // TODO add your handling code here:
        
    }                                  

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GUI_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GUI_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GUI_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUI_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GUI_Client().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable2;
    // End of variables declaration                   
}

Client.java:

package Wyznacznik;


import gui.GUI_Client;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;


public class Client  {

    
    
    public static void main(Double[] args){
        
        try {
            int rozmiar=5; 
			double macierz[][];
			double wartosc;
			BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in),1);
			Registry reg = LocateRegistry.getRegistry(1);
			
			Calculator stub = (Calculator)reg.lookup("Wyznacznik Macierzy");

			macierz = new double[rozmiar][rozmiar]; 
			
			for(int i = 0; i < rozmiar; i++){
				for(int j = 0; j < rozmiar; j++){
					System.out.print("Podaj wartość o adresie " + i+ "x"+j+": ");                                      
					wartosc = Double.parseDouble(stdin.readLine());
                                        macierz[i][j] = wartosc;
					
				}
					
			}
			System.out.println("Wyznacznik macierzy " +rozmiar+" x " +rozmiar+" jest równy: " + stub.wyznacznikMacierz(macierz));
			while(true){
				
			}
        } catch(Exception e) {
            System.out.println("Brak połączenia z serwerem, lub wystąpił inny błąd");
        }
    }

    
}
0

W tej chwili masz dwa niezależne programy (dwie klasy z metodą main). Która klasa ma być klasą startową w programie, Client czy GUI_Client?

0

GUI

0

Zmień klasę Client

package Wyznacznik;
 
 
import gui.GUI_Client;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
 
 
public class Client  
{
     int rozmiar=5; 
    double macierz[][] = new double[5][5];    
 
    public void send()
    {
        try 
        {

            BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in),1);
            Registry reg = LocateRegistry.getRegistry(1);
 
            Calculator stub = (Calculator)reg.lookup("Wyznacznik Macierzy");

            System.out.println("Wyznacznik macierzy " +rozmiar+" x " +rozmiar+" jest równy: " + stub.wyznacznikMacierz(macierz));

        } 
        catch(Exception e) 
       {
            System.out.println("Brak połączenia z serwerem, lub wystąpił inny błąd");
        }
    } 
}

W klasie GUI_Client dodaj pole

Client client = new Client();

dodaj przycisk "Wyślij" z ActionListenerem, w metodzie actionPerformed wpierw przepisz liczby z JTable do macierz a potem wywołaj client.send();.

0

Bardzo dziękuję ;)

A mógłbyś jeszcze napisać w jaki sposób mam się odwołać do tych wartości z jTable?
Najlepiej ten fragment kodu do przepisania wartości z tabeli do tablicy?

0

Zmień model.

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Integer [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            }

A potem

client.macierz[i][j] = jTable2.getModel()[i][j];
0

Tu co jeszcze nie gra?
user image

0

drugi błąd to był brak jednego zamknięcia nawiasu więc poprawiłem już, lecz nie wiem jaki jest problem w tej linijce ze zmianą modelu

0

Ja też nie wiem, u mnie działa (zmieniłem na Double) bo taki jest typ macierzy w klasie Client.
model.png
Zostaw w taki razie Object[][] i podczas przepisywania rzutuj (konwertuj).

0

ok jak dodałem ten ten fragment ze Stringami to przeszło też z Double zamiast Object

jeszcze tu jeden błąd mi wychodzi:
user image

0
  1. Przecież w pierwotnym kodzie miałeś ten fragment ze Stringami. Czemu go usunąłeś?
  2. Moja pomyłka
client.macierz[i][j] = jTable2.getModel().getValueAt(i,j);
  1. Przenieś client.send(); za pętlę.
0

Fragment ze stringami usunęło przy zmianie modelu, co do poprawionej linii kodu to nadal wywala błąd:
user image

Gdy usunę "getModel" to niby błędu nie ma ale i tak jest wypełniona zerami

0

getModel jest metodą - musi być nawias:

client.macierz[i][j] = (Double)(jTable2.getModel().getValueAt(i,j));

Ponieważ nie masz sortowania, to numery wierszy w tabeli i w modelu są równe i możesz pisać krócej.

client.macierz[i][j] = (Double)(jTable2.getValueAt(i,j));

Co do zer, to zmyślasz. Jeśli wypełnisz JTable, to w client.macierz są liczby z JTable.

0

ok tamto przeszło, lecz nadal są same zera, wypełniam tabelę, daję wyślij i przy takim wypisaniu w Client.java

 public void send()
    {
        try 
        {
 
            BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in),1);
            Registry reg = LocateRegistry.getRegistry(1);
 
            Calculator stub = (Calculator)reg.lookup("Wyznacznik Macierzy");
 
            System.out.println("Wyznacznik macierzy " +rozmiar+" x " +rozmiar+" jest równy: " + stub.wyznacznikMacierz(macierz));
            for(int i = 0; i < 5; i++){
              for(int j = 0; j < 5; j++){
            System.out.print(macierz[i][j]);
              }}
        } 
        catch(Exception e) 
       {
            System.out.println("Brak połączenia z serwerem, lub wystąpił inny błąd");
        }
    } 

wypisuje same zera i jak oblicza wyznacznik to też zawsze jest zero w wyniku

0

Przecież nie wiesz co jest w macierzy przed obliczeniem wyznacznika. Może metoda stub.wyznacznikMacierz jest błędna.

0

Bez gui działało wszystko bezproblemowo, więc metoda była raczej dobra, poza tym nie wiem czemu dziś po wciśnięciu "wyślij" wyskakują mi takie błędy choć wczoraj tego nie było a nic nie zmieniałem
user image

0

po usunięciu fragmentu z przypisaniem przechodzi ale po wstawieniu od razu te błędy wywala

0

Jeśli oczekujesz pomocy, to udostępnij aktualny kod klas Client i GUI_Client.

0

Client:

package Wyznacznik;
 
 
import Wyznacznik.GUI_Client;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
 
 
public class Client  
{
     int rozmiar=5; 
    double macierz[][] = new double[5][5];    
 
    public void send()
    {
        try 
        {
 
            BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in),1);
            Registry reg = LocateRegistry.getRegistry(1);
 
            Calculator stub = (Calculator)reg.lookup("Wyznacznik Macierzy");
 
            System.out.println("Wyznacznik macierzy " +rozmiar+" x " +rozmiar+" jest równy: " + stub.wyznacznikMacierz(macierz));
//            for(int i = 0; i < 5; i++){
//              for(int j = 0; j < 5; j++){
//            System.out.print(macierz[i][j]);
//              }}
        } 
        catch(Exception e) 
       {
            System.out.println("Brak połączenia z serwerem, lub wystąpił inny błąd");
        }
    } 
}

GUI_Client:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Wyznacznik;


/**
 *
 * @author Rafał
 */

public class GUI_Client extends javax.swing.JFrame {
Client client = new Client();

    /**
     * Creates new form GUI_Client
     */
    public GUI_Client() {
        
        initComponents();
    }
 
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jWyslij = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jWyslij.setText("jButton1");
        jWyslij.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jWyslijActionPerformed(evt);
            }
        });

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Double [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "", "", "", "",""
            }));
            jScrollPane2.setViewportView(jTable2);

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(436, 436, 436)
                            .addComponent(jWyslij))
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(73, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 59, Short.MAX_VALUE)
                    .addComponent(jWyslij)
                    .addGap(58, 58, 58))
            );

            pack();
        }// </editor-fold>                        

    private void jWyslijActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
      for(int i = 0; i < 5; i++){
              for(int j = 0; j < 5; j++){
                    
        client.macierz[i][j] = (Double)(jTable2.getValueAt(i,j));
        
    }                                       
   }
      client.send();
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GUI_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GUI_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GUI_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUI_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GUI_Client().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable2;
    private javax.swing.JButton jWyslij;
    // End of variables declaration                   
}
0
  1. Pisałem Ci, że nie wiesz jak wygląda tablica macierz, dla której jest liczony wyznacznik, bo wyświetlasz ją zbyt późno. Nie poprawiłeś tego i nadal nie wiesz jak ona wygląda.
public class Client  
{
    int rozmiar = 5; 
    double macierz[][] = new double[rozmiar][rozmiar];    

    public void send()
    {
        try 
        { 
            BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in),1);
            Registry reg = LocateRegistry.getRegistry(1);
            //tu musisz wyświetlać macierz
            for(int i = 0; i < rozmiar; i++)
            {
                System.out.println(Arrays.toString(macierz[i]));
            }
            System.out.println();
            Calculator stub = (Calculator)reg.lookup("Wyznacznik Macierzy");
            System.out.println("Wyznacznik macierzy " +rozmiar+" x " +rozmiar+" jest równy: " + stub.wyznacznikMacierz(macierz));
        }            
        catch(Exception e) 
        {
            System.out.println("Brak połączenia z serwerem, lub wystąpił inny błąd");
        }
    } 
}
  1. W modelu umieściłeś same nulle, nic dziwnego, że jeśli klikniesz w przycisk przed wypełnieniem całej JTable, to dostaniesz NullPointerException.
  2. Usunąłeś fragment
            Class[] types = new Class [] 
            {
                java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
            };

W konsekwencji, wartość zwracana przez getValueAt na wcześniej edytowanej komórce jest typu String. Tego typu nie da się rzutować na Double.

        jTable2.setModel(new javax.swing.table.DefaultTableModel
        (
            new Double [][] 
            {
                {0.0, 0.0, 0.0, 0.0, 0.0},
                {0.0, 0.0, 0.0, 0.0, 0.0},
                {0.0, 0.0, 0.0, 0.0, 0.0},
                {0.0, 0.0, 0.0, 0.0, 0.0},
                {0.0, 0.0, 0.0, 0.0, 0.0}
            },
            new String [] 
            {
                "1", "2", "3", "4", "5"
            }
        ) 
        {
            Class[] types = new Class [] 
            {
                java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class
            };
 
            public Class getColumnClass(int columnIndex) 
            {
                return types [columnIndex];
            }
        });
0

Ok wielkie dzięki, powiedzmy że działa, muszę jeszcze poprawić algorytm w serwerze bo dobrze przesyła lecz wynik daje ciągle 0..

Ale to co potrzebowałem to mi bardzo pomogłeś, jeszcze raz bardzo Ci dziękuję za pomoc i cierpliwość do mnie ;)

1 użytkowników online, w tym zalogowanych: 0, gości: 1