2014-10-04 3 views
1

학교용 클레버봇과 같은 자동 채팅 클라이언트를 만들고 있습니다. 2 가지 문제가 있습니다 ... 1) 스크롤 막대가 어떤 이유로 작동하지 않는 것 같습니다. 여기에 스크린 샷은 다음과 같습니다 enter image description hereGridBagLayout 이후 JScrollPane 스크롤 바가 작동하지 않습니다.

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

답변

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에 추가하고 GridBagConstraints가 인 컨테이너 에 JScrollPane을 추가하고 그대로 두십시오.

GridBagConstraints없이 창 에 추가 할 다른 여러 구성 요소가 거의없는 것처럼 거의 계획하지 않은 채로 무작위로 그리고 슬프게 코딩하는 것처럼 보입니다. 이것도하지 마십시오. 코드 작성을 중단하고 코드 작성을 계획하십시오. 그걸 조잡하고 결코 작동하지 않을 것이므로 자유롭게 생각해서 타이핑하지 마십시오. 정직한 오류는 괜찮지 만 엉성한 코딩은 아닙니다.

+0

+1 제한없이 추가되는 모든 "정크"를 알리는 데 +1. 그 코드는 필요하지 않습니다. – camickr

+0

@camickr : 감사합니다. 이 사람은 단지 벽에 임의의 쓰레기를 버리고 무엇이 달라 붙는 지보고 있습니다. 그러면 프로그램을 성공적으로 만들 수있는 방법이 아닙니다. 나는 무뚝뚝하고 어리 석었지만 실수는 너무 심해서 스스로 도울 수 없었다. –

+0

고마워요, 지금 당장 이걸 시도하고 있습니다 ... 저는 스윙에 익숙하지 않고이 모든 것들이 아주 분명한 질문들로 인해 유감입니다. :) –

1

) 스크롤 바는 작동하지 않는 것

window.add(dialog, c); 

다이얼로그가 아닌 윈도우에 스크롤 패널을 추가해야합니다. 대화 상자를 만들 때

JTextArea dialog = new JTextArea(5, 30); 

과 같은 문자를 사용해야합니다. 따라서 텍스트 영역을 적당한 크기로 만들 수 있습니다.

경우 (e.getKeyCode() == KeyEvent.VK_ENTER) {

는 Enter 키를 수신하는 모든 KeyListener를 사용하지 마십시오. 대신 텍스트 필드에 ActionListener를 추가하십시오. Enter 키를 누르면 ActionListener가 호출됩니다. 또한 텍스트 필드의 편집 가능 상태를 토글하는 이유는 무엇입니까? 그렇게 할 필요가 없습니다.

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

텍스트 영역에 텍스트를 추가하지 마십시오. 그냥 텍스트 영역의 append(...) 메소드를 사용하십시오.

관련 문제