Hot questions for Using JTextField in eclipse

Question:

Can someone please tell me what's wrong with this code? I need it to pop up a frame and fill the frame with certain field a namer field and an intake field and also display a button at the bottom of the grid. Any help would be welcomed, Thanks!!

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

    public class FrameDemo 
    //To create the gui and show it.
    {   
    public static void createAndShowGUI()
    {
        //create and set up the window.
        JFrame frame = new JFrame("RungeKutta");
        GridLayout first = new GridLayout(1,14);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create, name and Populate TextField   
        JTextField PL = new JTextField("Pendulum Length", 20);
        //Set TextField to Uneditable. Each will have Empty Field Below For Variables   
        PL.setEditable(false);  
        //Set Textfield for user entered dat
        JTextField PLv = new JTextField();
        //Allow handler for user input on Empty Textfield?

        JTextField AD = new JTextField("Angular Displacement", 20);
        AD.setEditable(false);
            JTextField ADv = new JTextField();

        JTextField AV = new JTextField("Angular Velocity", 20);
        AV.setEditable(false);
        JTextField Avv = new JTextField();

        JTextField TS= new JTextField("Time Steps", 20);
        TS.setEditable(false);
        JTextField TSv = new JTextField();

        JTextField MT = new JTextField("Max Time", 20);
        MT.setEditable(false);
        JTextField MTv = new JTextField();

        JTextField V = new JTextField("Viscosity (0-1)", 20);
        V.setEditable(false);
        JTextField Vv = new JTextField();

        //Create Button to Restart
    JButton BNewGraph = new JButton("Draw New Graph"); //Button to restart entire drawing process
        JLabel emptyLabel = new JLabel("");
    emptyLabel.setPreferredSize(new Dimension(600,500));
    frame.getContentPane().add(PL, first);
    frame.getContentPane().add(PLv, first);
    frame.getContentPane().add(AD, first);
    frame.getContentPane().add(ADv, first);
    frame.getContentPane().add(AV, first);
    frame.getContentPane().add(Avv, first);
    frame.getContentPane().add(TS, first);
    frame.getContentPane().add(TSv, first);
    frame.getContentPane().add(MT, first);
    frame.getContentPane().add(MTv, first);
    frame.getContentPane().add(V, first);
    frame.getContentPane().add(Vv, first);
    frame.getContentPane().add(BNewGraph, first);
    //display the window
    frame.pack();
    frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        //add job to event scheduler
        //create and show GUI
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
            }
    }

Answer:

This is not how you use GridLayout:

frame.getContentPane().add(PL, first);

Instead you'd set the container's layout using the layout manager:

frame.getContentPane().setLayout(first);

and then add components to the container:

frame.getContentPane().add(PL);
frame.getContentPane().add(PLv);
frame.getContentPane().add(AD);
frame.getContentPane().add(ADv);
frame.getContentPane().add(AV);
frame.getContentPane().add(Avv);
frame.getContentPane().add(TS);
frame.getContentPane().add(TSv);
frame.getContentPane().add(MT);
frame.getContentPane().add(MTv);
// and so on for all the components.

You will want to read the tutorial on how to use GridLayout which you can find here: GridLayout Tutorial.

As an aside, note that this:

frame.getContentPane().add(PL);

can be shortened to this:

frame.add(PL);

Also you will want to study and learn Java naming conventions: class names begin with an upper case letter and all method and variables with lower case letters. Also avoid variable names like pl or plv, or ad or adv, and instead use names that are a little bit longer and have meaning, names that make your code self-commenting. So instead of AD, consider angularDisplacementField for the JTextfield's name.


Myself, I'd use a GridBagLayout and do something like:

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.swing.*;

public class GuiDemo extends JPanel {

