我在JTextArea
中有一个JPanel
,我想使用JScrollPane
。我正在使用GridBagLayout
。当我运行它似乎框架为JScrollPane
腾出空间但它没有显示,任何帮助将不胜感激。我一直在尝试研究docs.oracle页面和Add JScrollPane to a 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);
答案 0 :(得分:1)
你的变量容器是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();
}
});
}
}
答案 1 :(得分:0)
我删除了代码的最后五行并稍微更改了一下。我工作得很好。
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);
}