Carrinho de compras em Swing

9 respostas
zap

Pessoal, alguem ja desenvolveu algo parecido com a Loja Virtual/ ShoppingCart utilizando Swing ??

Estou com dificuldades em algums pontos com Swing, tal como navegacao de telas, onde manter os objetos que estarao em memoria.

No JavaEE teria um objeto “carrinhoCompra” na session.
O controle de telas ficaria a cargo de um Servlet (ou Action) que direcionaria uma pagina jsp para outra.

Com JavaEE eu sei como faz, mas como isso tudo ficaria usando o Swing ???

Eu deveria ter um JFrame principal, e teria q ter tres telas (em sequencia) para o carrinho de compras.

O objeto carrinhoCompra deveria ficar no JFrame principal ?
Cada tela carrinho seria um JFrame (e nesse caso teria 4 JFrames) ?
Como fazer a navegacao entre as telas do carrinho de compras ? Da tela 1, para a tela 2. E da 2 para a 3.

Obrigado

9 Respostas

B

Rodando localmente você pode ter uma classe auxiliar, que tenha um atributo estático do tipo Carrinho para cada usuário, por exemplo.

Você também pode colocar o objeto carrinho dentro da instância do usuário que estiver logado no momento, mas isso limita que dois usuários se logem ao mesmo tempo.

Depende de como sua aplicação vai funcionar, se ela estiver rodando dentro de apenas uma JVM atributos estáticos podem ser a solução… Caso esteja trabalhando na rede você tem que pensar em alguma maneira de persistir estes dados. Um BD não é a solução ideal, mas trabalhando com Swing você terá muitas limitações.

zap

Obrigado por responder Bruno,

O caso do carrinho foi so um exemplo, na realidade eu preciso eh saber o como controlar o fluxo entre tres telas, que devem ter uma navegacao de avancar e voltar.

No caso de um sistama web eu teria tres jsp’s, e no botao avancar eu colocaria uma acao que chamaria uma Servlet que por sua vez passaria da pagina01.jsp para a pagina02.jsp, e da pagina02.jsp para a pagina03.jsp. O Botao voltar faria o mesmo, so que o fluxo inverso.

E num sistema Swing ? Como ficaria isso ? Teria tres JFrame’s, um pra cada telas ?

E outra coisa, um objeto do tipo pedidoVenda, que representaria as informacoes do pedido, para as tres telas, Onde ficaria esse objeto ? No Frame Principal ?

Ironlynx

Várias formas, mas eu recomendaria vc usar JInternalFrame para cada uma dessas telas dentro do JFrame principal, passando um atributo a esse JFrame em cada uma.Vc as deixará navegáveis e manipuláveis pois elas estarão associadas ao “pai”(Jframe).

Vc pode tb passá-lo como referência(ou um atributo static) no construtor(por exemplo) para cada tela que irá manipulá-lo.Claro que vc terá que ter atenção quando for instânciá-lo e quando for populá-lo tomando cuidado para não recriá-lo ou repopular.

zap

Fiz um pequeno exemplo, gostaria de saber se o caminho eh esse mesmo:

/**
 * 
 */
package br.gui;

import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JDesktopPane;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import java.awt.GridBagConstraints;
import javax.swing.JInternalFrame;
import java.awt.Rectangle;
import java.awt.Insets;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

import br.bean.CarrinhoComprasBean;

/**
 * @author zap
 *
 */
public class CarrinhoComprasInicial extends JFrame {
	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JPanel botoesJPanel = null;
	private JDesktopPane jDesktopPane = null;
	private JButton carrinhoJButton = null;
	private JInternalFrame carrinho01JInternalFrame = null;
	private JPanel carrinho01JContentPane = null;
	private JPanel botoesCarrinho01JPanel = null;
	private JButton botaoAvancarCarrinho01JButton = null;
	private JButton botaoVoltarCarrinho01JButton = null;
	private JLabel infoCarrinho01JLabel = null;
	private JInternalFrame carrinho02JInternalFrame = null;
	private JPanel carrinho02JContentPane = null;
	private JPanel botoesCarrinho02JPanel = null;
	private JButton botaoVoltarCarrinho02JButton = null;
	private JButton botaoAvancarCarrinho02JButton = null;
	private JLabel infoCarrinho02JLabel = null;
	
