Problemas com Codigo, Programa que formata um texto em uma JTextField

6 respostas
J

Buenas Pessoal…

Estou tentando elaborar um aplicativo em java que formate um texto. Com algumas opções de fontes Acionadas por JRadioButton e também opção de negrito e itálico ativadas através de um JCheckBox porem o problema aconteceu na hora de ativar a função das JCheckBox

foram criadas algumas condições de formatação, como:

if (negrito.isSelected() && italico.isSelected())

font1 = new Font( Serif, Font.BOLD + Font.ITALIC, 14);

No entanto, não queria mudar a fonte, nesse momento somente o negrito e italico; Mas esse comando Font, pede a forma da letra como um atributo"obrigatório".

Bom irei compartilhar o codigo fonte do programa, se possível me ajudem rsrsrs

Vlw Galera!

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;


public class Gui extends JFrame{

	private JTextField tf;

	private Font FSerif;
	private Font FMonospaced;
	private Font FSansSerif;
	private Font FTimesRoman;
	
	private Font fnegrito;
	private Font fitalico;
	
	private JCheckBox negrito;
	private JCheckBox italico;

	private JRadioButton Serif;
	private JRadioButton Monospaced;
	private JRadioButton SansSerif;
	private JRadioButton TimesRoman;
	
	
	private ButtonGroup group;
	
	public Gui(){
		super ("By JohnnyBoy");
		setLayout  (new FlowLayout());

		tf = new JTextField("Go Johnny, Go Johnny",25);
		add(tf);
		
		Serif = new JRadioButton("Serif",true);
		Monospaced = new JRadioButton("Monospaced",false);
		SansSerif = new JRadioButton("SansSerif",false);
		TimesRoman = new JRadioButton("TimesRoman",false);
		add(Serif);
		add(Monospaced);
		add(SansSerif);
		add(TimesRoman);
		
		
		
		negrito = new JCheckBox("negrito");
		italico = new JCheckBox("italico");
		add(negrito);
		add(italico);
	
	
	
	
	group = new ButtonGroup();
	group.add(Serif);
	group.add(Monospaced);
	group.add(SansSerif);
	group.add(TimesRoman);
	
	FSerif = new Font("Serif",Font.PLAIN,14);
	FMonospaced = new Font("Monospaced",Font.PLAIN,14);
	FSansSerif = new Font("SansSerif",Font.PLAIN,14);
	FTimesRoman = new Font("TimesRoman",Font.PLAIN,14);
	
	tf.setFont(FSerif);
	
	//espera o evento aconteçer. e passa a fonte do obj contrutor.
	Serif.addItemListener (new HandlerClass (FSerif));
	Monospaced.addItemListener (new HandlerClass (FMonospaced));
	SansSerif.addItemListener (new HandlerClass (FSansSerif));
	TimesRoman.addItemListener (new HandlerClass (FTimesRoman));
	
	
	negrito.addItemListener (new HandlerClass (fnegrito));
	italico.addItemListener (new HandlerClass (fitalico));
	
	negrito = new JCheckBox("negrito");
	italico = new JCheckBox("italico");
	
	HandlerClass handler = new HandlerClass(tf);
	negrito.addItemListener(handler);
	italico.addItemListener(handler);
	}

private class HandlerClass implements ItemListener{
	private Font font;
	
	
	public HandlerClass (Font f){
		font = f;
		}
	public HandlerClass(JTextField tf) {
		
	}
	public void itemStateChanged(ItemEvent event){
		tf.setFont(font);
	}
	public void itemStateChanged1(ItemEvent event1){
		Font font1 = null;
		
		if (negrito.isSelected() && italico.isSelected())
			font1 = new Font( "Serif", Font.BOLD + Font.ITALIC, 14);
			
			else if (negrito.isSelected())
			font1 = new Font("Serif",Font.BOLD,14);
			
			else if (italico.isSelected())
			font1 = new Font("Serif",Font.ITALIC,14);
			else
				font1 = new Font("Serif",Font.PLAIN,14);
		
		tf.setFont(font1);
		}
	}
	}

Esse programa é acessado por outra classe

import javax.swing.JFrame;
import javax.swing.JOptionPane;


