[JavaSwing] JTextArea in Java
JTextArea is a component for displaying multiple lines of text at the same time the user can edit the text.
Create a simple JTextArea
Now we will practice even an example that allows you to type and edit text. In your code, and images were explained quite clearly the commands performed with JTextArea.
package nguyenvanquan7826.JTextArea; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; /** * ----------------- @author nguyenvanquan7826 ----------------- * ---------------nguyenvanquan7826.wordpress.com -------------- */ public class DemoJTextArea extends JFrame { private JTextArea ta; public DemoJTextArea() { add(createMainPanel()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("Demo JTextArea"); pack(); setLocationRelativeTo(null); setVisible(true); } private JPanel createMainPanel() { JPanel panel = new JPanel(new BorderLayout()); // JScrollPane create a scroll when row of text larger than row of // JTextArea JScrollPane scroll = new JScrollPane(ta = createTextArea(10, 40)); panel.add(scroll, BorderLayout.CENTER); JButton btnClear = new JButton("Clear"); btnClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { clear(); } }); JPanel panelBottom = new JPanel(); panelBottom.add(btnClear); panel.add(panelBottom, BorderLayout.PAGE_END); return panel; } /** * create a JTextArea with rows and columns, two method setWrapStyleWord and * setLineWrap make text can down line when text too long */ private JTextArea createTextArea(int row, int col) { JTextArea ta = new JTextArea(row, col); ta.setWrapStyleWord(true); ta.setLineWrap(true); return ta; } /** * clear text of JTextArea */ private void clear() { ta.setText(""); } public static void main(String[] args) { new DemoJTextArea(); } }
Set the font and font color for JTextArea
You can set the font and font color like the following function:
/** * change font and color text of JTextArea */ private void changeColor() { Font font = new Font("Verdana", Font.BOLD, 20); ta.setFont(font); ta.setForeground(Color.BLUE); }
Read more : TUT Java swing, class JTextArea, use JTextArea
Recent Comments