   // or better -- use an enum for this
   public static final String[] FIELD_LABELS = {
      "Pendulum Length", "Angular Displacement", "Angular Velocity",
      "Time Steps", "Max Time", "Viscocity (0-1)"
   };
   private static final int TEXT_FIELD_COLUMNS = 10;
   private static final int GAP = 3;
   private static final Insets RIGHT_GAP_INSETS = new Insets(GAP, GAP, GAP, 3 * GAP);
   private static final Insets BALANCED_INSETS = new Insets(GAP, GAP, GAP, GAP);
   private Map<String, JTextField> labelFieldMap = new HashMap<>();

   public GuiDemo() {
      JPanel labelFieldPanel = new JPanel(new GridBagLayout());
      int row = 0;

      // to make sure that no focusAccelerator is re-used
      Set<Character> focusAccelSet = new HashSet<>();
      for (String fieldLabelLText : FIELD_LABELS) {
         JLabel fieldLabel = new JLabel(fieldLabelLText);
         JTextField textField = new JTextField(TEXT_FIELD_COLUMNS);
         labelFieldPanel.add(fieldLabel, getGbc(row, 0));
         labelFieldPanel.add(textField, getGbc(row, 1));
         labelFieldMap.put(fieldLabelLText, textField);

         for (char c : fieldLabelLText.toCharArray()) {
            if (!focusAccelSet.contains(c)) {
               textField.setFocusAccelerator(c);
               fieldLabel.setDisplayedMnemonic(c);
               focusAccelSet.add(c);
               break;
            }
         }

         row++;
      }
      JButton button = new JButton(new DrawGraphAction("Draw New Graph"));

      labelFieldPanel.add(button, getGbc(row, 0, 2, 1));

      setLayout(new BorderLayout(GAP, GAP));
      add(labelFieldPanel, BorderLayout.CENTER);
   }

   private class DrawGraphAction extends AbstractAction {
      public DrawGraphAction(String name) {
         super(name);
         int mnemonic = (int) name.charAt(0);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         // TODO calculation method

      }
   }

   public static GridBagConstraints getGbc(int row, int column) {
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = column;
      gbc.gridy = row;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;
      gbc.fill = GridBagConstraints.HORIZONTAL;
      if (column == 0) {
         gbc.anchor = GridBagConstraints.LINE_START;
         gbc.fill = GridBagConstraints.BOTH;
         gbc.insets = RIGHT_GAP_INSETS;
      } else {
         gbc.anchor = GridBagConstraints.LINE_END;
         gbc.fill = GridBagConstraints.HORIZONTAL;
         gbc.insets = BALANCED_INSETS;
      }

      return gbc;
   }

