Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9166623
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T15:11:37+00:00 2026-06-17T15:11:37+00:00

I’m useing WindowBuilder, and I want to ask how to search in a text

  • 0

I’m useing WindowBuilder, and I want to ask how to search in a text file for specific word, which I enter to JTextField by clicking a Search button? My program looks like this:

image http://img252.imageshack.us/img252/1410/39931036.png

This is my JTextField and JButton:

private void initialize() {
    frmInformacijaApieMuzikos = new JFrame();
    frmInformacijaApieMuzikos.setResizable(false);
    frmInformacijaApieMuzikos.setIconImage(Toolkit.getDefaultToolkit()
        .getImage(KDVizualizuotas.class.getResource(
        "/lt/kvk/i3_2/kalasnikovas_stanislovas/resources/Sidebar-Music-Blue-icon.png")));
    frmInformacijaApieMuzikos.setTitle("Muzikos stiliai");
    frmInformacijaApieMuzikos.setBounds(100, 100, 262, 368);
    frmInformacijaApieMuzikos.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    txtStilius = new JTextField();
    txtStilius.setBounds(10, 34, 128, 20);
    txtStilius.setColumns(10);

    JButton btnIekoti = new JButton("Ie\u0161koti");
    btnIekoti.setBounds(146, 36, 89, 19);
    btnIekoti.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
        }
    });
}

I have code “search in text file” which works in console, but I need to remake it: “Enter word to JTextField (not in console) and click search button (not Enter button) to find It”. I don’t know how to make It.

My code (These last 2 codes you can skip):

package lt.kvk.i3_2.kalasnikovas_stanislovas;

import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;


public class Stilius {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        try {


            FileReader fr = new FileReader("src/lt/kvk/i3_2/kalasnikovas_stanislovas/Stiliai.txt");
            BufferedReader br = new BufferedReader(fr);
            String stiliuSarasas;
            while((stiliuSarasas = br.readLine()) != null) {
                System.out.println(stiliuSarasas);
                }
            fr.close();


          /** String help = "";  
            System.out.println("Iveskite stiliaus pavadinima apie kuri ieskote informacijos (daugiau funkciju - Pagalba)");

            if ("Pagalba".equalsIgnoreCase(help)) { 
                help = input.nextLine();
            Pagalba pagalba = new Pagalba(help);
            }**/


            String kitasStilius = "Taip";       

            while (!"Ne".equalsIgnoreCase(kitasStilius)) {   
                if ("Taip".equalsIgnoreCase(kitasStilius)) {                 
                    System.out.println("Iveskite stiliaus pavadinima apie kuri ieskote informacijos");

                    String stilius = input.nextLine();
                    Veiksmai stiliausPaieska = new Veiksmai(stilius);   

                }
                else if ("Ne".equalsIgnoreCase(kitasStilius)) {

                } 
                else{
                     System.out.println("Neteisingai pasirinkta.");
                }
                System.out.println("Ar norite ieskoti kito stiliaus?");
                System.out.println("Iveskite: Taip or Ne");
                kitasStilius = input.nextLine();
            }
        }
        catch (IOException e) {
            System.out.println("Error:" + e.toString());
        }
     }
}

and other class

package lt.kvk.i3_2.kalasnikovas_stanislovas;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class Veiksmai {

        public Veiksmai(String stilius) throws IOException {
        BufferedReader bf = new BufferedReader(new FileReader("src/lt/kvk/i3_2/kalasnikovas_stanislovas/Miestai.txt"));
        int counter = 0;                
        String line;

        System.out.println("Ieskoma informacija apie " + stilius);
        ArrayList<String> miestuSarasas = new ArrayList<String>();

        String miestas = null;
        while (( line = bf.readLine()) != null){
            if (line.trim().length() == 0) miestas = null;
               else if (miestas == null) miestas = line;
               int indexfound = line.indexOf(stilius);
               if (indexfound > -1) {
                counter++;
                miestuSarasas.add(miestas);
               }                   
        }
        if (counter > 0) {
            System.out.println(stilius + " turi " + counter + " remejus: " + miestuSarasas);  

            try {
                 File file = new File("src/lt/kvk/i3_2/kalasnikovas_stanislovas/Atsakymas.txt");

                    if (!file.exists()) {
                    file.createNewFile();
                }

                FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(stilius + " turi " + counter + " remejus: " + miestuSarasas+"\n");
                bw.close();
    } 
            catch (IOException e) {
                e.printStackTrace();                
            }
        } else {
            System.out.println("Klaida, nerastas muzikos stilius");
        }
        bf.close();
    }
    public void stabdyti(){

    }
    public void sarasas() throws IOException{
        FileReader fr = new FileReader("src/lt/kvk/i3_2/kalasnikovas_stanislovas/Stiliai.txt");
        BufferedReader br = new BufferedReader(fr);
        String stiliuSarasas;
        while((stiliuSarasas = br.readLine()) != null) {
            System.out.println(stiliuSarasas);
            }
        fr.close();
    }

}

