我是 Jframes 新手,我想设计一个带有文本框和两个按钮的窗口。除了滚动条部分之外,我能够使其正常工作。 我编写了下面的代码来启用文本区域的滚动条。
private JTextArea outputPane;
outputPane = new JTextArea();
outputPane.setColumns(20);
outputPane.setRows(5);
outputPane.setFont(new Font("Monospaced", Font.PLAIN, 18));
outputPane.setBounds(12, 13, 408, 189);
contentPane.add(outputPane);
JScrollPane scrollPane = new JScrollPane(outputPane);
jScrollPane1.setBounds(399, 13, 21, 189);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
现在的问题是我在窗口上看到禁用的滚动条,但我看不到我的文本区域。
请帮我解决这个问题。我什至尝试使用 WindowsBuilder 但我无法弄清楚。
由于我仍处于学习阶段,因此将不胜感激对更正代码的详细解释。
提前致谢。
最佳答案
首先查看 Laying Out Components Within a Container和 How to Use Scroll Panes和 How to Use Text Areas可能不会受伤
Now the problem is I am getting a disabled scrollbar on the window but I cannot see my Text Area.
可能的问题是,您看到的JTextArea
,“禁用”滚动条只是因为您使用scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS
,这即使没有任何内容可滚动,也会始终显示滚动条,因此它可能看起来是空的。
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
// Swing is not thread safe, so need to get started in the
// Event Dispatching Thread before we do anything
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
// I simply hate the default look and feel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
// Always better to create an instance of a window
// to display you content then to extend from one
// directly...
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
// Our main UI, I do it this way so I'm not locked into a single
// use case and can decide how I want to use the view
public class TestPane extends JPanel {
public TestPane() {
// The default layout is a FlowLayout, so we want to change
// this will allow the main component to occupy the whole
// available space
setLayout(new BorderLayout());
// Providing "sizing" hints, 10 rows, 20 columns, this is
// platform independent, so it will size accordingly
JTextArea ta = new JTextArea(10, 20);
JScrollPane sp = new JScrollPane(ta);
add(sp);
}
}
}
关于Java - 放入 JscrollBar 后 JTextArea 未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34219421/