Collect data from a Jtable and send to a List

Asked

Viewed 292 times

2

In my Java application, I have a sales screen where the products that are selected go to a JTable. At the end of the sale, I need to collect data from JTable and deliver to the printing method, which is in another class. I’m just not able to imagine the most correct way to create the List and deliver to the other method.

Below I’ll put the code where I’m walking.

Telavenda.java

public void capturaProduto(){
    ArrayList lp = new ArrayList();

     for (int i = 0; i < TbProdutosVenda.getRowCount(); i++) {
         lp.add(TbProdutosVenda.getValueAt(i, 1).toString());
         lp.add(TbProdutosVenda.getValueAt(i, 2).toString());
         lp.add(TbProdutosVenda.getValueAt(i, 3).toString());
         lp.add(TbProdutosVenda.getValueAt(i, 6).toString());
     }

     imp.imprimirBalcao(lp);
}

Printed.java.

public void imprimirBalcao(List lista) {
    Frame f = new Frame("Frame temporário");
    f.pack();
    Toolkit tk = f.getToolkit();
    PrintJob pj = tk.getPrintJob(f, "MP4200", null);

    if (pj != null) {
        Graphics g = pj.getGraphics();
        g.drawString("Relacao de produtos", 50, 30);
        int y = 70;
        for (int i = 0; i < lista.size(); i++) {
            g.drawString("Código: " + lista.get(i), 50, y);
            y += 25;
            g.drawString("Nome: " + lista.get(i), 50, y);
            y += 25;
            g.drawString("Quantidade: " + lista.get(i), 50, y);
            y += 25;
            g.drawString("Preço: " + lista.get(i), 50, y);
            y += 50;
        }

        g.dispose();

        pj.end();
    }

    f.dispose();
}
  • What are the types of TbProdutosVenda.getValueAt(i, 1), of TbProdutosVenda.getValueAt(i, 2), of TbProdutosVenda.getValueAt(i, 3) and of TbProdutosVenda.getValueAt(i, 6)? I need that information to prepare my answer.

  • @VictorStafusa, TbProdutosVenda.getValueAt(i, 1) tipo int, TbProdutosVenda.getValueAt(i, 2) tipo String, TbProdutosVenda.getValueAt(i, 3) tipo Double, TbProdutosVenda.getValueAt(i, 6) tipo Double.

  • It is Double with upper case or double case?

  • By the way, the first is Integer instead of int. Correct?

  • this the way I passed it to you above. int and Double.

  • Wouldn’t be returning one List<List<?>>? One JTable can be imagined as an array, returning a single list seems a bit messy. It’s a list even if it needs to return?

Show 1 more comment

1 answer

1


First, model some classes that describe what you will print and put in them a method responsible for printing them. Let’s see, a reporting of printed products has several printed products and each printed product has code, name, quantity and price. Therefore:

public class ProdutoImpresso implements Drawable {
    private final String codigo;
    private final String nome;
    private final String quantidade;
    private final String preco;

    public ProdutoImpresso(String codigo, String nome, String quantidade, String preco) {
        this.codigo = codigo;
        this.nome = nome;
        this.quantidade = quantidade;
        this.preco = preco;
    }

    @Override
    public void draw(int x, int y, Graphics g) {
        g.drawString("Código: " + codigo, x, y);
        g.drawString("Nome: " + nome, x, y + 25);
        g.drawString("Quantidade: " + quantidade, x, y + 50);
        g.drawString("Preço: " + preco, x, y + 75);
    }
}
public class RelacaoDeProdutos implements Drawable {
    private final List<ProdutoImpresso> itens;

    public RelacaoDeProdutos(List<ProdutoImpresso> itens) {
        this.itens = itens;
    }

    @Override
    public void draw(int x, int y, Graphics g) {
        g.drawString("Relação de produtos", x, y);
        int y2 = y + 40;
        for (ProdutoImpresso i : itens) {
            i.draw(x, y2, g);
            y2 += 125;
        }
    }
}

That interface there is because you probably want to extend that to other things that you might want to print:

public interface Drawable {
    public void draw(int x, int y, Graphics g);
}

Having done so, their other classes become simple:

