使用swing组件在框架中打开文本文件

时间:2012-09-18 13:00:35

标签: java swing user-interface

我想使用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);
}
}

我应该在第二帧中使用哪个swing组件来打开文本文件?如果可能,请提供代码大纲!!

4 个答案:

答案 0 :(得分:3)

延伸到mKorbel和Dans回答:

你可以这样使用JTextArea

enter image description here

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

<强>参考文献:

答案 1 :(得分:2)

最简单的选择是JTextArea

另一个更好的选择是JEditorPane

您可以查看this文字组件教程,以便更好地了解它们并选择所需的最佳内容。

答案 2 :(得分:2)

答案 3 :(得分:1)

JtextArea text

fileInputStream myFIS;

objectInputStream myOIS(myFIS);

Data = myOIS.read();

text.setText(数据);

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

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