Swing

8 respostas
R

Galera estou estudando Swing e o problema é o seguinte:
1- fiz um programa que soma dois números e retorna um Jtextarea com o resultado.
ele está compilando: segue o código:

public class Main {

	public static void main(String[] args) {
		Janela j = new Janela("Robson");
		j.repaint();
		
	}
}
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.text.PlainDocument;







public class Janela extends JFrame{
	private JLabel lbTitulo;
	private JTextField tf1;
	private JTextField tf2;
	private JTextField tf3;
	private JButton btOk;
	private JButton btFechar;

	

	public Janela (String titulo){
		super(titulo);
		
		Container c = this.getContentPane();
		c.setLayout(null);


		setSize(380, 270);
		setResizable(false);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);
		CriarLabel(c);
		CriarTextField(c);
		CriarBotao(c);
	}

	public void CriarLabel(Container c){
		this.lbTitulo = new JLabel("Calcular");
		
		this.lbTitulo.setBounds(130, 20, 200, 20);
		this.lbTitulo.setFont(new Font("Arial", Font.BOLD, 16));
		this.lbTitulo.setForeground(Color.BLUE);
		this.lbTitulo.setToolTipText("Calcula Alguma Coisa");
		
		c.add(this.lbTitulo);
		
	}
	public void CriarTextField(Container c){
		this.tf1 = criaTextFieldNumero(c, "Número 1:", 60);
		this.tf2 = criaTextFieldNumero(c, "Número 2:", 85);
		
	
	
	}
	
	private JTextField criaTextFieldNumero(Container c, String rotulo, int posY) {
		JLabel lb = new JLabel(rotulo);
		lb.setBounds(20, posY, 60, 20);
		c.add(lb);

		JTextField tfNum = new JTextField(20);
		tfNum.setToolTipText(rotulo);
		tfNum.setBounds(85, posY, 100, 20);
		
		c.add(tfNum);

		return tfNum;
	}
	public void CriarBotao(Container c){
		
		this.btOk = new JButton("Ok");
		this.btFechar = new JButton("Fechar");

		this.btOk.setBounds(115, 200, 60, 20);
		this.btFechar.setBounds(195, 200, 80, 20);

		this.btOk.setToolTipText("Clique aqui para confirmar");
		this.btFechar.setToolTipText("Clique aqui para fechar o programa");

		this.btOk.setActionCommand("OK");
		this.btFechar.setActionCommand("FECHAR");
		
		OuvinteBotao ouvinteBotao = new OuvinteBotao();

		this.btOk.addActionListener(ouvinteBotao);
		this.btFechar.addActionListener(ouvinteBotao);

		c.add(this.btOk);
		c.add(this.btFechar);
		
		
	}
	
  
	    
		private class OuvinteBotao implements ActionListener {  
			  
	        @Override  
	        public void actionPerformed(ActionEvent ae) {  
	  
	            if (ae.getSource() instanceof JButton) {  
	                JButton jb = (JButton) ae.getSource();  
	                if ("OK".equals(jb.getActionCommand())) {  
	  
	                    System.out.println("Tela de resultado");  
	                    //mande a soma por parametro do construtor  
	                    Jsoma js = new Jsoma("Resultado", (Integer.parseInt(tf1.getText())+Integer.parseInt(tf2.getText())));  
	                } else if ("FECHAR".equals(jb.getActionCommand())) {  
	                    System.exit(1);  
	                }  
	            }  
	        }  
	    }
	}
import java.awt.*;  
import java.awt.event.*;  
import javax.swing.*;  
import javax.swing.border.Border;  
import javax.swing.text.JTextComponent;  
  
@SuppressWarnings("serial")  
public class Jsoma extends JWindow {  
  
    private JLabel lbTitulo;  
    private JButton btFechar;  
    private JTextArea resultTextArea;  
    private Integer resultado;  
  
    public Jsoma(String titulo, Integer soma) {  
  
        Container c = this.getContentPane();  
  
        Border raisedBorder = BorderFactory.createRaisedBevelBorder();  
        ((JComponent) c).setBorder(raisedBorder);  
  
        c.setLayout(null);  
  
        setSize(500, 270);  
        setLocationRelativeTo(null);  
          
        this.resultado = soma;  
  
          
          
        this.criarLabels(c);  
        this.criarBotoes(c);  
        this.createTextArea(c);  
  
        setVisible(true);  
  
    }  
  
