I am very new to Java. I want to write a program which simulates a garden. It must have 3 buttons being centre, side and anywhere. When i press centre it should highlight names of plants which are to be planted to the centre of the garden, when i press side, it highlights names to be planted on the sides
Asked
Active
Viewed 233 times
-1
-
2So what's the problem? – Aman Agnihotri Nov 20 '14 at 12:37
-
Please show what you've tried already -- a code sample will increase your chances of getting meaningful assistance. – eebbesen Nov 20 '14 at 12:40
-
public class Centre implements ActionListener { private JTextPane1 comp; private String textToHighlight; public MultiHighlight(jTextPane1 c, String chars) { comp = c; charsToHighlight = chars; } public void actionPerformed(ActionEvent e) { Highlighter h = comp.getHighlighter(); h.removeAllHighlights(); String text = jTextPane1.getText(); String words[] = text.split(" "); for(int i = 0;i
– Moamogedi Sonny Malefho Nov 20 '14 at 13:15 -
if(temp.equals("word")){ try{ h.addHighlight(i, temp.length(), DefaultHighlighter.DefaultPainter); } catch(Exception e){ } } } public static void main(String args[]) { JFrame frame = new JFrame("Gadernplanner"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTextArea area = new JTextArea(5, 20); area – Moamogedi Sonny Malefho Nov 20 '14 at 13:16
-
.setText("Hydrangea Roses Lawn Acca Alkanna Fragaria Cyclamen "); frame.getContentPane().add(new JScrollPane(area), BorderLayout.CENTER); JButton b = new JButton("Central"); b.addActionListener(new MultiHighlight(area, "Roses")); frame.getContentPane().add(b, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); } } – Moamogedi Sonny Malefho Nov 20 '14 at 13:16
-
@Abrar I cannot make this work, find above my code – Moamogedi Sonny Malefho Nov 20 '14 at 13:29
-
You can find your answer [here][1]. Please ck it. [1]: http://stackoverflow.com/questions/14086165/jtextpane-highlight-multiple-words – Nov 20 '14 at 14:22
-
You can find your answer [here][1]. Please ck it. [1]: http://stackoverflow.com/questions/14086165/jtextpane-highlight-multiple-words – Nov 20 '14 at 14:35
1 Answers
0
Try this
Highlighter h = jTextPane1.getHighlighter();
h.removeAllHighlights();
String text = jTextPane1.getText();
String words[] = text.split(" ");
for(int i = 0;i<words.length;i++){
String temp = words[i];
if(temp.equals("word")){
try{
h.addHighlight(i, temp.length(), DefaultHighlighter.DefaultPainter);
}
catch(Exception e){
}
}
}

Abrar Jahin
- 13,970
- 24
- 112
- 161