Please, anyone, tell me how to add the scrollbar to a JTextArea
. I tried out many things. but still not able to get it. I copied some codes related to the text area.
public class main extends JPanel {
private JTextArea jcomp1;
public main() {
jcomp1 = new JTextArea(5, 5);
setPreferredSize(new Dimension(944, 574));
// setPreferredSize (new Dimension (1024, 1080));
setLayout(null);
//add components
add(jcomp1);
jcomp1.setBounds(110, 165, 330, 300);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Paraphrasing Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new main());
frame.pack();
frame.setVisible(true);
}
}
CodePudding user response:
Oracle has a helpful tutorial,
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class JTextAreaExample extends JPanel {
private static final long serialVersionUID = 1L;
private JTextArea jcomp1;
public JTextAreaExample() {
this.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
this.setLayout(new BorderLayout());
jcomp1 = new JTextArea(5, 30);
jcomp1.setMargin(new Insets(5, 5, 5, 5));
JScrollPane scrollPane = new JScrollPane(jcomp1);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Paraphrasing Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JTextAreaExample(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
}
CodePudding user response:
Add the text area to (the viewport of) a JScrollPane
. The easiest way is to add it in the constructor. Then add the scroll pane to a panel with a layout (in a GUI that uses layouts).