【问题标题】:Opening a text file in a frame using swing components使用 swing 组件在框架中打开文本文件
【发布时间】:2012-09-10 18:01:01
【问题描述】:

我想使用 swing 组件在框架中打开一个文本文件,最好使用高亮工具。我在第一帧的文本文件中获取文本文件的名称,并想在第二帧中打开文本文件。我的代码是


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

public class FirstGUI extends JFrame {

private JLabel label;
private JTextField textfield;
private JButton button;

public FirstGUI() {
    setLayout(new FlowLayout());

    label = new JLabel("Enter the file path:");
    add(label);

    textfield = new JTextField();
    add(textfield);

    button = new JButton("Open");
    add(button);

    AnyClass ob = new AnyClass();
    button.addActionListener(ob);
}

public class AnyClass implements ActionListener {
    public void actionPerformed(ActionEvent obj) {
        //SecondGUI s =new SecondGUI();
        //s.setVisible(true);
    }
}

public static void main(String[] args) {

    FirstGUI obj= new FirstGUI();
    obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    obj.setSize(600,600);
    obj.setLocation(100,100);
    obj.setVisible(true);
}
}

我应该在第二帧中使用什么摆动组件来打开其中的文本文件?如果可能,请提供代码大纲!!

【问题讨论】:

    标签: java swing user-interface


    【解决方案1】:

    扩展 mKorbel 和 Dans 答案:

    你可以像这样使用JTextArea

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.lang.reflect.InvocationTargetException;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.SwingUtilities;
    import javax.swing.text.*;
    
    public class LineHighlightPainter {
    
        String revisedText = "Hello, World! ";
        String token = "Hello";
    
        public static void main(String args[]) {
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
    
                    @Override
                    public void run() {
                        new LineHighlightPainter().createAndShowGUI();
                    }
                });
            } catch (InterruptedException | InvocationTargetException ex) {
                ex.printStackTrace();
            }
        }
    
        public void createAndShowGUI() {
            JFrame frame = new JFrame("LineHighlightPainter demo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            JTextArea area = new JTextArea(9, 45);
            area.setLineWrap(true);
            area.setWrapStyleWord(true);
            area.setText(revisedText);
    
            // Highlighting part of the text in the instance of JTextArea
            // based on token.
            highlight(area, token);
    
            frame.getContentPane().add(new JScrollPane(area), BorderLayout.CENTER);
            frame.pack();
            frame.setVisible(true);
        }
    
        // Creates highlights around all occurrences of pattern in textComp
        public void highlight(JTextComponent textComp, String pattern) {
            // First remove all old highlights
            removeHighlights(textComp);
    
            try {
                Highlighter hilite = textComp.getHighlighter();
                Document doc = textComp.getDocument();
                String text = doc.getText(0, doc.getLength());
    
                int pos = 0;
                // Search for pattern
                while ((pos = text.indexOf(pattern, pos)) >= 0) {
                    // Create highlighter using private painter and apply around pattern
                    hilite.addHighlight(pos, pos + pattern.length(), myHighlightPainter);
                    pos += pattern.length();
                }
    
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
        }
    
        // Removes only our private highlights
        public void removeHighlights(JTextComponent textComp) {
            Highlighter hilite = textComp.getHighlighter();
            Highlighter.Highlight[] hilites = hilite.getHighlights();
    
            for (int i = 0; i < hilites.length; i++) {
                if (hilites[i].getPainter() instanceof MyHighlightPainter) {
                    hilite.removeHighlight(hilites[i]);
                }
            }
        }
        // An instance of the private subclass of the default highlight painter
        Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(Color.red);
    
        // A private subclass of the default highlight painter
        class MyHighlightPainter
                extends DefaultHighlighter.DefaultHighlightPainter {
    
            public MyHighlightPainter(Color color) {
                super(color);
            }
        }
    }
    

    或者使用JTextPane 并且可以通过以下方式突出显示文本:

    1) 在文档级别更改任意文本部分的任何样式属性,例如:

    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setForeground(sas, Color.YELLOW);
    doc.setCharacterAttributes(start, length, sas, false);
    

    2) 通过 textPane 级别的荧光笔突出显示:

    DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
    textPane.getHighlighter().addHighlight(startPos, endPos,highlightPainter);
    

    参考资料:

    【讨论】:

      【解决方案2】:

      JtextArea 文本

      fileInputStream myFIS;

      objectInputStream myOIS(myFIS);

      数据 = myOIS.read();

      text.setText(数据);

      这应该让您知道该去哪里。不要忘记使用文件位置设置文件输入流,以便它知道要打开哪个文件。然后 ObjectInputStream 将获取数据并将信息保存到一个名为 Data 的字段中。然后将 textArea 设置为使用 Data 作为信息来“设置”要显示的 textArea。

      注意:ObjectInputStream 不是唯一可用的输入流。您将不得不使用与您的文件相关的输入流。

      【讨论】:

        【解决方案3】:

        【讨论】:

          【解决方案4】:

          最简单的选择是JTextArea

          另一个更好的选择是JEditorPane

          您可以查看this 文本组件教程,以更好地理解它们并选择您需要的最佳组件。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-11-05
            • 2015-02-14
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多