public class apples {
	public static void main(String[] args) {

		
		//iog = apelido para o objeto da inferfacegrafica
		Gui go = new Gui();
			go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		go.setSize(300,250);
		go.setVisible(true);
		
		}
	}

6 Respostas

julianolandim

basta voce pegar a fonte que ja esta no seu JTextField

Abraço

J

Obrigado pela atenção Julianolandim…

Cara ainda não estou conseguindo fazer funcionar
Os checkbox

public void itemStateChanged1(ItemEvent event1){
Não estão sendo acessados pelo programa…

Neste programa ele troca as fontes do JTextField
consegi fazer eles funcionarem em programas separados. um para os radiobuttons escolhendo a fonte e outro com o checkbox escolhendo entre negrito e italico… Porem não consegui fazer os 2 no mesmo pograma

julianolandim

se voce puder postar a classe eu posso te falar aonde esta o erro.

julianolandim

rs… eu estava tão cansado que não tinha visto que vc ja tinha postado a classe acima, vou tentar resolver e ja e mando.
t+

julianolandim

pronto agora esta ai o que voce precisa, eu comentei tudo que nao usei no seu codigo,não apaguei para voce comparar, observe a forma que adicionei os Listener nos seus JComboBox e JCheckBox, observe tambem a forma que eu usei para mudar a fonte, ou seja quando vc escolhe a opcao de negrito ou italico ele nao muda a fonte somente o stilo e quando vc escolhe a fonte ele nao muda o stilo somente a fonte.
Teste ai e analise bem, porque o mais importante de tudo alem de funcionar é entender o codigo.

/**
 *
 * @author Juliano Landim 
 * @date 20/02/2012
 */

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class Gui extends JFrame {

    private JTextField tf;
    private Font FSerif;
    private Font FMonospaced;
    private Font FSansSerif;
    private Font FTimesRoman;
    private Font fnegrito;
    private Font fitalico;
    private JCheckBox negrito;
    private JCheckBox italico;
    private JRadioButton Serif;
    private JRadioButton Monospaced;
    private JRadioButton SansSerif;
    private JRadioButton TimesRoman;
    private ButtonGroup group;

    public Gui() {
        super("By JohnnyBoy");
        setLayout(new FlowLayout());

        tf = new JTextField("Go Johnny, Go Johnny", 25);
        add(tf);

        Serif = new JRadioButton("Serif", true);
        Monospaced = new JRadioButton("Monospaced", false);
        SansSerif = new JRadioButton("SansSerif", false);
        TimesRoman = new JRadioButton("TimesRoman", false);
        add(Serif);
        add(Monospaced);
        add(SansSerif);
        add(TimesRoman);



        negrito = new JCheckBox("negrito");
        italico = new JCheckBox("italico");
        add(negrito);
        add(italico);


        negrito.addActionListener(new ActionListener() { // listener para negrito

            @Override
            public void actionPerformed(ActionEvent ae) {
                mudaFonte();
            }
        });

        italico.addActionListener(new ActionListener() { // listener para italico

            @Override
            public void actionPerformed(ActionEvent ae) {
                mudaFonte();
            }
        });



        group = new ButtonGroup();
        group.add(Serif);
        group.add(Monospaced);
        group.add(SansSerif);
        group.add(TimesRoman);
        
        Serif.addActionListener(new ActionListener() { // listener para Serif

            @Override
            public void actionPerformed(ActionEvent ae) {
                tf.setFont(new Font("Serif", tf.getFont().getStyle(), 14));
            }
        });  
              
        Monospaced.addActionListener(new ActionListener() { // listener para mospaced

            @Override
            public void actionPerformed(ActionEvent ae) {
                tf.setFont(new Font("Monospaced", tf.getFont().getStyle(), 14));
            }
        });
        
        SansSerif.addActionListener(new ActionListener() { // listener para sansserif

            @Override
            public void actionPerformed(ActionEvent ae) {
                tf.setFont(new Font("SansSerif", tf.getFont().getStyle(), 14));
            }
        });    
        
        TimesRoman.addActionListener(new ActionListener() { // listener para timesroman

            @Override
            public void actionPerformed(ActionEvent ae) {
                tf.setFont(new Font("SansSerif", tf.getFont().getStyle(), 14));
            }
        });         
        
        //FSerif = new Font("Serif", tf.getFont().getStyle(), 14);
        //FMonospaced = new Font("Monospaced", tf.getFont().getStyle(), 14);
        //FSansSerif = new Font("SansSerif", tf.getFont().getStyle(), 14);
        //FTimesRoman = new Font("TimesRoman", tf.getFont().getStyle(), 14);

        //tf.setFont(FSerif);

   
        //espera o evento aconteçer. e passa a fonte do obj contrutor.  
       // Serif.addItemListener(new HandlerClass(FSerif));
       // Monospaced.addItemListener(new HandlerClass(FMonospaced));
       // SansSerif.addItemListener(new HandlerClass(FSansSerif));
       // TimesRoman.addItemListener(new HandlerClass(FTimesRoman));


        //negrito.addItemListener (new HandlerClass (fnegrito));  
        //italico.addItemListener (new HandlerClass (fitalico));  

        //negrito = new JCheckBox("negrito");  
        //italico = new JCheckBox("italico");  

        ///HandlerClass handler = new HandlerClass(tf);  
        //negrito.addItemListener(handler);  
        //italico.addItemListener(handler);  




    }

    public void mudaFonte() { // metodo que muda a fonte

        Font font1 = null;

        if (negrito.isSelected() && italico.isSelected()) {
            font1 = new Font(tf.getFont().getFamily(), Font.BOLD + Font.ITALIC, 14);
        } else if (negrito.isSelected()) {
            font1 = new Font(tf.getFont().getFamily(), Font.BOLD, 14);
        } else if (italico.isSelected()) {
            font1 = new Font(tf.getFont().getFamily(), Font.ITALIC, 14);
        } else {
            font1 = new Font(tf.getFont().getFamily(), Font.PLAIN, 14);
        }

        tf.setFont(font1);

    }

   /** 
    private class HandlerClass implements ItemListener {

        private Font font;

        public HandlerClass(Font f) {
            font = f;
        }

        public HandlerClass(JTextField tf) {
        }

        public void itemStateChanged(ItemEvent event) {
            
            if(event.getSource().equals(FMonospaced)){
                tf.setFont(new Font("Monospaced", tf.getFont().getStyle(), 14));
                System.out.println("ok");
            }else if(event.getSource().equals(FSerif)){
                tf.setFont(new Font("Serif", tf.getFont().getStyle(), 14));
            }else{
                tf.setFont(font);
            }
        }

        //public void itemStateChanged1(ItemEvent event1) {
         //   Font font1 = null;

         //   if (negrito.isSelected() && italico.isSelected()) {
         //       font1 = new Font("Serif", Font.BOLD + Font.ITALIC, 14);
         //   } else if (negrito.isSelected()) {
         //       font1 = new Font("Serif", Font.BOLD, 14);
         //   } else if (italico.isSelected()) {
         //       font1 = new Font("Serif", Font.ITALIC, 14);
         //   } else {
         //       font1 = new Font("Serif", Font.PLAIN, 14);
         //   }

         //   tf.setFont(font1);
       // }
    }
    
    */
}
J

Obrigado julianolandim, ajudou mtu aqui. Valeu Fera!

Pessoal, estou continuando esse "exercício"

O código está desta forma. Foram adicionados um botão, que mostra uma JOptionPane, com as características da fonte selecionada. Porem consegui faze-la imprimir o negrito e itálico. Mas o nome da fonte não consegui, não achei o local correto para declarar a variável do tipo String FontNome , e também não consegui inicializar um valor de acordo com o JRadioButton selecionado.

import java.awt.FlowLayout;  
import java.awt.Font;  
import java.awt.event.ActionEvent;  
import java.awt.event.ActionListener;  

  
import javax.swing.*;  

public class FonteEditor extends JFrame {  
  
    private JTextField tf;  

    private JCheckBox negrito;  
    private JCheckBox italico;  
    private JRadioButton Serif;  
    private JRadioButton Monospaced;  
    private JRadioButton SansSerif;  
    private JRadioButton TimesRoman;  
    private ButtonGroup group;  
  
    private JButton botao;

    String FontNome;

	private String FontTip;
    
    public FonteEditor() {  
    	
        super("By JohnnyBoy");  
        setLayout(new FlowLayout());  
        
       //Onde declarar  FontNome?
        String FontNome ;
        
        tf = new JTextField("Go Johnny, Go Johnny", 25);  
        add(tf);  
  
        Serif = new JRadioButton("Serif", true);  
        Monospaced = new JRadioButton("Monospaced", false);  
        SansSerif = new JRadioButton("SansSerif", false);  
        TimesRoman = new JRadioButton("TimesRoman", false);
         
        add(Serif);  
        add(Monospaced);  
        add(SansSerif);  
        add(TimesRoman);  

  
  
        negrito = new JCheckBox("negrito");  
        italico = new JCheckBox("italico");  
        add(negrito);  
        add(italico);  
  
        botao = new JButton("BOtão");
        add(botao);
        botao.addActionListener(new ActionListener()
        {
        	public void actionPerformed(ActionEvent event){
	        	JOptionPane.showMessageDialog(null,"FONTE SELECIONADA FOI: "+FontNome+" "+FontTip+" "+getState());	
        	}
        });
        
     // listener para negrito  e italico
        negrito.addActionListener(new ActionListener() { 
  
            @Override  
            public void actionPerformed(ActionEvent ae) {  
                mudaFonte();
             
            }  
        });  
        italico.addActionListener(new ActionListener() {  
  
            @Override  
            public void actionPerformed(ActionEvent ae) {  
                mudaFonte();  
                
            }  
        });  
  
  
  
        group = new ButtonGroup();  
        group.add(Serif);  
        group.add(Monospaced);  
        group.add(SansSerif);  
        group.add(TimesRoman);  

          
     // listener para as fontes
        Serif.addActionListener(new ActionListener() {  


		@Override  
            public void actionPerformed(ActionEvent ae) {  
                tf.setFont(new Font("Serif", tf.getFont().getStyle(), 14));  
            //    this.FontNome = "Serif";
                
            }  
        });    
        Monospaced.addActionListener(new ActionListener() { 
  
       

			@Override  
            public void actionPerformed(ActionEvent ae) {  
                tf.setFont(new Font("Monospaced", tf.getFont().getStyle(), 14));  
          //      this.FontNome = "Monospaced";
            }  
        });  
        SansSerif.addActionListener(new ActionListener() {   
  
            @Override  
            public void actionPerformed(ActionEvent ae) {  
                tf.setFont(new Font("SansSerif", tf.getFont().getStyle(), 14));  
             //   this.FontNome = "SansSerif";
            }  
        });      
        TimesRoman.addActionListener(new ActionListener() { 
  
            @Override  
            public void actionPerformed(ActionEvent ae) {  
                tf.setFont(new Font("TimesRoman", tf.getFont().getStyle(), 14));  
            //    this.FontNome = "TimesRoman";
            }  
        });           

     
    }  
  
    
 // metodo que muda a fonte  
    public void mudaFonte() { 
        Font font1 = null;  
  
        if (negrito.isSelected() && italico.isSelected()) {  
            font1 = new Font(tf.getFont().getFamily(), Font.BOLD + Font.ITALIC, 14); 
            this.FontTip = "Negrito e Itálico";
        } else if (negrito.isSelected()) {  
            font1 = new Font(tf.getFont().getFamily(), Font.BOLD, 14);  
            this.FontTip = "Negrito";
        } else if (italico.isSelected()) {  
            font1 = new Font(tf.getFont().getFamily(), Font.ITALIC, 14);  
            this.FontTip = "Itálico";
        } else {  
            font1 = new Font(tf.getFont().getFamily(), Font.PLAIN, 14);      
            this.FontTip = " ; ";  
        }  
  
        tf.setFont(font1);  
  
    }  
    
    
    
 }

Alguém se propõem a ajudar? Valeu!!

Criado 14 de fevereiro de 2012
Ultima resposta 27 de fev. de 2012
Respostas 6
Participantes 2