我想将滚动条添加到我的文本区域中,我知道添加滚动条的简单代码,但是当我将滚动条的代码放入整个文本区域时,就消失了!
问题是什么?
这是我的代码:
private JFrame frame;
private JTextArea textarea;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SmsForm window = new SmsForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SmsForm() {
initialize();
}
private void initialize() {
frame = new JFrame("???");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel groupBoxEncryption = new JPanel();
final JTextArea textarea=new JTextArea();
textarea.setBounds(50, 100, 300, 100);
frame.getContentPane().add(textarea);
textarea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JScrollPane scrollPanePlain = new JScrollPane(textarea);
groupBoxEncryption.add(scrollPanePlain);
scrollPanePlain.setBounds(100, 30, 250, 100);
scrollPanePlain.setVisible(true);
最佳答案
有很多问题
您需要将JPanel
groupBoxEncryption
添加到应用程序JFrame
不要将textarea
添加到框架中-组件只能有一个父组件
如前所述,您使用的是null
布局,该布局不会调整组件的大小-不用考虑布局管理器。
由于默认情况下JPanel
使用FlowLayout
,因此您需要为面板getPreferredSize
覆盖groupBoxEncryption
。最好还是使用诸如GridLayout
之类的布局管理器来自动调整组件的大小
例
JPanel groupBoxEncryption = new JPanel(new GridLayout());