	private CarrinhoComprasBean carrinhoComprasBean = null;
	private JButton botaoSairCarrinho01JButton = null;
	private JButton botaoSairCarrinho02JButton = null;
	
	/**
	 * This method initializes botoesJPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getBotoesJPanel(){
		if( botoesJPanel == null ){
			GridBagConstraints gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.anchor = GridBagConstraints.CENTER;
			botoesJPanel = new JPanel();
			botoesJPanel.setLayout(new GridBagLayout());
			botoesJPanel.add(getCarrinhoJButton(), gridBagConstraints);
		}
		return botoesJPanel;
	}

	/**
	 * This method initializes jDesktopPane	
	 * 	
	 * @return javax.swing.JDesktopPane	
	 */
	private JDesktopPane getJDesktopPane(){
		if( jDesktopPane == null ){
			jDesktopPane = new JDesktopPane();
			jDesktopPane.add(getCarrinho01JInternalFrame(), null);
			jDesktopPane.add(getCarrinho02JInternalFrame(), null);
		}
		return jDesktopPane;
	}

	/**
	 * This method initializes carrinhoJButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getCarrinhoJButton(){
		if( carrinhoJButton == null ){
			carrinhoJButton = new JButton();
			carrinhoJButton.setText("Carrinho");
			carrinhoJButton.addActionListener( new java.awt.event.ActionListener() {
				public void actionPerformed( java.awt.event.ActionEvent e ){
					System.out.println( "CarrinhoJButton actionPerformed()" ); // TODO Auto-generated Event stub actionPerformed()
					carrinho01JInternalFrame.setVisible( true );
					carrinhoComprasBean = new CarrinhoComprasBean();
				}
			} );
		}
		return carrinhoJButton;
	}

	/**
	 * This method initializes carrinho01JInternalFrame	
	 * 	
	 * @return javax.swing.JInternalFrame	
	 */
	private JInternalFrame getCarrinho01JInternalFrame(){
		if( carrinho01JInternalFrame == null ){
			carrinho01JInternalFrame = new JInternalFrame();
			carrinho01JInternalFrame.setBounds(new Rectangle(89, 63, 609, 415));
			carrinho01JInternalFrame.setTitle("Carrinho Tela 01");
			carrinho01JInternalFrame.setContentPane(getCarrinho01JContentPane());
		}
		return carrinho01JInternalFrame;
	}

