java - JScrollPane 滚动条在 GridBagLayout 后不起作用

标签 java mysql database jscrollpane gridbaglayout

我正在为学校制作一个自动聊天客户端,例如 Cleverbot。我有 2 个问题... 1) 由于某种原因,滚动条似乎不起作用。这是一个截图: enter image description here

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;
    }
}

最佳答案

抱歉,直言不讳,但您的问题只是草率的代码之一。

您要将对话框两次 添加到窗口容器中,一次在 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 添加到 with GridBagConstraints 的容器中,然后保留它。

您有几个要添加到窗口的其他组件没有 GridBagConstraints,几乎没有考虑,就好像您是在没有计划的情况下随意草率地编码(?)。也不要这样做。停下来,先计划您要编码的内容,然后才创建您的代码。不要随意输入它,因为那很草率,永远不会奏效。诚实的错误是好的,但草率的编码,不行。

关于java - JScrollPane 滚动条在 GridBagLayout 后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26189180/

相关文章:

java - 如何从 NumberLong 获取日期时间

mysql 同一字段中的多个计数和组值

python - 根据星期几将 Pandas 数据框分成两部分

java - Dagger2 在注入(inject)类中注入(inject)时出错

java - 使用 XMLAdapter 时 JAXB 无法编码(marshal) null 值

java - 如何检查在休息服务中将java对象转换为json所花费的时间

mysql - ABS() 可以处理日期吗?

php - mysql 获取所有其他行如何从同一个表中获得相同的 id

database - 安卓数据库备份

database - 打开/解密 Webex Connect db3 文件