    private void createTextArea(Container c) {  
        //aqui foi alterado e agora criado um area de texto e pega o que foi guardado no objeto resultado  
        JTextArea areaResultado = new JTextArea();  
        areaResultado.setText("Soma: "+this.resultado);  
        areaResultado.setEditable(false);  
        areaResultado.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));  
  
        JScrollPane scroller = new JScrollPane(areaResultado);  
        scroller.setBounds(20, 60, 450, 130);  
        scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);  
        scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);  
  
        c.add(scroller);  
  
    }  
  
    private void criarLabels(Container c) {  
        this.lbTitulo = new JLabel("Resultado");  
        this.lbTitulo.setBounds(200, 20, 200, 20);  
        this.lbTitulo.setFont(new Font("Arial", Font.BOLD, 16));  
        this.lbTitulo.setForeground(Color.BLUE);  
        this.lbTitulo.setToolTipText("Calculor de Primos");  
        c.add(this.lbTitulo);  
    }  
  
    private void criarBotoes(Container c) {  
        this.btFechar = new JButton("Fechar");  
        this.btFechar.setBounds(200, 200, 80, 20);  
        this.btFechar.setToolTipText("");  
        this.btFechar.setActionCommand("FECHAR");  
  
        OuvinteBotao ouvinteBotao = new OuvinteBotao();  
        this.btFechar.addActionListener(ouvinteBotao);  
  
        c.add(this.btFechar);  
    }  
  
    // classe private para tratar os eventos dos botões  
    private class OuvinteBotao implements ActionListener {  
  
        @Override  
        public void actionPerformed(ActionEvent ae) {  
            if (ae.getSource() instanceof JButton) {  
                JButton jb = (JButton) ae.getSource();  
                if ("FECHAR".equals(jb.getActionCommand())) {  
                    Jsoma.this.dispose();
                }  
            }  
        }  
    }  
}

Agora queria saber se alguém pode me mostrar como fazer um prorama assim:
1- No lugar de somar duas textField eu queria, pegar todo o numero do text fild, ordena-lo e assim com o textfield abaixo, sendo que , para cada ação é executada uma
thread diferente. no fim ele ordena os numeros e retorna o numero maior depois de ordenado..

8 Respostas

ViniGodoy

Releia a última frase do seu tópico. Justamente quando você ia descrever o que queria, escreveu um texto sem pé nem cabeça.

Além disso, dúvidas de interface gráfica vão no fórum de interface gráfica. De threads no de Java Avançado.

Onde exatamente está sua dúvida? O que você não sabe fazer?

R
int numeros[] = new int[tf1.getText().length()];
	    				for (int i = 0; i <tf1.getText().length(); i++) {	
	    				numeros[i]= Integer.parseInt(tf1.getText());
	    				
	    				}	
	    				Arrays.sort(numeros); // metodo de ordenação do vetor
	    				for(int i = 0; i < 5; i++)
	    				System.out.println(numeros[i]);

o qeu eu quero fazer é ordenar os numeros que eu coloco no text field:
exemplo:
987654321=123456789 ai ordeno ele, esse codigo acima não esta dando certo, ele nao ta ordenando,

ViniGodoy
Troque isso:
for (int i = 0; i &lt;tf1.getText().length(); i++) {      
   numeros[i]= Integer.parseInt(tf1.getText());  
}
Por isso:
for (int i = 0; i &lt;tf1.getText().length(); i++) {      
   numeros[i] = tf1.getText().charAt(i);                    
}
>
Vingdel

Seu array não está sendo ordenado pois todos os índices estão recebendo o número completo.

Pense melhor nesta linha:numeros[i] = Integer.parseInt(tf1.getText());Abraço!

EDIT: Desculpe, demorei a enviar, por isso postagem foi feita com a resposta já concluida.

R

é verdade, estava lendo aqui e acho qeu tenho que implementar o comparato…
tem ?

R

reenviando, acho que não deu certo:
estou fazendo o que voce disse vinigodoy

codigo:
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.text.PlainDocument;







public class xjanela extends JFrame{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JLabel lbTitulo;
	private JTextField tf1;
	private JTextField tf2;
	private JButton btOk;
	private JButton btFechar;
	private int[] numeros;
	

	public xjanela (String titulo){
		super(titulo);
		
		Container c = this.getContentPane();
		c.setLayout(null);


		setSize(380, 270);
		setResizable(false);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);
		CriarLabel(c);
		CriarTextField(c);
		CriarBotao(c);
	}

	public void CriarLabel(Container c){
		this.lbTitulo = new JLabel("Calcular");
		
		this.lbTitulo.setBounds(130, 20, 200, 20);
		this.lbTitulo.setFont(new Font("Arial", Font.BOLD, 16));
		this.lbTitulo.setForeground(Color.BLUE);
		this.lbTitulo.setToolTipText("Calcula Alguma Coisa");
		
		c.add(this.lbTitulo);
		
	}
	public void CriarTextField(Container c){
		this.tf1 = criaTextFieldNumero(c, "Número 1:", 60);
		this.tf2 = criaTextFieldNumero(c, "Número 2:", 85);
		
	
	
	}
	
	private JTextField criaTextFieldNumero(Container c, String rotulo, int posY) {
		JLabel lb = new JLabel(rotulo);
		lb.setBounds(20, posY, 60, 20);
		c.add(lb);

		JTextField tfNum = new JTextField(20);
		tfNum.setToolTipText(rotulo);
		tfNum.setBounds(85, posY, 100, 20);
		
		c.add(tfNum);

		return tfNum;
	}
	public void CriarBotao(Container c){
		
		this.btOk = new JButton("Ok");
		this.btFechar = new JButton("Fechar");

		this.btOk.setBounds(115, 200, 60, 20);
		this.btFechar.setBounds(195, 200, 80, 20);

		this.btOk.setToolTipText("Clique aqui para confirmar");
		this.btFechar.setToolTipText("Clique aqui para fechar o programa");

		this.btOk.setActionCommand("OK");
		this.btFechar.setActionCommand("FECHAR");
		
		OuvinteBotao ouvinteBotao = new OuvinteBotao();

		this.btOk.addActionListener(ouvinteBotao);
		this.btFechar.addActionListener(ouvinteBotao);

		c.add(this.btOk);
		c.add(this.btFechar);
		
		
	}
	

		private class OuvinteBotao implements ActionListener {  
			  
	        @Override  
	        public void actionPerformed(ActionEvent ae) {  
	  
	            if (ae.getSource() instanceof JButton) {  
	                JButton jb = (JButton) ae.getSource();  
	                if ("OK".equals(jb.getActionCommand())) {  
	  
	                    System.out.println("Tela de resultado");  
	                    
	                   
	                    int numeros[] = new int[tf1.getText().length()];  
	                    for (int i = 0; i <tf1.getText().length(); i++) {      
	                    numeros[i]= tf1.getText().charAt(i)  ;
	                      
	                    }     
	                    Arrays.sort(numeros); // metodo de ordenação do vetor  
	                    for(int i = 0; i < 5; i++)  
	                    System.out.println(numeros[i]);   
	                   
	                } else if ("FECHAR".equals(jb.getActionCommand())) {  
	                    System.exit(1);  
	                }  
	            }  
	        } 
		}}