	/**
	 * This method initializes carrinho01JContentPane	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getCarrinho01JContentPane(){
		if( carrinho01JContentPane == null ){
			infoCarrinho01JLabel = new JLabel();
			infoCarrinho01JLabel.setText("Primeira tela do carrinho de compras: adicionar itens ao carrinho");
			infoCarrinho01JLabel.setHorizontalAlignment(SwingConstants.CENTER);
			carrinho01JContentPane = new JPanel();
			carrinho01JContentPane.setLayout(new BorderLayout());
			carrinho01JContentPane.add(getBotoesCarrinho01JPanel(), BorderLayout.NORTH);
			carrinho01JContentPane.add(infoCarrinho01JLabel, BorderLayout.CENTER);
		}
		return carrinho01JContentPane;
	}

	/**
	 * This method initializes botoesCarrinho01JPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getBotoesCarrinho01JPanel(){
		if( botoesCarrinho01JPanel == null ){
			GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
			gridBagConstraints5.gridx = 4;
			gridBagConstraints5.gridy = 0;
			GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
			gridBagConstraints2.insets = new Insets(4, 4, 4, 4);
			gridBagConstraints2.gridy = 0;
			gridBagConstraints2.gridx = 3;
			GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
			gridBagConstraints1.gridx = 1;
			gridBagConstraints1.insets = new Insets(4, 4, 4, 4);
			gridBagConstraints1.gridwidth = 2;
			gridBagConstraints1.gridy = 0;
			botoesCarrinho01JPanel = new JPanel();
			botoesCarrinho01JPanel.setLayout(new GridBagLayout());
			botoesCarrinho01JPanel.add(getBotaoAvancarCarrinho01JButton(), gridBagConstraints2);
			botoesCarrinho01JPanel.add(getBotaoVoltarCarrinho01JButton(), gridBagConstraints1);
			botoesCarrinho01JPanel.add(getBotaoSairCarrinho01JButton(), gridBagConstraints5);
		}
		return botoesCarrinho01JPanel;
	}

	/**
	 * This method initializes botaoAvancarCarrinho01JButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBotaoAvancarCarrinho01JButton(){
		if( botaoAvancarCarrinho01JButton == null ){
			botaoAvancarCarrinho01JButton = new JButton();
			botaoAvancarCarrinho01JButton.setText("Avancar");
			botaoAvancarCarrinho01JButton.addActionListener( new java.awt.event.ActionListener() {
				public void actionPerformed( java.awt.event.ActionEvent e ){
					carrinho01JInternalFrame.setVisible( false );
					carrinho02JInternalFrame.setVisible( true );
					System.out.println( "BotaoAvancarCarrinho01JButton actionPerformed()" ); // TODO Auto-generated Event stub actionPerformed()
				}
			} );
		}
		return botaoAvancarCarrinho01JButton;
	}

	/**
	 * This method initializes botaoVoltarCarrinho01JButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBotaoVoltarCarrinho01JButton(){
		if( botaoVoltarCarrinho01JButton == null ){
			botaoVoltarCarrinho01JButton = new JButton();
			botaoVoltarCarrinho01JButton.setText("Voltar");
			botaoVoltarCarrinho01JButton.setEnabled(false);
		}
		return botaoVoltarCarrinho01JButton;
	}

	/**
	 * This method initializes carrinho02JInternalFrame	
	 * 	
	 * @return javax.swing.JInternalFrame	
	 */
	private JInternalFrame getCarrinho02JInternalFrame(){
		if( carrinho02JInternalFrame == null ){
			carrinho02JInternalFrame = new JInternalFrame();
			carrinho02JInternalFrame.setBounds(new Rectangle(89, 63, 609, 415));
			carrinho02JInternalFrame.setTitle("Carrinho Tela 02");
			carrinho02JInternalFrame.setContentPane(getCarrinho02JContentPane());
		}
		return carrinho02JInternalFrame;
	}

