2014-10-04 5 views
1

Я делаю клиент для автоматического чата, такой как Cleverbot для школы. У меня есть 2 проблемы ... 1) полоса прокрутки не работает по какой-то причине. Вот скриншот: enter image description hereПрокрутка панели JScrollPane не работает после GridBagLayout

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 или что-то в этом роде? Есть ли более простой способ сделать это, когда я могу сделать матрицу похожей на ту, что у меня есть, читая текстовый файл?

*************** EDIT ****************

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

ответ

1

Извините, что вам грубо, но ваша проблема - просто один из неряшливых кодов.

Вы добавляете диалоговое окно дважды в контейнер окна, один раз в 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, почти без мыслей, почти как если бы вы случайно и небрежно кодировали без планирования (?). Не делайте этого. Остановитесь, планируйте, что вы хотите сначала записать, и только затем создайте свой код. Не вводите его в задумчивость, так как это неряшливо и никогда не будет работать. Честные ошибки - это хорошо, но небрежное кодирование, нет.

+0

+1 для заметок всех «нежелательных», которые добавляются без ограничений. Ничего из этого кода не требуется. – camickr

+0

@camickr: спасибо, и я сразу ответил на ваш ответ. Этот парень просто бросает случайный хлам на стену и видит, какие палки, и это не то, как вы можете успешно создать программу. Я был тупым, возможно, слишком тупым, но ошибки настолько вопиющие, что я не мог с собой поделать. –

+0

Спасибо, я сейчас пытаюсь это сделать ... Я новичок в качелях и все это, поэтому извините за очевидные вопросы :) –

1

) полоса прокрутки, кажется, не работает

window.add(dialog, c); 

Вам нужно добавить прокрутку в окно, а не диалогом. Также, когда вы создаете диалог, вы должны использовать что-то вроде:

JTextArea dialog = new JTextArea(5, 30); 

поэтому текстовая область может быть создана с разумным размером.

если (e.getKeyCode() == KeyEvent.VK_ENTER) {

Не используйте KeyListener для прослушивания клавиши Enter. Вместо этого добавьте ActionListener в текстовое поле. ActionListener будет вызываться при нажатии клавиши Enter. Также почему вы переключаете редактируемое состояние текстового поля? Это не нужно делать.

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

Не добавляйте текст в текстовую область. Просто используйте метод текстовой области append(...).

Смежные вопросы