java – 为什么在使用null LayoutManager时,我的JScrollPane与JTextArea不可见?
作者:互联网
我正在尝试在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与我教的教科书一致.
解决方法:
这将有效:
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);
第一个将设置该组件相对于其容器的x / y位置.
第二个2(w / h)将设置该组件的大小.
换一种说法:-
> setBounds(int x,int y,int witdh,int height) – 设置组件的大小和位置
> setLocation(int x,int y) – 设置组件的位置
标签:java,swing,jscrollpane,jtextarea,null-layout-manager 来源: https://codeday.me/bug/20190610/1211196.html