我们如何在java中的JTextArea上添加JScrollPane? [英] How can we add JScrollPane on JTextArea in java?

查看:400
本文介绍了我们如何在java中的JTextArea上添加JScrollPane?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我以下程序有什么问题吗?我想在 JtextArea 上安装 JScrollPane 但是当我添加它时, JTextArea 不可见。

Can anybody tell me what is the problem in following program? I want to fit JScrollPane on JtextArea but when I add it then JTextArea is not visible.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Area extends JFrame
{
    private JTextArea ta;
    private JTextField tf;
    JScrollPane jp;

    public Area()
    {
       super("Text Area");
       tf=new JTextField();
       tf.setBounds(100,350,300,30);
       add(tf);
       ta=new JTextArea();
       ta.setBounds(100,100,300,200);
       jp= new JScrollPane(ta);
       add(jp);
       setLayout(null);
       setSize(500,500);
       setVisible(true);
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }

   public static void main(String...s)
   {
      new Area();
   }
}


推荐答案

我看几个问题:


  • 不要使用 null 布局;请使用真正的布局

  • Don't use a null layout; do use a real layout.

JFrame 的默认布局是 BorderLayout ;默认位置是 CENTER ;只有一个组件可以一次占据一个位置;以下示例使用 NORTH & CENTER

The default layout of JFrame is BorderLayout; the default position is CENTER; only one component can occupy a position at a time; the example below uses NORTH & CENTER.

使用适当的构造函数参数来初始调整文本组件的大小。

Use the appropriate constructor parameters to size the text components initially.

滚动条小于封闭组件时,滚动条会自动出现;调整框架大小以查看效果。

The scrollbar will appear automatically whenever the scrollpane is smaller than the enclosed component; resize the frame to see the effect.

此处所示,框架的大小为效果较小。

As shown here, the frame's size is made smaller for effect.

另请参阅 初始主题

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/** @see https://stackoverflow.com/a/19215436/230513 */
public class Area extends JFrame {

    public Area() {
        super("Text Area");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTextField tf = new JTextField(12);
        add(tf, BorderLayout.NORTH);
        JTextArea ta = new JTextArea(24, 12);
        JScrollPane jp = new JScrollPane(ta);
        add(jp, BorderLayout.CENTER);
        pack();
        // arbitrary size to make vertical scrollbar appear
        setSize(240, 240);
        setLocationByPlatform(true);
        setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Area();
            }
        });
    }
}

这篇关于我们如何在java中的JTextArea上添加JScrollPane?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