   public static GridBagConstraints getGbc(int row, int column, int width, int height) {
      GridBagConstraints gbc = getGbc(row, column);
      gbc.gridwidth = width;
      gbc.gridheight = height;
      gbc.insets = BALANCED_INSETS;
      gbc.fill = GridBagConstraints.BOTH;
      return gbc;
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("Gui Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new GuiDemo());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Question:

The following is my menu class. I want to obtain values from the masterdetails class's textfields when i click the Save button. How do i do? I have tried creating an object of the second class and using the getText() to retrieve data but I am not able to get it somehow

import java.awt.*;

import javax.swing.*;
import javax.swing.JOptionPane.*;

import java.awt.event.*;

 public class menu extends JFrame implements ActionListener
{
public JMenu jb1,jb7,jb8;
public JPanel panel;
public  ImageIcon i,j;
public JFrame jf;
private JMenuBar menubar=new JMenuBar(); 
String str = null;
String str1=null;
public menu()
 {
 setTitle("Main_Screen");
 setJMenuBar(menubar);
 jb1=new JMenu("File");`enter code here`
 jb7=new JMenu("Details");
 jb8=new JMenu("Report");

 JMenuItem e=new JMenuItem("Exit");

 menubar.add(jb1);
 menubar.add(jb7);
 menubar.add(jb8);


 JMenuItem jm1=new JMenuItem("Save");
 jb1.add(jm1); 
 JMenuItem jm3=new JMenuItem("Save As");
 jb1.add(jm3); 
 JMenuItem jm4=new JMenuItem("Update");
 jb1.add(jm4); 
 JMenuItem jm5=new JMenuItem("Retrieve");
 jb1.add(jm5);
 JMenuItem jm6=new JMenuItem("Exit");
 jb1.add(jm6);



 JMenuItem jm8=new JMenuItem("Master Details");
 jb7.add(jm8);
 JMenuItem jm12=new JMenuItem("Performance Testing");
 jb7.add(jm12);
 JMenuItem jm13=new JMenuItem("Raw Materials");
 jb7.add(jm13);

 JMenuItem jm81=new JMenuItem("Generate");
 jb8.add(jm81);




  panel=(JPanel)getContentPane( );
       panel.setLayout(new BorderLayout());

       JLabel lb1=new JLabel("",i,JLabel.CENTER);
       panel.add(lb1,BorderLayout.CENTER);

e.addActionListener(this);


jm1.addActionListener(this);
jm3.addActionListener(this);
jm4.addActionListener(this);
jm5.addActionListener(this);
jm6.addActionListener(this);
jm13.addActionListener(this);

jm12.addActionListener(this);

jm8.addActionListener(this);
jm81.addActionListener(this);

}

public void actionPerformed(ActionEvent a)
{

    String str=a.getActionCommand();
    if(str.equals("Master Details"))
    {
    masterdetails f=new masterdetails();
    f.setSize(800,600);
    f.setVisible(true);
    f.show();

    }

    if(str.equals("Save"))
    {
    masterdetails m=new masterdetails();

    //m.setSize(800,600);
    //m.setVisible(true);
    //m.show();

    }

}


 public static void main(String args[])
 {
 menu m=new menu();
 m.setSize(800,600);
 m.setVisible(true);
 m.show();
 }
 }

The Master details class looks as follows.

import java.awt.Font;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.awt.*;

import javax.swing.*;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.wb.swt.SWTResourceManager;


public class masterdetails extends JFrame implements ActionListener {

    public JPanel panel;
    public JLabel title,lblnumber,lblPSINo,lblmodel,lblcapacity,lblpressure,lblplungerdia;
    public JLabel lblnostrk,lblclient,lblpono,lblsize,lblstrokelen;
    public JLabel lblmotorhp,lblmotorrpm,lblmotorno,lblmake,lblpumptagno,lblitemno,lbldate;

    public JButton b1;

    public String number1="";
    public JTextField number,PSINo,model,capacity,pressure,plungerdia;
    public JTextField nostrk,client,pono,size,strokelen;
    public JTextField motorhp,motorrpm,motorno,make,pumptagno,itemno;
    DateTime date;
    Font g;

    String str=null;

    public masterdetails()
    {   g=new Font("",Font.BOLD,18);
        panel=(JPanel)getContentPane();
        panel.setLayout(null);
        title=new JLabel("Master Details");
        title.setFont(g);
        title.setBounds(325, 10, 150, 40);
        panel.add(title);

        lblnumber=new JLabel("No.");
        lblnumber.setBounds(10, 57, 87, 21);
        number=new JTextField("");
        number.setBounds(121, 57, 116, 21);     
        panel.add(lblnumber);
        panel.add(number);

        lbldate=new JLabel("Date");
        lbldate.setBounds(10, 97, 87, 21);
        panel.add(lbldate);

        lblPSINo=new JLabel("Pump SI No.");
        PSINo=new JTextField("");
        PSINo.setBounds(121, 137, 116, 21);
        lblPSINo.setBounds(10, 137, 87, 21);
        panel.add(lblPSINo);
        panel.add(PSINo);

        lblmodel=new JLabel("Model");
        model=new JTextField("");
        model.setBounds(121, 175, 116, 21);
        lblmodel.setBounds(10, 177, 87, 21);
        panel.add(lblmodel);
        panel.add(model);

        lblcapacity=new JLabel("Capacity");
        capacity=new JTextField("");
        lblcapacity.setBounds(10, 217, 87, 21);
        capacity.setBounds(121, 213, 116, 21);
        panel.add(lblcapacity);
        panel.add(capacity);

        lblpressure=new JLabel("Pressure");
        pressure=new JTextField("");
        lblpressure.setBounds(10, 257, 87, 21);
        pressure.setBounds(121, 252, 116, 21);
        panel.add(lblpressure);
        panel.add(pressure);

        lblplungerdia=new JLabel("Plunger Dia.");
        plungerdia=new JTextField("");
        lblplungerdia.setBounds(10, 297, 87, 21);
        plungerdia.setBounds(121, 291, 116, 21);
        panel.add(lblplungerdia);
        panel.add(plungerdia);

        lblnostrk=new JLabel("No.of Strk/Min");
        nostrk=new JTextField("");
        lblnostrk.setBounds(10, 337, 87, 21);
        nostrk.setBounds(121, 330, 116, 21);
        panel.add(nostrk);
        panel.add(lblnostrk);

        lblpumptagno=new JLabel("Pump Tag No.");
        pumptagno=new JTextField("");
        pumptagno.setBounds(121, 369, 116, 21);
        panel.add(pumptagno);
        lblpumptagno.setBounds(10, 369, 87, 21);
        panel.add(lblpumptagno);

        lblclient=new JLabel("Client.");
        client=new JTextField("");
        client.setBounds(430, 57, 214, 21);
        panel.add(client);
        lblclient.setBounds(335, 57, 87, 21);
        panel.add(lblclient);

        lblpono=new JLabel("P.O. No.");
        pono=new JTextField("");
        pono.setBounds(430, 96, 214, 21);
        panel.add(pono);
        lblpono.setBounds(335, 96, 87, 21);
        panel.add(lblpono);

        lblsize=new JLabel("Size");
        size=new JTextField("");
        size.setBounds(430, 137, 214, 21);
        panel.add(size);
        lblsize.setBounds(335, 137, 87, 21);
        panel.add(lblsize);

        lblstrokelen=new JLabel("Stroke Length");
        strokelen=new JTextField("");
        strokelen.setBounds(430, 175, 214, 21);
        panel.add(strokelen);
        lblstrokelen.setBounds(335, 175, 87, 21);
        panel.add(lblstrokelen);

        lblmotorhp=new JLabel("Motor H.P.");
        motorhp=new JTextField("");
        motorhp.setBounds(430, 213, 214, 21);
        panel.add(motorhp);
        lblmotorhp.setBounds(335, 213, 87, 21);
        panel.add(lblmotorhp);

        lblmotorrpm=new JLabel("Motor RPM");
        motorrpm=new JTextField("");
        motorrpm.setBounds(430, 252, 214, 21);
        panel.add(motorrpm);
        lblmotorrpm.setBounds(335, 252, 87, 21);
        panel.add(lblmotorrpm);

        lblmotorno=new JLabel("Motor No.");
        motorno=new JTextField("");
        motorno.setBounds(430, 291, 214, 21);
        panel.add(motorno);
        lblmotorno.setBounds(335, 291, 87, 21);
        panel.add(lblmotorno);

        lblmake=new JLabel("Make");
        make=new JTextField("");
        make.setBounds(430, 330, 214, 21);
        panel.add(make);
        lblmake.setBounds(335, 330, 87, 21);
        panel.add(lblmake);

        lblitemno=new JLabel("Item No.");
        itemno=new JTextField("");
        itemno.setBounds(430, 369, 214, 21);
        panel.add(itemno);
        lblitemno.setBounds(335, 369, 87, 21);
        panel.add(lblitemno);

        b1=new JButton("Next");
        b1.setBounds(671, 507, 75, 25);
        panel.add(b1);
        b1.addActionListener(this);


    }

    @Override
    public void actionPerformed(ActionEvent a) {

        // TODO Auto-generated method stub

        String str=a.getActionCommand();

        if(str.equals("Next"))
        {

        performancetest f=new performancetest();
        f.setSize(800,600);
        f.setVisible(true);
        f.show();

        }


    }
    public static void main(String args[])
    {
    masterdetails f=new masterdetails();
            f.setVisible(true);
            f.setSize(800,600);
            f.show();
    }





}

Answer:

To maintain encapsulation, I would suggest you create a getter for the String in question in the class that has the Textfield. This method should be public and only return the text that Textfield has.

You can then access it from the other class by simply calling it on the appropriate object.

Example:

public class A{
    private B b;


    private void someMethod(){
        //This will receive the Text of the Textfield!
        String text = b.getTextfieldValue();
    }
}


public class B{
    private JTextField text;

    public String getTextfieldValue(){
        return text.getText();
    }
}

Question:

I'm trying to make a simple program where there is a text input field and a label, and when you input something to the field it stores the input as "testInput" and changes the label to that text. I'm using Eclipse's Window Builder plugin for this, and it has worked fine before. What happens now is it will take the text in, but wont send it back out to the jLabel. Here is my code:

package interest;

import java.awt.EventQueue;

import javax.swing.JFrame;
import java.awt.GridBagLayout;
import javax.swing.JTextField;
import java.awt.GridBagConstraints;
import javax.swing.JLabel;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class TestWin {

String testInput;

private JFrame frame;
private JTextField txtTest;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                TestWin window = new TestWin();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public TestWin() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    GridBagLayout gridBagLayout = new GridBagLayout();
    gridBagLayout.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0};
    gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0, 0};
    gridBagLayout.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
    gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
    frame.getContentPane().setLayout(gridBagLayout);

    txtTest = new JTextField(); 
    //Change label when enter is pressed
    txtTest.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            testInput = txtTest.getText();
            txtTest.setText(testInput);
        }
    });
    txtTest.setText("test");
    GridBagConstraints gbc_txtTest = new GridBagConstraints();
    gbc_txtTest.insets = new Insets(0, 0, 5, 0);
    gbc_txtTest.fill = GridBagConstraints.HORIZONTAL;
    gbc_txtTest.gridx = 5;
    gbc_txtTest.gridy = 1;
    frame.getContentPane().add(txtTest, gbc_txtTest);
    txtTest.setColumns(10);

    JLabel lblTest = new JLabel("test");
    GridBagConstraints gbc_lblTest = new GridBagConstraints();
    gbc_lblTest.gridx = 5;
    gbc_lblTest.gridy = 4;
    frame.getContentPane().add(lblTest, gbc_lblTest);
}

}

