Bha*_*ani 0 java swing awt jtextarea
我试图在JTextArea中添加滚动条但滚动条没有显示在textarea中..
这是我的代码,
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame("MySql Console");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
panel.setLayout(null);
JTextArea txtQuery = new JTextArea ();
txtQuery.setBounds(10, 10, 365, 45);
JScrollPane scroll = new JScrollPane (txtQuery,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//scroll.setPreferredSize(new Dimension(100, 50));
panel.add(scroll);
panel.add(txtQuery);
frame.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
从互联网尝试了一些替代品,但仍然没有工作
panel.setLayout(null);
JTextArea txtQuery = new JTextArea ();
txtQuery.setBounds(10, 10, 365, 45);
JScrollPane scroll = new JScrollPane (txtQuery,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//scroll.setPreferredSize(new Dimension(100, 50));
panel.add(scroll);
panel.add(txtQuery);
Run Code Online (Sandbox Code Playgroud)
不要使用null布局.布局管理器将确定组件的首选大小,然后滚动窗格可以确定何时需要滚动条.在向文本区域添加文本时,滚动条将自动出现.
不要将文本区域添加到面板.组件只能有一个父组件.您已将文本区域添加到滚动窗格.
通过指定文本区域的行/列,为文本区域指定首选大小.
所以你修改过的代码应该是这样的:
//panel.setLayout(null);
JTextArea txtQuery = new JTextArea (5, 20);
//txtQuery.setBounds(10, 10, 365, 45);
JScrollPane scroll = new JScrollPane (txtQuery);
//scroll.setPreferredSize(new Dimension(100, 50));
panel.add(scroll);
//panel.add(txtQuery);
Run Code Online (Sandbox Code Playgroud)