1

I want to open a text file in a frame using swing components, preferably with highlighting facility. I get the name of the text file in a text filed in the first frame and want to open the text file in the second frame.My code is


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

What swing component should I use in my second frame to open a text file in it ? If possible, please provide the outline of the code !!

Dan D.
  • 32,246
  • 5
  • 63
  • 79
OneMoreError
  • 7,518
  • 20
  • 73
  • 112

4 Answers4

3

Extending on mKorbel and Dans answer:

Well you could use a JTextArea like so:

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

Or alternatively use a JTextPane and text can be highlighted by:

1) Changing any style attributes of arbitrary text parts on the document level, something like:

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

2) Highlight via a Highlighter on the textPane level:

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

References:

Community
  • 1
  • 1
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
2

The simplest choice would be a JTextArea.

Another better choice is a JEditorPane.

You can take a look at this text components tutorial for understanding them better and choosing the best you need.

Dan D.
  • 32,246
  • 5
  • 63
  • 79
2

have look at

mKorbel
  • 109,525
  • 20
  • 134
  • 319
1

JtextArea text

fileInputStream myFIS;

objectInputStream myOIS(myFIS);

Data = myOIS.read();

text.setText(Data);

that should give you some kind of an idea where to go. Don't forget to set the file input stream up with a file location so it knows what file to open. Then the ObjectInputStream will take the data and save the information into a field called Data. Then set the textArea to use Data as the information to "Set" the textArea to display.

Note: ObjectInputStream is not the only input stream available to use. you will have to use the input stream that correlates to your file.

Matt Westlake
  • 3,499
  • 7
  • 39
  • 80