I'm sure I'm making a really simple mistake, so any help is appreciated!


Answer:

Put

JLabel lblTest = new JLabel("test");

at the begining of initialize() (or anywhere above txtTest.addActionListener...), and then replace

txtTest.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        testInput = txtTest.getText();
        txtTest.setText(testInput);
    }
});

for

txtTest.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        testInput = txtTest.getText();
        lblTest.setText(testInput);    //This line was changed.
    }
});

Question:

I have a main frame : JFrame>contentFrame>ScrollPane>BigPanel>panel_1T

private JPanel contentPane;
private JPanel BigPanel;
private JPanel panel_1T;

In panel_1T, I have put a FOOD button WITH its actionListener:

JButton button_19 = new JButton("FOOD");
button_19.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {

            newFoodUI nf = new newFoodUI();//Open other class
            nf.setVisible(true);
            nf.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);      

                                                 }
                                               });
panel_1T.setLayout(new GridLayout(0, 2, 0, 0));
panel_1T.add(button_19);

When user click FOOD button, new JFrame in newFoodUI class will be shown.: JFrame>contentPane>panel>tabbedPane>panel_3>panel_5

In panel_5, I put a JTextField:

public static JTextField textField_3;

textField_3 = new JTextField();
panel_5.add(textField_3, "9, 4, fill, default");
textField_3.setColumns(10);

