How to break line automatically into a texo component?

Asked

Viewed 2,017 times

0

I would like when it reaches the maximum number of letters/words on that line, to break automatically.

When I put a pizza works smoothly:

Quando eu coloco uma pizza funciona tranquilamente.

But when I put more than one pizza the text gets bigger than jLabel so you can’t see all the pizzas or the total:

Mas Quando eu coloco mais de uma pizza o texto fica maior que a jLabel aí não dá pra ver todas as pizzas nem o total.

My code:

 private void btnAdicionarActionPerformed(java.awt.event.ActionEvent evt) {                                             
    //Verificar se o local de entrega foi duplamente selecionado ou se nenhum

    if(((checkLocal.isSelected()) && (checkCasa.isSelected())) ||((checkLocal.isSelected()==FALSE) && (checkCasa.isSelected()==FALSE)) ){
        JOptionPane.showMessageDialog(null,"Foram escolhidos dois locais de entrega ou nenhum foi selecionado.\nPor favor verifique o local de entrega");
    }else if(checkLocal.isSelected()){

    String Entregar =checkLocal.getText();
    }else if(checkCasa.isSelected()){

    String Entregar =checkCasa.getText();
    }

    //Os dados foram verificados


    String Nome      = txtNomeVenda.getText();
    String Endereco  = txtEndereco.getText();
    String Sabor1    = (String) SaborPizza1.getSelectedItem();
    String Sabor2    = (String) SaborPizza2.getSelectedItem();   
    String Borda     = (String) BordaEscolha.getSelectedItem();
    String SaborTodo = "";


    if(Borda.equals("Nenhuma")){
    Borda = "";
    }

    if(Sabor2.equals("Nenhum")){
    SaborTodo = "1 "+Sabor1+" Borda:"+Borda;
    }else{
    SaborTodo = " 1/2"+Sabor1+" 1/2"+Sabor2+" \nBorda:"+Borda;
    }

    PizzaNota.setText(PizzaNota.getText()+"\n"+SaborTodo+"");

    txtNomeNota.setText(txtNomeVenda.getText());
}                         
  • Another thing, use Jtextfield if you need to break line, not Jlabel. This component is made for short text.

  • There is a jLabel there where it says "Pizzas:" and the goal was to show all the pizzas that were ordered, but when I add more than one pizza jLabel increases and you can not see anything

  • This section is not executable.

  • As I said, Jlabel is not to use for long texts and line breaks, so there is Jtextarea, which allows for line breaks and long texts.

  • How so it is not executable??

  • Ah understood I’ll try, thanks again kkkk

  • You need to provide an example of your code that people can copy and run to see the problem.

  • All right, it’s just that I’m kind of new at Stack, I’m learning to use even kkkk

Show 3 more comments

1 answer

4


Jlabels also accept html tags, despite being a nut solution that if misused, will make your code difficult to read and maintenance, for sporadic cases you can use the form below:

PizzaNota.setText("<html>"+PizzaNota.getText()+"<br>"+SaborTodo+"</html>");

This will break the text between the two strings concatenated in the JLabel.


Using JTextArea is much easier, since it already has methods you set for it to break the line automatically, through the JTextArea#setLineWrap, and along with this method, you can also configure the component to break the line and text correctly, avoiding breaking a word that does not fit at the end of the line, with the method JTextArea#setWrapStyleWord. See the example below:

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class JTextAreaQuebraLinhaTest extends JFrame {

    private JPanel contentPane;
    private JScrollPane scrollPane;
    private JTextArea textArea;

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            new JTextAreaQuebraLinhaTest().setVisible(true);
        });
    }

    public JTextAreaQuebraLinhaTest() {
        initComponents();
    }

    private void initComponents() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(450, 300));

        this.contentPane = new JPanel();
        this.contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
        setContentPane(this.contentPane);

        this.textArea = new JTextArea(5, 15);
        // quebra a linha ao chegar no limite
        // da textarea
        this.textArea.setLineWrap(true);
        // define a quebra de linha sem quebrar
        // a palavra no final da linha, caso
        // nao caiba inteira
        this.textArea.setWrapStyleWord(true);

        this.scrollPane = new JScrollPane(this.textArea);
        this.contentPane.add(this.scrollPane);

        pack();
        setLocationRelativeTo(null);
    }
}

Testing the line break:

inserir a descrição da imagem aqui

  • Downvoter, kindly inform us what the problem is with the answer. Otherwise it is no use your vote, if I do not correct the problem, if this vote was due to it.

Browser other questions tagged

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