public void capturaProduto() {    
    List<ProdutoImpresso> lp = new ArrayList<>();

    for (int i = 0; i < TbProdutosVenda.getRowCount(); i++) {
        ProdutoImpresso item = new ProdutoImpresso(
                TbProdutosVenda.getValueAt(i, 1).toString(),
                TbProdutosVenda.getValueAt(i, 2).toString(),
                TbProdutosVenda.getValueAt(i, 3).toString(),
                TbProdutosVenda.getValueAt(i, 6).toString());
        lp.add(item);
    }

    RelacaoDeProdutos r = new RelacaoDeProdutos(lp);
    imp.imprimir("MP4200", 50, 30, r);
}
public void imprimir(String titulo, int x, int y, Drawable toDraw) {
    Frame f = new Frame("Frame temporário");
    f.pack();
    Toolkit tk = f.getToolkit();
    PrintJob pj = tk.getPrintJob(f, titulo, null);
    Graphics g = null;
    try {
        if (pj != null) {
            g = pj.getGraphics();
            toDraw.draw(x, y, g);
        }
    } finally {
        if (g != null) g.dispose();
        if (pj != null) pj.end();
        f.dispose();
    }
}

The block finally serves in case it finishes the objects even if you pass some Drawable misbehaved who throw an exception in the method draw.

The advantage of doing it this way is that whenever you have something that can be drawn on the screen, in the printer or somewhere else, you just have to implement the interface Drawable and that’s it. Also, whenever you have a complex object to be printed/drawn on the whole, it is worth using the strategy that each part is responsible for its own design, making a Drawable be composed of other Drawables.

Finally, to print any Drawable, all you will need to do is (after you have created the Drawable):

    imp.imprimir(titulo, x, y, drawable);

If you are with Java 8, you can try a bolder step and make your Drawable thus:

public interface Drawable {
    public void draw(int x, int y, Graphics g);

    public default void imprimir(String titulo, int x, int y) {
        Frame f = new Frame("Frame temporário");
        f.pack();
        Toolkit tk = f.getToolkit();
        PrintJob pj = tk.getPrintJob(f, titulo, null);
        Graphics g = null;
        try {
            if (pj != null) {
                g = pj.getGraphics();
                draw(x, y, g);
            }
        } finally {
            if (g != null) g.dispose();
            if (pj != null) pj.end();
            f.dispose();
        }
    }
}

And with that your method capturaProduto() gets like this:

public void capturaProduto() {    
    List<ProdutoImpresso> lp = new ArrayList<>();

    for (int i = 0; i < TbProdutosVenda.getRowCount(); i++) {
        ProdutoImpresso item = new ProdutoImpresso(
                TbProdutosVenda.getValueAt(i, 1).toString(),
                TbProdutosVenda.getValueAt(i, 2).toString(),
                TbProdutosVenda.getValueAt(i, 3).toString(),
                TbProdutosVenda.getValueAt(i, 6).toString());
        lp.add(item);
    }

    RelacaoDeProdutos r = new RelacaoDeProdutos(lp);
    r.imprimir("MP4200", 50, 30);
}

And then you no longer need to use the object imp class Impresso.

  • public class Relacaodeproducts Drawable Implements { private final List<Productbuy> items; public Relacaodeproducts(List<Productbuy> items) { this.items = item; } @Override public void draw(int x, int y, Graphics g) { g.Drawstring("Product relation", x, y); int Y2 = y + 40; for (Itemimpressao i : items) { i.draw(x, Y2, g); Y2 += 125; } } } In the snippet you refer to this.items = item; but item comes from where. And in the passage Itemimpressao i : items Itemimpressao refers to what?

  • @Claytonquintiliano Corrected. It’s because when I did that, I changed the name of classes and variables over and over and those two had fallen behind.

  • obtained an Exception in thread "AWT-Eventqueue-0" java.lang.Classcastexception: java.lang.String cannot be cast to java.lang.Integer. On the conversion of this object (Integer) Tbproducessvenda.getValueAt(i, 1)

  • @Claytonquintilian was in the getValueAt(i, 1)? If so, it’s because he wasn’t int, and yes String even.

  • Yes it was in this same item, you say that it is String in the model of Jtable? If it is there all like objects.

  • @Claytonquintiliano Edited again. Apparently he’s always coming as String in the JTable. But forcing with the toString() as long as you don’t come null, it solves for any type, at least for the simple types you are using so far, whether or not String.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.