2

我在编辑器上工作。我正在使用Java swing。我嵌入了一个JTextAreawith JScrollPane。我想将jtextarea特定尺寸的JScrollPane. 为此,我使用了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();
     }
}
4

1 回答 1

8

您只需将JTextArea加到 中JScrollPane,然后将其加到CENTER中。JPanelBorderLayout

不要使用绝对定位。添加适当的LayoutManager,让 LayoutManager 完成其余的工作,以在屏幕上定位和调整组件的大小。

为了使用该setBounds(...)方法,您必须为组件使用不值得使用的布局,提供透视图,如AbsolutePositioningnull的第一段所述。尽管在您提供的代码示例中,您同时使用 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();
            }
        });
    }
}
于 2013-01-12T08:02:30.200 回答