User will write some text into textField_3. Then user click SAVE button in panel_3, it will perform this:

JButton button_4 = new JButton("SAVE");
button_4.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

                setContentPane(contentPane);
                panel_3.revalidate();
                panel_3.repaint();
                panel_3.updateUI();

                panel_5.revalidate();
                panel_5.repaint();
                panel_5.updateUI();


                contentPane.revalidate();
                contentPane.repaint();

            JOptionPane.showMessageDialog(null, "Saved !");

        }
    });
    button_4.setBounds(873, 396, 75, 33);
    contentPane.add(button_4);
}

The result is, when I click SAVE button and close the Frame in newFoodUI, I will reopen back by click the FOOD button to check whether the text I wrote has been saved or not. But its not saving the text I wrote.


Answer:

You have to save the value from the textfeld textField_3.getText() and set this value manually to textfeld when showing textField_3.setText(value). So you have to keep your value in your project or store persistent somewhere.

Question:

Hey all the following code below works with highlighting the supplied word to search for but if there are more than just one (1) of that word in the sentence then it wont find it. It just stops at finding one (1) match.

private JFrame frame;
private static JTextField textField;
private static JTextField txtWorld;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                CaretDemo window = new CaretDemo();
                window.frame.setVisible(true);

                String text = "hello world. How are you?";

                textField.setText(text);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public CaretDemo() {
    initialize();
}