o resultado que aparece é o seguinte:
Tela de resultado
[I@1457cb

obrigado desde já.

ViniGodoy
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class XJanela extends JFrame {
	private static final long serialVersionUID = 1L;
	private JLabel lbTitulo;
	private JTextField tf1;
	private JTextField tf2;
	private JButton btOk;
	private JButton btFechar;

	public XJanela(String titulo) {
		super(titulo);

		Container c = this.getContentPane();
		c.setLayout(null);

		setSize(380, 270);
		setResizable(false);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		CriarLabel(c);
		CriarTextField(c);
		CriarBotao(c);
	}

	public void CriarLabel(Container c) {
		this.lbTitulo = new JLabel(&quot;Calcular&quot;);

		this.lbTitulo.setBounds(130, 20, 200, 20);
		this.lbTitulo.setFont(new Font(&quot;Arial&quot;, Font.BOLD, 16));
		this.lbTitulo.setForeground(Color.BLUE);
		this.lbTitulo.setToolTipText(&quot;Calcula Alguma Coisa&quot;);

		c.add(this.lbTitulo);

	}

	public void CriarTextField(Container c) {
		this.tf1 = criaTextFieldNumero(c, &quot;Número 1:&quot;, 60);
		this.tf2 = criaTextFieldNumero(c, &quot;Número 2:&quot;, 85);

	}

	private JTextField criaTextFieldNumero(Container c, String rotulo, int posY) {
		JLabel lb = new JLabel(rotulo);
		lb.setBounds(20, posY, 60, 20);
		c.add(lb);

		JTextField tfNum = new JTextField(20);
		tfNum.setToolTipText(rotulo);
		tfNum.setBounds(85, posY, 100, 20);

		c.add(tfNum);

		return tfNum;
	}

	public void CriarBotao(Container c) {

		this.btOk = new JButton(&quot;Ok&quot;);
		this.btFechar = new JButton(&quot;Fechar&quot;);

		this.btOk.setBounds(115, 200, 60, 20);
		this.btFechar.setBounds(195, 200, 80, 20);

		this.btOk.setToolTipText(&quot;Clique aqui para confirmar&quot;);
		this.btFechar.setToolTipText(&quot;Clique aqui para fechar o programa&quot;);

		this.btOk.setActionCommand(&quot;OK&quot;);
		this.btFechar.setActionCommand(&quot;FECHAR&quot;);

		this.btOk.addActionListener(new OuvinteOk());
		this.btFechar.addActionListener(new OuvinteFechar());

		c.add(this.btOk);
		c.add(this.btFechar);

	}
	
	private class OuvinteOk implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent ae) {
			System.out.println(&quot;Tela de resultado&quot;);

			int numeros[] = new int[tf1.getText().length()];
			for (int i = 0; i &lt; tf1.getText().length(); i++) {
				numeros[i] = Integer.parseInt(&quot;&quot;
						+ tf1.getText().charAt(i));

			}
			Arrays.sort(numeros); // metodo de ordenação do vetor
			for (int i = 0; i &lt; numeros.length; i++)
				System.out.print(numeros[i]);
			System.out.println();
		}
		
	}

	private class OuvinteFechar implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent ae) {
			System.exit(0);
		}
	}
	public static void main(String[] args) {
		new XJanela(&quot;Ordenação&quot;).setVisible(true);
	}
}
ViniGodoy

Movido para o fórum de Interface Gráfica. Por favor, leia atentamente a descrição dos fóruns antes de postar.

Criado 12 de junho de 2011
Ultima resposta 13 de jun. de 2011
Respostas 8
Participantes 3