4

JScrollPane 内に JTextArea を表示しようとしていますが、(簡略化された) プログラムを実行すると空のフレームが表示されます。

import java.awt.Container;
import java.awt.Dimension;    
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

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

    public ScrollPaneTest() {
        setSize(500, 500);
        setLocation(100, 100);
        myCP = this.getContentPane();
        myCP.setLayout(null);

        resultsTA = new JTextArea("Blah blah");
        scrollPane = new JScrollPane(resultsTA,
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollPane.setPreferredSize(new Dimension(200, 100));
        scrollPane.setLocation(100, 300);
        myCP.add(scrollPane);

        setVisible(true);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    public static void main(String[] args) {
        new ScrollPaneTest();
    }
}

null LayoutManager を使用して、教えている教科書との一貫性を保ちます。

4

2 に答える 2

7

これは機能します:

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

    public ScrollPaneTest() {
        setSize(500, 500);
        setLocation(100, 100);
        myCP = this.getContentPane();
        myCP.setLayout(null);

        resultsTA = new JTextArea("Blah blah");
        resultsTA.setBounds(10, 10, 150, 30);

        scrollPane = new JScrollPane(resultsTA,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollPane.setPreferredSize(new Dimension(200, 100));
        scrollPane.setBounds(0, 0, 500, 500);

        myCP.add(scrollPane);
        setVisible(true);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    public static void main(String[] args) {
        new ScrollPaneTest();
    }
}

nullレイアウトを使用している場合は、境界を指定する必要があります。


編集

setBounds()メソッドはメソッドのタスクをカバーしますsetLocation()

例えば、setBounds(x,y,w,h);

最初の2は、コンテナに対するそのコンポーネントのx/y位置を設定します。2番目の2(w / h)は、そのコンポーネントのサイズを設定します。

言い換えると:-

  1. setBounds(int x、int y、int witdh、int height) –コンポーネントのサイズと位置を設定します
  2. setLocation(int x、int y) –コンポーネントの場所を設定します
于 2011-04-07T05:28:11.350 に答える