繁体   English   中英

GridBagLayout后,JScrollPane滚动条不起作用

[英]JScrollPane scrollbar doesnt work after GridBagLayout

我正在为学校制作像Cleverbot这样的自动聊天客户端。 我有2个问题... 1)滚动条由于某种原因似乎不起作用。 这是屏幕截图: 在此处输入图片说明

import javax.swing.*;
import java.awt.*;

import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

import java.lang.Math;

public class ChatBot extends JFrame implements KeyListener{
    //Main method
    public static void main(String[] args){
        new ChatBot();
    }
    //Swing settings
    JPanel window=new JPanel(){
        protected void paintComponent(Graphics g){
            super.paintComponent(g);
            Image background = new ImageIcon("textEffect.png").getImage();
            int x = (window.getWidth() - background.getWidth(null)) / 2;
            int y = (window.getHeight() - background.getHeight(null)) / 2;
            g.drawImage(background,x,y,null,this);
        }
    };
    JLabel label=new JLabel("Say: ");
    JTextArea dialog=new JTextArea();
    JTextField input=new JTextField(46);
    JScrollPane scroll=new JScrollPane(
        dialog,
        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
    );
    //Makes window and starts bot
    public ChatBot(){
        super("Pollockoraptor");
        setSize(600,400);
        setResizable(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        dialog.setEditable(false);
        dialog.setLineWrap(true);
        dialog.setOpaque(false);
        scroll.getViewport().setOpaque(false);
        input.addKeyListener(this);
        window.add(scroll);
        window.add(label);
        window.add(input);
        //background color; new Color(97, 118, 131) is a nice color
        window.setBackground(new Color(255, 255, 255));
        add(window);
        setVisible(true);
        //Gui Layout
        window.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;
        //Dialog
        c.weightx = 1.0;
        c.weighty = 1.0;
        c.anchor = GridBagConstraints.PAGE_START;
        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(10, 10, 0, 10);
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 3;
        c.gridheight = 2;
        window.add(dialog, c);
        //Input box
        c.weightx = 0;
        c.weighty = 0;
        c.anchor = GridBagConstraints.PAGE_END;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(0, 0, 10, 10);
        c.gridx = 1;
        c.gridy = 2;
        c.gridwidth = GridBagConstraints.REMAINDER;
        window.add(input, c);
        //Label
        c.weightx = 0;
        c.weighty = 0;
        c.anchor = GridBagConstraints.PAGE_END;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(0, 10, 10, 0);
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 1;
        window.add(label, c);
        input.requestFocus();
    }
    //knowledgeBase
    String[][] knowledgeBase={
        {"hi","hello","howdy","hey"},
        {"hi","hello","hey"},
        {"how are you", "how r u", "how r you", "how are u"},
        {"good","doing well"},
        {"shut up","noob","stop talking"}
    };
    //What to do when enter is pressed
    public void keyPressed(KeyEvent e){
        if(e.getKeyCode()==KeyEvent.VK_ENTER){
            input.setEditable(false);
            //get the user input
            String quote=input.getText();
            input.setText("");
            if(!quote.equals("")){
                addText("You:\t"+quote);
                quote.trim();
                while(quote.charAt(quote.length()-1)=='!' || quote.charAt(quote.length()-1)=='.' || quote.charAt(quote.length()-1)=='?'){
                    quote=quote.substring(0,quote.length()-1);
                }
                quote.trim();
                byte response=0;
                int j=0;
                //check the knowledgeBase for a match or change topic
                while(response==0){
                    //if a match is found, reply with the answer
                    if(inArray(quote.toLowerCase(),knowledgeBase[j*2])){
                        response=2;
                        int r=(int)Math.floor(Math.random()*knowledgeBase[(j*2)+1].length);
                        addText("\nPollockoraptor:\t"+knowledgeBase[(j*2)+1][r]);
                    }
                    j++;
                    //if a match is not found, go to change topic
                    if(j*2==knowledgeBase.length-1 && response==0){
                        response=1;
                    }
                }
                //change topic if bot is lost
                if(response==1){
                    int r=(int)Math.floor(Math.random()*knowledgeBase[knowledgeBase.length-1].length);
                    addText("\nPollockoraptor:\t"+knowledgeBase[knowledgeBase.length-1][r]);
                }
                addText("\n");
            }
        }
    }
    //other events
    public void keyTyped(KeyEvent e){}
    public void keyReleased(KeyEvent e){
        if(e.getKeyCode()==KeyEvent.VK_ENTER){
            input.setEditable(true);
        }
    }
    //format the input
    public void addText(String str){
        dialog.setText(dialog.getText()+str);
    }
    //check the knowledgeBase for a match
    public boolean inArray(String in,String[] str){
        boolean match=false;
        for(int i=0;i<str.length;i++){
            if(str[i].equals(in)){
                match=true;
            }
        }
        return match;
    }
}

我可以完成所有其他工作,但是我还需要一种方法来建立可以轻松编辑的响应数据库。 我该怎么做? 我必须使用MySQL或类似的东西吗? 有什么更简单的方法可以做到,即我可以通过阅读文本文件来制作类似于我的矩阵?

***************编辑****************

import javax.swing.*;
import java.awt.*;

import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

import java.lang.Math;

public class ChatBot extends JFrame implements KeyListener{
    //Main method
    public static void main(String[] args){
        new ChatBot();
    }
    //Swing settings
    JPanel window=new JPanel(){
        protected void paintComponent(Graphics g){
            super.paintComponent(g);
            Image background = new ImageIcon("textEffect.png").getImage();
            int x = (window.getWidth() - background.getWidth(null)) / 2;
            int y = (window.getHeight() - background.getHeight(null)) / 2;
            g.drawImage(background,x,y,null,this);
        }
    };
    JLabel label=new JLabel("Say: ");
    JTextArea dialog=new JTextArea(5,30);
    JTextField input=new JTextField(46);
    JScrollPane scroll=new JScrollPane(
        dialog,
        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
    );
    //Makes window and starts bot
    public ChatBot(){
        super("Pollockoraptor");
        setSize(600,400);
        setResizable(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        dialog.setEditable(false);
        dialog.setLineWrap(true);
        dialog.setOpaque(false);
        scroll.getViewport().setOpaque(false);
        input.addKeyListener(this);
        window.add(scroll);
        //background color; new Color(97, 118, 131) is a nice color
        window.setBackground(new Color(255, 255, 255));
        add(window);
        setVisible(true);
        //Gui Layout
        window.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;
        //Dialog
        c.weightx = 1.0;
        c.weighty = 1.0;
        c.anchor = GridBagConstraints.PAGE_START;
        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(10, 10, 0, 10);
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 3;
        c.gridheight = 2;
        window.add(scroll, c);
        //Input box
        c.weightx = 0;
        c.weighty = 0;
        c.anchor = GridBagConstraints.PAGE_END;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(0, 0, 10, 10);
        c.gridx = 1;
        c.gridy = 2;
        c.gridwidth = GridBagConstraints.REMAINDER;
        window.add(input, c);
        //Label
        c.weightx = 0;
        c.weighty = 0;
        c.anchor = GridBagConstraints.PAGE_END;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(0, 10, 10, 0);
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 1;
        window.add(label, c);
        input.requestFocus();
    }
    //knowledgeBase
    String[][] knowledgeBase={
        {"hi","hello","howdy","hey"},
        {"hi","hello","hey"},
        {"how are you", "how r u", "how r you", "how are u"},
        {"good","doing well"},
        {"shut up","noob","stop talking"}
    };
    //What to do when enter is pressed
    public void keyPressed(KeyEvent e){
        if(e.getKeyCode()==KeyEvent.VK_ENTER){
            input.setEditable(false);
            //get the user input
            String quote=input.getText();
            input.setText("");
            if(!quote.equals("")){
                addText("You:\t"+quote);
                quote.trim();
                while(quote.charAt(quote.length()-1)=='!' || quote.charAt(quote.length()-1)=='.' || quote.charAt(quote.length()-1)=='?'){
                    quote=quote.substring(0,quote.length()-1);
                }
                quote.trim();
                byte response=0;
                int j=0;
                //check the knowledgeBase for a match or change topic
                while(response==0){
                    //if a match is found, reply with the answer
                    if(inArray(quote.toLowerCase(),knowledgeBase[j*2])){
                        response=2;
                        int r=(int)Math.floor(Math.random()*knowledgeBase[(j*2)+1].length);
                        addText("\nPollockoraptor:\t"+knowledgeBase[(j*2)+1][r]);
                    }
                    j++;
                    //if a match is not found, go to change topic
                    if(j*2==knowledgeBase.length-1 && response==0){
                        response=1;
                    }
                }
                //change topic if bot is lost
                if(response==1){
                    int r=(int)Math.floor(Math.random()*knowledgeBase[knowledgeBase.length-1].length);
                    addText("\nPollockoraptor:\t"+knowledgeBase[knowledgeBase.length-1][r]);
                }
                addText("\n");
            }
        }
    }
    //other events
    public void keyTyped(KeyEvent e){}
    public void keyReleased(KeyEvent e){
        if(e.getKeyCode()==KeyEvent.VK_ENTER){
            input.setEditable(true);
        }
    }
    //format the input
    public void addText(String str){
        dialog.append(str);
    }
    //check the knowledgeBase for a match
    public boolean inArray(String in,String[] str){
        boolean match=false;
        for(int i=0;i<str.length;i++){
            if(str[i].equals(in)){
                match=true;
            }
        }
        return match;
    }
}

*************** EDIT2 ****************

import javax.swing.*;
import java.awt.*;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import java.lang.Math;

public class ChatBot extends JFrame implements ActionListener{
    //Main method
    public static void main(String[] args){
        new ChatBot();
    }
    //Swing settings
    JPanel window=new JPanel(){
        protected void paintComponent(Graphics g){
            super.paintComponent(g);
            Image background = new ImageIcon("textEffect.png").getImage();
            int x = (window.getWidth() - background.getWidth(null)) / 2;
            int y = (window.getHeight() - background.getHeight(null)) / 2;
            g.drawImage(background,x,y,null,this);
        }
    };
    JLabel label=new JLabel("Say: ");
    JTextArea dialog=new JTextArea(5,30);
    JTextField input=new JTextField(46);
    JScrollPane scroll=new JScrollPane(
        dialog,
        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
    );
    //Makes window and starts bot
    public ChatBot(){
        super("Pollockoraptor");
        setSize(600,400);
        setResizable(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        dialog.setEditable(false);
        dialog.setLineWrap(true);
        dialog.setOpaque(false);
        scroll.getViewport().setOpaque(false);
        input.addActionListener(this);
        window.add(scroll);
        //background color; new Color(97, 118, 131) is a nice color
        window.setBackground(new Color(255, 255, 255));
        add(window);
        setVisible(true);
        //Gui Layout
        window.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;
        //Dialog
        c.weightx = 1.0;
        c.weighty = 1.0;
        c.anchor = GridBagConstraints.PAGE_START;
        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(10, 10, 0, 10);
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 3;
        c.gridheight = 2;
        window.add(scroll, c);
        //Input box
        c.weightx = 0;
        c.weighty = 0;
        c.anchor = GridBagConstraints.PAGE_END;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(0, 0, 10, 10);
        c.gridx = 1;
        c.gridy = 2;
        c.gridwidth = GridBagConstraints.REMAINDER;
        window.add(input, c);
        //Label
        c.weightx = 0;
        c.weighty = 0;
        c.anchor = GridBagConstraints.PAGE_END;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(0, 10, 10, 0);
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 1;
        window.add(label, c);
        input.requestFocus();
    }
    //knowledgeBase
    String[][] knowledgeBase={
        {"hi","hello","howdy","hey"},
        {"hi","hello","hey"},
        {"how are you", "how r u", "how r you", "how are u"},
        {"good","doing well"},
        {"shut up","noob","stop talking"}
    };
    //What to do when enter is pressed
    public void actionPerformed(ActionEvent e){
        //get the user input
        String quote=input.getText();
        input.setText("");
        if(!quote.equals("")){
            addText("You:\t"+quote);
            quote.trim();
            while(quote.charAt(quote.length()-1)=='!' || quote.charAt(quote.length()-1)=='.' || quote.charAt(quote.length()-1)=='?'){
                quote=quote.substring(0,quote.length()-1);
            }
            quote.trim();
            byte response=0;
            int j=0;
            //check the knowledgeBase for a match or change topic
            while(response==0){
                //if a match is found, reply with the answer
                if(inArray(quote.toLowerCase(),knowledgeBase[j*2])){
                    response=2;
                    int r=(int)Math.floor(Math.random()*knowledgeBase[(j*2)+1].length);
                    addText("\nPollockoraptor:\t"+knowledgeBase[(j*2)+1][r]);
                }
                j++;
                //if a match is not found, go to change topic
                if(j*2==knowledgeBase.length-1 && response==0){
                    response=1;
                }
            }
            //change topic if bot is lost
            if(response==1){
                int r=(int)Math.floor(Math.random()*knowledgeBase[knowledgeBase.length-1].length);
                addText("\nPollockoraptor:\t"+knowledgeBase[knowledgeBase.length-1][r]);
            }
            addText("\n");
        }
    }
    //format the input
    public void addText(String str){
        dialog.append(str);
    }
    //check the knowledgeBase for a match
    public boolean inArray(String in,String[] str){
        boolean match=false;
        for(int i=0;i<str.length;i++){
            if(str[i].equals(in)){
                match=true;
            }
        }
        return match;
    }
}

)滚动条似乎不起作用

window.add(dialog, c);

您需要将滚动窗格添加到窗口,而不是dialog。 同样,在创建对话框时,您应该使用类似以下的内容:

JTextArea dialog = new JTextArea(5, 30);

因此可以以合理的大小创建文本区域。

如果(e.getKeyCode()== KeyEvent.VK_ENTER){

不要使用KeyListener来监听Enter键。 而是将ActionListener添加到文本字段。 当按下Enter键时,将调用ActionListener。 另外,为什么还要切换文本字段的可编辑状态? 不需要这样做。

dialog.setText(dialog.getText()+ STR);

请勿这样做,以将文本添加到文本区域。 只需使用文本区域的append(...)方法即可。

抱歉,直截了当,但是您的问题只是草率的代码之一。

您将对话框两次添加到窗口容器中,一次添加到JScrollPane中,一次添加到其自身。

public ChatBot() {
  super("Pollockoraptor");
  setSize(600, 400);
  setResizable(true);
  setDefaultCloseOperation(EXIT_ON_CLOSE);
  dialog.setEditable(false);
  dialog.setLineWrap(true);
  dialog.setOpaque(false);
  scroll.getViewport().setOpaque(false);
  input.addKeyListener(this);

  // **** adding a bunch of junk **without** constraings??
  window.add(scroll);  // *** add scrollpane *with* dialog here
  window.add(label);
  window.add(input);

  // .....

  GridBagConstraints c = new GridBagConstraints();
  c.fill = GridBagConstraints.HORIZONTAL;
  // Dialog
  c.weightx = 1.0;
  c.weighty = 1.0;
  c.anchor = GridBagConstraints.PAGE_START;
  c.fill = GridBagConstraints.BOTH;
  c.insets = new Insets(10, 10, 0, 10);
  c.gridx = 0;
  c.gridy = 0;
  c.gridwidth = 3;
  c.gridheight = 2;
  window.add(dialog, c); // *** then add dialog by itself*** ???? WTF???

不要那样做 而是将其添加到JScrollPane中,将JScrollPane添加到具有GridBagConstraints的容器中然后将其保留。

您还没有添加GridBagConstraints就将其他几个组件添加到窗口中,几乎没有任何想法,就好像您在没有计划(?)的情况下随意地和随意地编码。 也不要这样做。 停下来,先计划要编码的内容,然后再创建代码。 不要随意输入,因为它太草率了,永远都行不通。 诚实的错误是可以的,但是草率的编码不会。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM