3

I'm trying to make a calculator program in java, but I'm not sure how to center the text in my JTextArea. I've tried searching google and YouTube, but I don't find anything. Here is my source code:

import javax.swing.*;
import java.awt.*;

public class Sect1 extends JTextArea{
    public static final Dimension ss = Toolkit.getDefaultToolkit().getScreenSize();
    
    public Sect1(){
        this.setBounds(ss.width / 4, ss.height / 5, 100, 100);
        this.setLineWrap(true);
        this.setWrapStyleWord(true);
    }
}
  • 1
    Why are you using a JTextArea? Typically a calculator displays the results on a single line which would imply you use a JTextField. A JTextField allows you to center the text horizontally. You can also use a JTextPane which will allow you to center the text horizontally. – camickr Mar 02 '21 at 15:24
  • Well it's a table calculator, so the user would type 10 : 20 then 1 : x then the computer would say x = 2 –  Mar 02 '21 at 15:58
  • 1
    I would still suggest the input is a JTextField and then you can output the results to a JTextArea. See: [How to Use Text Fields](https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html) for a basic example of using two components. – camickr Mar 02 '21 at 16:12
  • 1
    Skip centering the text in a JTextArea. Finish your project and if you have time, come back to centering the text. Besides, table calculators left justify the output. – Gilbert Le Blanc Mar 02 '21 at 16:24
  • Alright I'll just finish it up. –  Mar 02 '21 at 16:36

1 Answers1

2

You may wish to consider entering text in a single line with JTextField and center its contents using:

setHorizontalAlignment(JTextField.CENTER);

But if you need something like JTextArea for introducing multiple lines of text, use JTextPane or its subclass, JEditorPane which give you more customisation and control over the written text.

For centering text inside a JTextPane:

JTextPane textPane = new JTextPane();

StyledDocument documentStyle = textPane.getStyledDocument();
SimpleAttributeSet centerAttribute = new SimpleAttributeSet();
StyleConstants.setAlignment(centerAttribute, StyleConstants.ALIGN_CENTER);
documentStyle.setParagraphAttributes(0, documentStyle.getLength(), centerAttribute, false);
hexstorm
  • 318
  • 4
  • 14