Could you help me, please? I’m still newbie in Java. I tried so many, but everything wont work.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T15:11:38+00:00Added an answer on June 17, 2026 at 3:11 pm

    I did this program long time back, it highlights the word in JTextField automatically.Hope this helps:

    enter image description here

    Code:

    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.GroupLayout.*;
    
    
    public class Stringtext extends JFrame
                           implements DocumentListener {
    
    private JTextField entry;
    private JLabel jLabel1;
    private JScrollPane jScrollPane1;
    private JLabel status;
    private JTextArea textArea;
    
    final static Color  HILIT_COLOR = Color.YELLOW;
    final static Color  ERROR_COLOR = Color.PINK;
    final static String CANCEL_ACTION = "cancel-search";
    
    final Color entryBg;
    final Highlighter hilit;
    final Highlighter.HighlightPainter painter;
    
    
    public Stringtext() {
        initComponents();
      /*code to put text from a file
        InputStream in = getClass().getResourceAsStream("file2.txt");
        try {
            textArea.read(new InputStreamReader(in), null);
        } catch (IOException e) {
            e.printStackTrace();
        }
      */
        textArea.setText("hello Mr! please try to post an SSCCE next time otherwise don't you DARE to...");
        hilit = new DefaultHighlighter();
        painter = new DefaultHighlighter.DefaultHighlightPainter(HILIT_COLOR);
        textArea.setHighlighter(hilit);
    
        entryBg = entry.getBackground();
        entry.getDocument().addDocumentListener(this);
    
        InputMap im = entry.getInputMap(JComponent.WHEN_FOCUSED);
        ActionMap am = entry.getActionMap();
        im.put(KeyStroke.getKeyStroke("ESCAPE"), CANCEL_ACTION);
        am.put(CANCEL_ACTION, new CancelAction()); 
    
        }
    
    
      private void initComponents() {
        entry = new JTextField();
        textArea = new JTextArea();
        status = new JLabel();
        jLabel1 = new JLabel();
    
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setTitle("TextFieldDemo");
    
        textArea.setColumns(20);
        textArea.setLineWrap(true);
        textArea.setRows(5);
        textArea.setWrapStyleWord(true);
        textArea.setEditable(true);
        jScrollPane1 = new JScrollPane(textArea);
    
        jLabel1.setText("Enter text to search:");
    
        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
    
    ParallelGroup hGroup = layout.createParallelGroup(GroupLayout.Alignment.LEADING);
    SequentialGroup h1 = layout.createSequentialGroup();
    ParallelGroup h2 = layout.createParallelGroup(GroupLayout.Alignment.CENTER);
    
    h1.addContainerGap();
    
    h2.addComponent(jScrollPane1, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE);
    h2.addComponent(status, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE);
    
    SequentialGroup h3 = layout.createSequentialGroup();
    h3.addComponent(jLabel1);
    h3.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED);
    h3.addComponent(entry, GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE);
    
    h2.addGroup(h3);
    
    h1.addGroup(h2);
    
    h1.addContainerGap();
    
    hGroup.addGroup(GroupLayout.Alignment.TRAILING, h1);
    
    layout.setHorizontalGroup(hGroup);
    
    
    
    ParallelGroup vGroup = layout.createParallelGroup(GroupLayout.Alignment.LEADING);
    
    SequentialGroup v1 = layout.createSequentialGroup();
    
    v1.addContainerGap();
    
    ParallelGroup v2 = layout.createParallelGroup(GroupLayout.Alignment.BASELINE);
    v2.addComponent(jLabel1);
    v2.addComponent(entry, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE);
    
    v1.addGroup(v2);
    v1.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED);
    v1.addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE);
    v1.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED);
    v1.addComponent(status);
    v1.addContainerGap();
    
    //Add the group v1 to the group vGroup
    vGroup.addGroup(v1);
    //Create the vertical group
    layout.setVerticalGroup(vGroup);
    pack();
       }
    
       public void search() {
        hilit.removeAllHighlights();
    
        String s = entry.getText();
    
        if (s.length() <= 0) {
            message("Nothing to search");
            return;
          }
    
        String content = textArea.getText();
    
        int index = content.indexOf(s, 0);
        if (index >= 0) {   // match found
            try {
                int end = index + s.length();
                hilit.addHighlight(index, end, painter);
                textArea.setCaretPosition(end);
                entry.setBackground(entryBg);
                message("'" + s + "' found. Press ESC to end search");
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
        } else {
            entry.setBackground(ERROR_COLOR);
            message("'" + s + "' not found. Press ESC to start a new search");
        }
       }
    
      void message(String msg) {
        status.setText(msg);
       }
    
       public void insertUpdate(DocumentEvent ev) {
        search();
       }
    
      public void removeUpdate(DocumentEvent ev) {
        search();
       }
    
       public void changedUpdate(DocumentEvent ev) {
       }
    
      class CancelAction extends AbstractAction {
        public void actionPerformed(ActionEvent ev) {
            hilit.removeAllHighlights();
    
            entry.setText("boo");
            entry.setBackground(entryBg);
        }
       }
    
    
       public static void main(String args[]) {
    
    SwingUtilities.invokeLater(new Runnable() {
            public void run() {
    
                UIManager.put("swing.boldMetal", Boolean.FALSE);
        new Stringtext().setVisible(true);
            }
        });
       }
      }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want use html5's new tag to play a wav file (currently only supported
I have an autohotkey script which looks up a word in a bilingual dictionary
I have a text area in my form which accepts all possible characters from
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I have a reasonable size flat file database of text documents mostly saved in
i want to parse a xhtml file and display in UITableView. what is the
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.