繁体   English   中英

未设置jscrollpane中jtextarea的位置和大小

[英]location and size of jtextarea in jscrollpane is not set

我正在编辑。 我正在使用Java swing。 我在JScrollPane嵌入了一个JTextArea 我想将特定大小的jtextareaJScrollPane的中间。 为此,我使用了setLocation函数。 但这行不通吗?

public class ScrollPaneTest extends JFrame {
private Container myCP;
private JTextArea resultsTA;
private JScrollPane scrollPane;
private  JPanel jpanel;

public ScrollPaneTest() {
resultsTA = new JTextArea(50,50);
resultsTA.setLocation(100,100);
jpanel=new JPanel(new BorderLayout());
jpanel.add(resultsTA,BorderLayout.CENTER);

scrollPane = new JScrollPane(jpanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(800, 800));
scrollPane.setBounds(0, 0, 800, 800);

setSize(800, 800);
setLocation(0, 0);
myCP = this.getContentPane();
myCP.setLayout(new BorderLayout());
myCP.add(scrollPane);
setVisible(true);
addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
        System.exit(0);
    }
 });
}
public static void main(String[] args) {
     new ScrollPaneTest();
     }
}

您只需将JTextArea添加到JScrollPane并将其添加到具有BorderLayoutJPanelCENTER

不要使用AbsolutePositioning。 添加适当的LayoutManager ,让LayoutManager进行其余操作,以在屏幕上定位和调整组件大小。

为了使用setBounds(...)方法,您必须为组件使用null布局,这是不值得使用的,提供透视,如AbsolutePositioning第一段中所述。 尽管在您提供的代码示例中,您将同时进行这两个事情,即使用Layout和AbsolutePositioning,但这在所有方面都是错误的。 我的建议停止这样做 :-)

在提供的示例中,您提供的ROWSCOLUMNS足以根据布局关注来调整JTextArea的大小。

代码示例:

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

public class Example
{
    private JTextArea tarea;

    private void displayGUI()
    {
        JFrame frame = new JFrame("JScrollPane Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout(5, 5));

        JScrollPane textScroller = new JScrollPane();
        tarea = new JTextArea(30, 30);
        textScroller.setViewportView(tarea);

        contentPane.add(textScroller);
        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new Example().displayGUI();
            }
        });
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM