无法将JScrollBar/JScrollPane添加到此JTextPane

use*_*719 0 java swing jtextpane jscrollpane

好的,所以这里是我的代码片段,其中包含问题:

private JTextField userText;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
private JTextPane images;
private JScrollPane jsp = new JScrollPane(images); 

public Server(){
   super(name+" - IM Server");
  images = new JTextPane();
  images.setContentType( "text/html" );
  HTMLDocument doc = (HTMLDocument)images.getDocument();
  userText = new JTextField();
  userText.setEditable(false);
  userText.addActionListener(
     new ActionListener(){
        public void actionPerformed(ActionEvent event){
           sendMessage(event.getActionCommand());
           userText.setText("");
        }
     }
  );
  add(userText, BorderLayout.NORTH);
  add(jsp);
  add(images, BorderLayout.CENTER);
  images.setEditable(false);
  try {
    doc.insertString(0, "This is where images and text will show up.\nTo send an image, do\n*image*LOCATION OF IMAGE\n with NO SPACES or EXTRA TEXT.", null );
} catch (BadLocationException e) {
    e.printStackTrace();
}
  setSize(700,400);
  setVisible(true);
  ImageIcon logo = new javax.swing.ImageIcon(getClass().getResource("CHAT.png"));
  setIconImage(logo.getImage());
}
Run Code Online (Sandbox Code Playgroud)

当我使用它时,我的JTextPane上没有滚动条?!我试过移动add(jsp); 上面和下面的位置,并在下面添加(图片,BorderLayout.NORTH); 把它弄出来了?!所以我想知道的是如何将这个JScrollPane添加到我的JTextPane中以给它一个滚动条.提前致谢!

Mad*_*mer 5

基本上,您实际上从未向JScrollPane... 添加有效组件

private JTextPane images;
private JScrollPane jsp = new JScrollPane(images); 
Run Code Online (Sandbox Code Playgroud)

执行此images操作时null,基本上就是在调用new JScrollPane(null);

然后,你基本上添加imagesjsp框架的顶部(替换)...

add(jsp);
add(images, BorderLayout.CENTER);
Run Code Online (Sandbox Code Playgroud)

默认位置是BorderLayout.CENTER,边框布局只能支持其中任何一个5个可用位置中的单个组件...

相反,尝试像......

public Server(){
    super(name+" - IM Server");
    images = new JTextPane();
    images.setContentType( "text/html" );
    HTMLDocument doc = (HTMLDocument)images.getDocument();
    userText = new JTextField();
    userText.setEditable(false);
    userText.addActionListener(
     new ActionListener(){
        public void actionPerformed(ActionEvent event){
           sendMessage(event.getActionCommand());
           userText.setText("");
        }
     }
    );
    add(userText, BorderLayout.NORTH);
    jsp.setViewportView(images);
    add(jsp);
    //add(images, BorderLayout.CENTER);
    images.setEditable(false);
    try {
        doc.insertString(0, "This is where images and text will show up.\nTo send an image, do\n*image*LOCATION OF IMAGE\n with NO SPACES or EXTRA TEXT.", null );
    } catch (BadLocationException e) {
        e.printStackTrace();
    }
    setSize(700,400);
    setVisible(true);
    ImageIcon logo = new javax.swing.ImageIcon(getClass().getResource("CHAT.png"));
    setIconImage(logo.getImage());
}
Run Code Online (Sandbox Code Playgroud)