简体   繁体   English

用Java(JDK 7)制作类似于Notepad的应用程序无法使jtextarea自动滚动。 有人能帮我吗?

[英]Making a Notepad-like application in Java (JDK 7), can't make the jtextarea autoscroll. Can someone help me?

Here is all of the code, you can Copy & Paste it into your Java programming software. 这是所有代码,您可以将其复制并粘贴到Java编程软件中。 I developed it in Eclipse. 我在Eclipse中开发了它。 Paste the line you modified/added. 粘贴您修改/添加的行。

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.DefaultCaret;
import javax.swing.border.*;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Notepad extends JFrame implements ActionListener {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
        private JMenuBar menuBar;
        private JMenu menuFile;
        private JMenu menuEdit;
        private JMenuItem open;
        private JMenuItem save;
        private JMenuItem exit;
        private JMenuItem copy;
        private JMenuItem paste;

        private JTextArea page;

        Notepad(){

        super("Notepad");
        init();
        this.setSize(1024, 768);
        this.setVisible(true);
    }//end Notepad

    private void init(){

          //create text area
        page = new JTextArea();
        page.setCaretPosition(page.getDocument().getLength());page.setCaretPosition(page.getDocument().getLength());page.setCaretPosition(page.getDocument().getLength());page.setCaretPosition(page.getDocument().getLength());page.setCaretPosition(page.getDocument().getLength());page.setCaretPosition(page.getDocument().getLength());page.setCaretPosition(page.getDocument().getLength());page.setCaretPosition(page.getDocument().getLength());page.setCaretPosition(page.getDocument().getLength());
        page.setEditable(true);
        page.setFont(new Font("Comic Sans MS", Font.BOLD, 20));
        page.setLineWrap(true);

        //create menus
        menuFile = new JMenu("File");
        menuEdit = new JMenu("Edit");

        //create menu items
        open = new JMenuItem("Open");
        save = new JMenuItem("Save");
        exit = new JMenuItem("Exit");
        copy = new JMenuItem("Copy");
        paste = new JMenuItem("Paste");

        //add listener to menu items
        exit.addActionListener(this);
        copy.addActionListener(this);
        paste.addActionListener(this);
        save.addActionListener(this);
        open.addActionListener(this);

        //add items to menus
        menuFile.add(open);
        menuFile.add(save);
        menuFile.add(exit);

        menuEdit.add(copy);
        menuEdit.add(paste);

        //create menu bar
        menuBar = new JMenuBar();

        //adds menus to the bar
        menuBar.add(menuFile);
        menuBar.add(menuEdit);


        //add stuff to the window
        this.setJMenuBar(menuBar);
        this.add(page);


    }//end init

    //this method opens a file
    private void openFile(){

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        int result = fileChooser.showOpenDialog(this);

        if(result == JFileChooser.CANCEL_OPTION)
            return;

        File fileName = fileChooser.getSelectedFile();

        if (fileName == null || fileName.getName().equals("")){
            JOptionPane.showMessageDialog(this, "Invalid File Name", "This is an" + " invalid file name.", JOptionPane.ERROR_MESSAGE);
        }//end if

        else{
            JOptionPane.showMessageDialog(this, fileName.getName());
            BufferedReader input;
            try{
                input = new BufferedReader(new FileReader(fileName.getAbsolutePath()));
                String line;

                while((line = input.readLine()) != null){
                    page.append(line+"\n");
                }//end while
                input.close();
            }//end try
            catch(Exception e){
                JOptionPane.showMessageDialog(this, "Error", e.toString(), JOptionPane.ERROR_MESSAGE);
            }//end catch
        }//end else
    }//end openFile

    //this method saves our data to a file
    private void saveFile(){

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        int result = fileChooser.showSaveDialog(this);

        if(result == JFileChooser.CANCEL_OPTION)
            return;

        File fileName = fileChooser.getSelectedFile();

        if (fileName == null || fileName.getName().equals("")){
            JOptionPane.showMessageDialog(this, "Invalid File Name", "This is an" + " invalid file name.", JOptionPane.ERROR_MESSAGE);
        }//end if
        else{
            BufferedWriter output;
            try{
                output = new BufferedWriter(new FileWriter(fileName.getAbsolutePath()));
                output.write(page.getText(), 0, page.getText().length());
                output.close();
            }//end try
            catch(Exception e){
                JOptionPane.showMessageDialog(this, "Error", e.toString(), JOptionPane.ERROR_MESSAGE);
            }//end catch
        }//end else
    }//end saveFile

    @Override
    public void actionPerformed(ActionEvent e) {
        //TODO Auto-generated method stub

        if (e.getSource() == exit){
            this.dispose();
        }//end if
        else if (e.getSource() == copy){
            page.copy();
        }//end else if
        else if (e.getSource() == paste){
            page.paste();
        }//end else if
        else if (e.getSource() == save){
            this.saveFile();
        }//end else if
        else{
            this.openFile();
        }//end else
    }//end override

}//end class

I have looked at other stack overflow pages, they didn't work. 我查看了其他堆栈溢出页面,但它们没有起作用。 nothing I tried did. 我没有尝试做任何事情。

Wrapping the JTextArea in a JScrollPane like this makes it work: 像这样在JScrollPane包装JTextArea使其起作用:

this.add(new JScrollPane(page));

It then adds/removes horizontal and vertical scrollbars as needed, and scrolls the scrollpane along with the caret. 然后,根据需要添加/删除水平和垂直滚动条,并与插入符号一起滚动滚动窗格。

The page.setCaretPosition(page.getDocument().getLength()); page.setCaretPosition(page.getDocument().getLength()); is aplied at the time you call it. 在您调用它时被放大了。 That means that I'll set the caret position when you call it. 这意味着当您调用它时,我将设置插入符号的位置。 So that also mean that I should be called after setting the tekst like: 因此,这也意味着在将tekst设置为以下方式后,我应该被叫来:

page.append("Hi");
page.setCaretPosition(page.getDocument().getLength());

And now It will scroll. 现在它将滚动。 But you'll always have to call it if you want to let the area auto-scroll in this way. 但是,如果要以这种方式自动滚动区域,则始终必须调用它。 And if you want to make it a little bit easier you could write a method for it. 而且,如果您想使其变得更简单,则可以为其编写一个方法。

public void scroll(){
    page.setCaretPosition(page.getDocument().getLength());
}

I hope that this helps you and if you need somemore info or clarification feel free to ask. 希望对您有所帮助,如果您需要更多信息或说明,请随时提出。

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

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