	/**
	 * This method initializes carrinho02JContentPane	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getCarrinho02JContentPane(){
		if( carrinho02JContentPane == null ){
			infoCarrinho02JLabel = new JLabel();
			infoCarrinho02JLabel.setText("Segunda tela do carrinho de compras: informar formas de pagamento");
			infoCarrinho02JLabel.setHorizontalAlignment(SwingConstants.CENTER);
			carrinho02JContentPane = new JPanel();
			carrinho02JContentPane.setLayout(new BorderLayout());
			carrinho02JContentPane.add(getBotoesCarrinho02JPanel(), BorderLayout.NORTH);
			carrinho02JContentPane.add(infoCarrinho02JLabel, BorderLayout.CENTER);
		}
		return carrinho02JContentPane;
	}

	/**
	 * This method initializes botoesCarrinho02JPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getBotoesCarrinho02JPanel(){
		if( botoesCarrinho02JPanel == null ){
			GridBagConstraints gridBagConstraints6 = new GridBagConstraints();
			gridBagConstraints6.gridx = 2;
			gridBagConstraints6.gridy = 0;
			GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
			gridBagConstraints4.insets = new Insets(4, 4, 4, 4);
			GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
			gridBagConstraints3.gridx = 1;
			gridBagConstraints3.insets = new Insets(4, 4, 4, 4);
			gridBagConstraints3.gridy = 0;
			botoesCarrinho02JPanel = new JPanel();
			botoesCarrinho02JPanel.setLayout(new GridBagLayout());
			botoesCarrinho02JPanel.add(getBotaoVoltarCarrinho02JButton(), gridBagConstraints4);
			botoesCarrinho02JPanel.add(getBotaoAvancarCarrinho02JButton(), gridBagConstraints3);
			botoesCarrinho02JPanel.add(getBotaoSairCarrinho02JButton(), gridBagConstraints6);
		}
		return botoesCarrinho02JPanel;
	}

	/**
	 * This method initializes botaoVoltarCarrinho02JButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBotaoVoltarCarrinho02JButton(){
		if( botaoVoltarCarrinho02JButton == null ){
			botaoVoltarCarrinho02JButton = new JButton();
			botaoVoltarCarrinho02JButton.setText("Voltar");
			botaoVoltarCarrinho02JButton.addActionListener( new java.awt.event.ActionListener() {
				public void actionPerformed( java.awt.event.ActionEvent e ){
					carrinho01JInternalFrame.setVisible( true );
					carrinho02JInternalFrame.setVisible( false );
					System.out.println( "BotaoVoltarCarrinho02JButton actionPerformed()" ); // TODO Auto-generated Event stub actionPerformed()
				}
			} );
		}
		return botaoVoltarCarrinho02JButton;
	}

	/**
	 * This method initializes botaoAvancarCarrinho02JButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBotaoAvancarCarrinho02JButton(){
		if( botaoAvancarCarrinho02JButton == null ){
			botaoAvancarCarrinho02JButton = new JButton();
			botaoAvancarCarrinho02JButton.setText("Avancar");
			botaoAvancarCarrinho02JButton.setEnabled(false);
		}
		return botaoAvancarCarrinho02JButton;
	}

	/**
	 * This method initializes botaoSairCarrinho01JButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBotaoSairCarrinho01JButton(){
		if( botaoSairCarrinho01JButton == null ){
			botaoSairCarrinho01JButton = new JButton();
			botaoSairCarrinho01JButton.setText("Sair");
			botaoSairCarrinho01JButton.addActionListener( new java.awt.event.ActionListener() {
				public void actionPerformed( java.awt.event.ActionEvent e ){
					System.out.println( "BotaoSairCarrinho01JButton actionPerformed()" ); // TODO Auto-generated Event stub actionPerformed()
					sairCarrinhoCompras();
				}
			} );
		}
		return botaoSairCarrinho01JButton;
	}

	/**
	 * This method initializes botaoSairCarrinho02JButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBotaoSairCarrinho02JButton(){
		if( botaoSairCarrinho02JButton == null ){
			botaoSairCarrinho02JButton = new JButton();
			botaoSairCarrinho02JButton.setText("Sair");
			botaoSairCarrinho02JButton.addActionListener( new java.awt.event.ActionListener() {
				public void actionPerformed( java.awt.event.ActionEvent e ){
					System.out.println( "BotaoSairCarrinho02JButton actionPerformed()" ); // TODO Auto-generated Event stub actionPerformed()
					sairCarrinhoCompras();
				}
			} );
		}
		return botaoSairCarrinho02JButton;
	}
	
	private void sairCarrinhoCompras(){
		carrinhoComprasBean = null;
		carrinho01JInternalFrame.dispose();
		carrinho02JInternalFrame.dispose();
		
	}
	
	/**
	 * @param args
	 */
	public static void main( String[] args ){
		// TODO Auto-generated method stub
		SwingUtilities.invokeLater( new Runnable() {
			public void run(){
				CarrinhoComprasInicial thisClass = new CarrinhoComprasInicial();
				thisClass.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
				thisClass.setVisible( true );
			}
		} );
	}
	