private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    textField = new JTextField();
    textField.setBounds(21, 11, 350, 36);
    frame.getContentPane().add(textField);
    textField.setColumns(10);

    txtWorld = new JTextField();
    txtWorld.setColumns(10);
    txtWorld.setBounds(21, 156, 350, 36);
    frame.getContentPane().add(txtWorld);

    JButton btnNewButton = new JButton("New button");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Highlighter highlighter = textField.getHighlighter();
            HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.pink);          
            int p0 = textField.getText().indexOf(txtWorld.getText());
            int p1 = p0 + txtWorld.getText().length();

            try {
                highlighter.removeAllHighlights();
                highlighter.addHighlight(p0, p1, painter);
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
        }
    });

    btnNewButton.setBounds(221, 203, 128, 29);
    frame.getContentPane().add(btnNewButton);
}

The above code looks like this when ran and supplied the word "world" to find.

But now if I add to the sentence and add another "world" then hit the button this is what it looks like:

As you see, it still has the same highlighted word without also highlighting the second (2) "world".

UPDATE 1

I have attempted using regex in order to loop and find the needed word.

btnNewButton_3.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        System.out.println("hi");
        String theSentence = txtTheSentence.getText();
        String WordToFind = txtWordToFind.getText();
        Highlighter h = txtWordToFind.getHighlighter();

        Pattern pattern = Pattern.compile("\\b"+WordToFind+"\\b", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(theSentence);

        if(matcher.find()){
            String extractedWord = matcher.group(0);
            System.out.println(extractedWord);
        }
    }
});

But this does not produce even one word found.


Answer:

it still has the same highlighted word without also highlighting the second (2) "world" -

Well that is exactly what your code does.

First you remove all the highlights and then add back a single highlight.

If you want multiple words to be highlighted then you need to:

  1. first remove all the highlights and then
  2. write a loop and process all the text in the string.

You can use the String.indexOf(text, fromIndex) method to continue the search from a new index once you find the matching text.

Question:

I am using the eclipse GUI drag and drop tool. I have a JTextField in my program which shows content from a line in a textfile. Now, I want to add a horizontal scrollbar underneath the JTextField so that the user can view the content no matter how long it is.

I have the scrollbar and JTextField ready in my JFrame. Can someone provide me with guidance on how to link them please?


Answer:

Don't try to use a JTextField and a JScrollBar.

Instead, use a JTextArea which is designed to work with a JScrollPane:

JTextArea ta = new JTextArea(1, 10);
ta.getDocument().putProperty("filterNewlines", Boolean.TRUE);
JScrollPane sp = new JScrollPane( ta );
sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

You need to reserve space for the scrollbar otherwise it will paint over top of the text. The scrollbar will be activated when required.

This "filterNewLines" property just removes newline characters from the text so only a single line of text can be displayed in the text area.