In this example you will be shown how to set or change the tab size for the JTextArea
component. You can use the setTabSize(int size)
to define the tab size. For this demo we create a combo box that have some integer values which will be used to define the tab size. When you change the selected item in the combo box the JTextArea
tab size will be change immediately.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
public class TextAreaSetTabSize extends JPanel {
public TextAreaSetTabSize() {
initializeUI();
}
public static void showFrame() {
JPanel panel = new TextAreaSetTabSize();
panel.setOpaque(true);
JFrame frame = new JFrame("JTextArea Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TextAreaSetTabSize::showFrame);
}
private void initializeUI() {
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(500, 200));
JLabel label = new JLabel("Tab size: ");
Object[] items = {2, 4, 8, 10, 20};
final JComboBox<Object> comboBox = new JComboBox<>(items);
JPanel tabPanel = new JPanel(new FlowLayout());
tabPanel.add(label);
tabPanel.add(comboBox);
this.add(tabPanel, BorderLayout.NORTH);
final JTextArea textArea = new JTextArea();
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
// Sets the number of characters to expand tabs to.
textArea.setTabSize((Integer) comboBox.getSelectedItem());
comboBox.addItemListener(e -> textArea.setTabSize(
(Integer) comboBox.getSelectedItem()));
JScrollPane pane = new JScrollPane(textArea);
pane.setPreferredSize(new Dimension(500, 200));
pane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
this.add(pane, BorderLayout.CENTER);
}
}
The output of the code snippet above is:
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024