	/**
	 * This is the default constructor
	 */
	public CarrinhoComprasInicial(){
		super();
		initialize();
	}
	
	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize(){
		this.setSize( 800, 600 );
		this.setContentPane( getJContentPane() );
		this.setTitle("Carrinho de Compras");
	}
	
	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane(){
		if( jContentPane == null ){
			jContentPane = new JPanel();
			jContentPane.setLayout( new BorderLayout() );
			jContentPane.add(getBotoesJPanel(), BorderLayout.NORTH);
			jContentPane.add(getJDesktopPane(), BorderLayout.CENTER);
		}
		return jContentPane;
	}
}
/**
 * 
 */
package br.bean;

import java.util.Date;
import java.util.List;

/**
 * @author zap
 *
 */
public class CarrinhoComprasBean {
	
	private Long id;
	private Date data;
	private List<ItemCarrinhoCompras> listaItens;
	
	public CarrinhoComprasBean(){
		super();
		this.id = null;
		this.data = null;
		this.listaItens = null;
	}

	public CarrinhoComprasBean( Long id, Date data, List<ItemCarrinhoCompras> listaItens ){
		super();
		this.id = id;
		this.data = data;
		this.listaItens = listaItens;
	}
	
}
/**
 * 
 */
package br.bean;

/**
 * @author zap
 * 
 */
public class ItemCarrinhoCompras {
	private Long id;
	private String descricao;
	private Double preco;
	private Double quantidade;
	
	public ItemCarrinhoCompras(){
		super();
		this.id = null;
		this.descricao = null;
		this.preco = null;
		this.quantidade = null;
	}
	
	public ItemCarrinhoCompras( Long id, String descricao, Double preco, Double quantidade ){
		super();
		this.id = id;
		this.descricao = descricao;
		this.preco = preco;
		this.quantidade = quantidade;
	}
}

Para alternar entre as telas deveria somente setar visivel para true ou false ?
E para sair ? O dispose esta correto ? Ao clicar no botao sair nao consigo acessar a tela novamente atrave do botao Carrinho

zap

Alguma sugestao ?

Fernando_Generoso_da

Eu não utilizaria telas, se não fosse EXTREMAMENTE necessário. Se são forms diferentes, pq não utiliza TabbedPanes??

http://java.sun.com/docs/books/tutorial/uiswing/components/tabbedpane.html.

Para cada TabbedPane, você coloca um formulário diferente…aí o cliente selecionaria o tabbled pane facilmente e preencheria.
Agora, se para o preenchimento do segundo formulário, por exemplo, é necesseário o preenchimento do primeiro, então tu vai ter que utilizar um JDialog, que é modal.

Fernando

zap

A necessidade eh simplesmente a exigencia, por parte do cliente, deste tipo de navegacao atraves de telas. Isso eh devido ah conversao de um sistema antigo em forms.

Eu tinha feito alguns teste com o JTabbedPane, e funcionou sim. Mas o caso eh que precisava ser uma tela chamando outra.

A verdade eh que ainda nao estou bem certo da melhor forma de modelar essas telas em Swing. Nao sei o JDesktopPane com JInternalFrame’s sao a melhor opcao.
E ainda estou apanhando um pouco com a escolha do(s) gerenciador de layout

Fernando_Generoso_da

Cara,
me veio uma idéia na cabeça, não sei se é viagem, mas tudo bem :slight_smile:

Faz um form principal, onde tu irá renderizar os panels, que serão suas telas…
aí tu empilha esses panels…e fica trabalhando…chama um panel(empilha), volta pro panel anterior(desempilha)…e assim tu vai controlando tua navegação, apenas fazendo um swap no teu frame principal, dos panels que tu precisar…

foi só uma idéia maluca…

Fernando

zap

Valeu … acho q esse pode ser um caminho a seguir mesmo.
Vou usar para isso o CardLayout, que tinham me sugerido.

abcs

Criado 17 de abril de 2009
Ultima resposta 30 de abr. de 2009
Respostas 9
Participantes 4