[英]Trouble with JScrollPane in JTextArea in JPanel in JFrame
我在JPanel
中有一个JTextArea
,我想使用JScrollPane
。 我正在使用GridBagLayout
。 当我运行它时,该框架似乎为JScrollPane
腾出了空间,但未显示出来,将不胜感激。 我一直在尝试研究docs.oracle页面,并在此处将JScrollPane添加到JPanel,但是由于某种原因,它拒绝显示。
final JTextArea test= new JTextArea(5,30);
test.setLineWrap(true);
test.setWrapStyleWord(true);
test.setEditable(false);
JScrollPane spane = new JScrollPane(test);
spane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
JFrame frame = new JFrame ();
frame.setSize(800, 250);
frame.setTitle("test1");
frame.setLocation(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.getContentPane().add(spane);
GridBagConstraints k = new GridBagConstraints();
k.gridx = 4;
k.gridy = 5;
a.setConstraints(spane,k);
container.add(spane);
您的可变容器是JPanel? 我认为您忘记了调用add()方法。 但是下面是我的建议代码。
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
public class MyScrollPane extends JPanel
{
public MyScrollPane()
{
GridBagConstraints k = new GridBagConstraints();
k.gridx = 4;
k.gridy = 5;
final JTextArea test= new JTextArea(5, 30);
test.setLineWrap(true);
test.setWrapStyleWord(true);
test.setEditable(false);
JScrollPane spane = new JScrollPane(test);
spane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
GridBagLayout gbl = new GridBagLayout();
gbl.setConstraints(spane,k);
JPanel panel = new JPanel(gbl);
panel.add(spane);
add(panel);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame();
frame.setSize(800, 250);
frame.setTitle("test1");
frame.setLocation(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.getContentPane().add(new MyScrollPane());
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run()
{
createAndShowGUI();
}
});
}
}
我已经删除了代码的最后五行,并做了一些更改。 我很好
public class MainFrame extends JFrame {
private JTextArea test = new JTextArea(5, 30);
private JScrollPane spane;
public MainFrame() {
this.setSize(800, 250);
this.setTitle("test1");
this.setLocation(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
test.setLineWrap(true);
test.setWrapStyleWord(true);
test.setEditable(false);
spane = new JScrollPane(test);
spane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
this.getContentPane().add(spane);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.