how to color a particular word in a jtextpane?


i have searched in the google but all examples are quite complex so this is my code can you give a example code to color a particular text like "void"
so that i can learned it in a simple way
please package highlighter; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; import javax.swing.JTextPane; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultHighlighter; /** * * @author Admin */ public class Highlighter implements KeyListener{ /** * @param args the command line arguments */ JTextPane text; void gui() { JFrame frame = new JFrame(); text = new JTextPane(); frame.add(text, BorderLayout.CENTER); String s = text.getText(); s.indexOf(s); int lenght = s.length(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { // TODO code application logic here new Highlighter().gui(); } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { throw new UnsupportedOperationException("Not supported yet."); } public void keyReleased(KeyEvent e) { throw new UnsupportedOperationException("Not supported yet."); } }
Posted On: Wednesday 17th of October 2012 05:31:46 AM Total Views:  138
View Complete with Replies

RELATED TOPICS OF Swing / AWT / SWT PROGRAMMING LANGUAGE




Change icon color dinamically

! I'm trying to create a JFrame with 3 circles inside it and make it work like a traffic light. I've created a separate class for lights, but I can't make them change colors dinamically, because once the icon has been drawn, I can't change it's color anymore Should I give up this idea or there is a way to get it done package trafficlight; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import javax.swing.Icon; public class Light implements Icon { private int size; private Color colorOff = Color.BLACK; private Color currentColor = Color.BLACK; private Color colorOn; private int delay; public Light(Color color, int size, int delay) { this.colorOn = color; this.size = size; this.delay = delay; } public void switchLight(boolean turnOn) { //here I want to make my Light to change its color } @Override public void paintIcon(Component c, Graphics g, int x, int y) { g.setColor(currentColor); g.drawOval(x, y, size, size); g.fillOval(x, y, size, size); } @Override public int getIconWidth() { return size; } @Override public int getIconHeight() { return size; } public int getDelay() { return delay; } public void setDelay(int delay) { this.delay = delay; } }
VIEWS ON THIS POST

133

Posted on:

Thursday 20th September 2012
View Replies!

color help

Folks, Below is a code I have been writing on my own (well a modification from what online version read). The error has been highlighted. import javax.swing.JOptionPane; public class playwithrange { public static void main(String[] args) { String color ; color= JOptionPane.showInputDialog("Choose between green, black and white"); switch (color){ case green: System.out.println("You are a green person"); break; default: System.out.println("Eh whatever"); } } }
VIEWS ON THIS POST

129

Posted on:

Thursday 20th September 2012
View Replies!

how to get colored line to differentiate text field array in swing

I have developed one frame on which I used GridBagLayout to arrange textfields of 12X12. i.e., total 144 textfields on frame. Now I want to differentiate these text fields with colored line after each 3 columns and three rows as shown in the following diagram. I shouldn't change the names of that text fields, because I interrelated those text fields using their names as jt[0][0], jt[0][1]......jt[6][2]........ and So on.I tried in many ways, but I couldn't find the solution. Please suggest. Below is the some part of my code.
VIEWS ON THIS POST

232

Posted on:

Friday 21st September 2012
View Replies!

Program color scheme controlled by a Colors class: object or enum?

I'm writing a rather large program with lots of classes and potentially lots of JFrames. Could I have one class devoted to establishing the primary selection of colors that will be repeated throughout the program That way, rather than remembering each color definition, I can just code something like Colors.TitleFont to represent the color of the title of each window, and Colors.InputPanelBg to represent the background of any input window. I have not found examples of this on-line, but it seems reasonable. Would a Colors object or an Enum work for this Here is my attempt, but Eclipse says "The constructor GSCOLORS(String) is undefined." import java.awt.Color; public enum GSCOLORS { InputPanelA("0xa29292"), InputPanelB("0x92a292"); private Color col; GSCOLORS(Color colorId) { col = colorId; } public Color getCol() { return col; } }
VIEWS ON THIS POST

134

Posted on:

Friday 21st September 2012
View Replies!

having problems with setting the color of a buffered Imaghe

I created a buffered image in my programme and I want it to have a green (orany color other than black)background however i have been unable to get it to change from black to any other other color.hers the code i have been working with .
VIEWS ON THIS POST

332

Posted on:

Friday 21st September 2012
View Replies!

Change Background color on button Click

Hi I want to change Background color of Jpanel and its font on button click. Can anyone tell me what i am doing wrong Here is the code: import java.applet.*; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.event.*; import javax.swing.*; public class test3 extends Applet { JPanel c; JScrollPane s; Button connect; Panel controls; Color back,fore; public void init() { back = Color.black; fore = Color.white; setBackground(Color.darkGray); setLayout(new BorderLayout()); s = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); //s.setSize(100, 100); add("Center",s); c = new myCanvas11(this); s.setOpaque(false); s.setViewportView(c); //s.add(c); c.setSize(1000, 16000); add("North", controls = new Panel()); controls.setLayout(new FlowLayout()); controls.add(connect = new Button("Change Color")); } public void start() { // s.setScrollPosition(100, 100); } public boolean action(Event e, Object arg) { back = Color.magenta; fore = Color.blue; //setBackground(back); //invalidate(); //repaint(); c.setBackground(back); c.repaint(); //s.getViewport().setBackground(back); // s.getViewport().repaint(); //c.repaint(); c.setFocusable(true); return true; } } class myCanvas11 extends JPanel implements KeyListener { Image buffImage; Graphics offscreen; boolean initDone = false; int chw, chh; // size of a char (in pixels) int chd; // offset of char from baseline int width, height; // size of applet (in pixels) int w, h; // size of applet (in chars) Font fn; Graphics gr; int nh, nw; test3 owner; static int counter = 0; myCanvas11(test3 t) { super(); owner = t; nh = 16000; nw = 1000; this.setOpaque(true); this.setFocusable(true); addKeyListener(this); } public void reshape(int nx, int ny, int nw1, int nh1) { if (nw1 != width || nh1 != height) { width = nw; height = nh; gr = getGraphics(); fn = new Font("Courier", Font.PLAIN, 11); if (fn != null) gr.setFont(fn); FontMetrics fnm = gr.getFontMetrics(); chw = fnm.getMaxAdvance(); chh = fnm.getHeight(); chd = fnm.getDescent(); // kludge for Windows NT and others which have too big widths if (chw + 1 >= chh) { chw = (chw + 1) / 2; } // work out size of drawing area h = nh / chh; w = nw / chw; buffImage = this.createImage(nw, nh); offscreen = buffImage.getGraphics(); //offscreen.setColor(Color.black); //offscreen.fillRect(0, 0, nw, nh); offscreen.setColor(Color.blue); offscreen.setFont(fn); if (initDone) offscreen.drawString(" World!", 0, 50); else offscreen.drawString("khushbu", 2, 50); initDone = true; offscreen.drawImage(buffImage, 0, 0, this); } super.reshape(nx, ny, nw, nh); } public void paint(Graphics g) { // if (!initDone) // initpaint(g); // else g.drawImage(buffImage, 0, 0, this); //g.drawImage(buffImage, 0, 0, owner.back, this); } public void update(Graphics g) { g.drawImage(buffImage, 0, 0, this); super.update(g); //g.drawImage(buffImage, 0, 0, owner.back, this); } public void initpaint(Graphics g) { try { nh = getHeight(); nw = getWidth(); gr = getGraphics(); fn = new Font("Courier", Font.PLAIN, 11); if (fn != null) gr.setFont(fn); FontMetrics fnm = gr.getFontMetrics(); chw = fnm.getMaxAdvance(); chh = fnm.getHeight(); chd = fnm.getDescent(); // kludge for Windows NT and others which have too big widths if (chw + 1 >= chh) { chw = (chw + 1) / 2; } // work out size of drawing area h = nh / chh; w = nw / chw; buffImage = this.createImage(nw, nh); offscreen = buffImage.getGraphics(); //offscreen.setColor(Color.black); //offscreen.fillRect(0, 0, nw, nh); offscreen.setColor(Color.white); offscreen.setFont(fn); if (initDone) offscreen.drawString(" World!", 0, 50); else offscreen.drawString("khushbu", 2, 50); initDone = true; g.drawImage(buffImage, 0, 0, this); } catch (Exception e) { e.printStackTrace(); } } /** Handle the key typed event from the text field. */ public void keyTyped(KeyEvent e) { } /** Handle the key pressed event from the text field. */ public void keyPressed(KeyEvent e) { String s; offscreen.setColor(owner.fore); offscreen.setFont(fn); for (int i = counter; i < counter + 25; ++i) { s = Integer.toString(i); offscreen.drawString(s, 3, i * chh); offscreen.drawLine(10, i * chh, 160, i * chh); } //owner.s.setScrollPosition(0, counter * 16); counter = counter + 25; repaint(); } /** Handle the key released event from the text field. */ public void keyReleased(KeyEvent e) { } public boolean keyDown(Event e, int k) { String s; offscreen.setColor(owner.fore); offscreen.setFont(fn); for (int i = counter; i < counter + 25; ++i) { s = Integer.toString(i); offscreen.drawString(s, 3, i * chh); offscreen.drawLine(10, i * chh, 160, i * chh); } //owner.s.setScrollPosition(0, counter * 16); counter = counter + 25; repaint(); return true; } }
VIEWS ON THIS POST

184

Posted on:

Saturday 22nd September 2012
View Replies!

Trouble with JEditorPane changing colors with styles

I'm using Styles to change the color of my reserved words, but its changing incorrectly, its changing right when I type in the first line but in the next lines only part of the word is changed, what is wrong with my code\t the problem! Uploaded with ImageShack.us this is the code -> public void doFindText(String find) { SimpleAttributeSet bluAttr = new SimpleAttributeSet(); StyleConstants.setForeground(bluAttr, Color.BLUE); SimpleAttributeSet GreenAttr = new SimpleAttributeSet(); StyleConstants.setForeground(GreenAttr, Color.GREEN); int nextPosn = 0; if (!find.equals(findText) ) // *** new find word findPosn = 0; // *** start from top nextPosn = nextIndex( Ed_Prog.getText(), find, findPosn, false); if ( nextPosn >= 0 ) { //Ed_Prog.setSelectionStart( nextPosn-1 ); // position cursor at word start //Ed_Prog.setSelectionEnd( nextPosn + find.length() ); if(find.equalsIgnoreCase("programa")){ Ed_Prog.getStyledDocument().setCharacterAttributes(nextPosn,nextPosn + find.length()+1, bluAttr, false); }else if(find.equalsIgnoreCase("string")){ Ed_Prog.getStyledDocument().setCharacterAttributes(nextPosn-1,nextPosn + find.length()+1, GreenAttr, false); } else if(find.equalsIgnoreCase("inteiro")){ Ed_Prog.getStyledDocument().setCharacterAttributes(nextPosn-1,nextPosn + find.length()+1, GreenAttr, false); } else if(find.equalsIgnoreCase("real")){ Ed_Prog.getStyledDocument().setCharacterAttributes(nextPosn-1,nextPosn + find.length()+1, GreenAttr, false); } findPosn = nextPosn + find.length()+1; // reset for next //search findText = find; // save word & case nextPosn = 0; } else { findPosn = nextPosn; // set to -1 if not found //JOptionPane.showMessageDialog(this, find + " not Found!" ); } }
VIEWS ON THIS POST

206

Posted on:

Saturday 22nd September 2012
View Replies!

Trying to get a square change color on button click

EDIT: Obviously a beginners question! Probably in the wrong forum, please feel free to move mods! Apologies! I thought I'd help myself understanding the GUI and ActionListener proces a bit better by sussing out how to do something simple like putting a button and a rectangle on a screen and then having it change color from blue to red on buttonclick. Appears I've ended up in a swamp and everytime I move I get sucked farther in. I soon found out I have no clue how to easily change the color of something when clicking a button so I thought I'd fake it first by simply running a different color panel on mouseclick. And that failed miserably too! Trying to use the boolean swoosh in two different classes is not the way to go. So a little help, hint or push in the right direction would be greatly appreciated! import javax.swing.*; import java.awt.*; import java.awt.event.*; public class KnopOefen implements ActionListener { JFrame frame; public static void main(String[] args) { boolean swoosh = true; KnopOefen knop = new KnopOefen(); knop.go(); } public void go() { frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton button = new JButton("Click to make the square red!"); button.addActionListener(this); Rectangle recty = new Rectangle(); frame.getContentPane().add(BorderLayout.SOUTH, button); frame.getContentPane().add(BorderLayout.CENTER, recty); frame.setSize(300,300); frame.setVisible(true); } public void actionPerformed(ActionEvent event) { boolean swoosh = false; KnopOefen knip = new KnopOefen(); knip.go(); } }
VIEWS ON THIS POST

199

Posted on:

Wednesday 26th September 2012
View Replies!

background and foreground color is not changing in full screen window

why my background and foreground color is not changing\t import java.awt.*; import javax.swing.*; public class mainScreen extends JFrame{ public static void main(String args[]) { DisplayMode dm = new DisplayMode(800, 600, 16, DisplayMode.REFRESH_RATE_UNKNOWN); mainScreen ms = new mainScreen(); ms.run(dm); } public void run(DisplayMode dm) { setBackground(Color.PINK); setForeground(Color.GRAY); setFont(new Font("Arial", Font.PLAIN, 24)); Screen s = new Screen(); try{ s.setFullScreen(dm, this); try{ Thread.sleep(5000); }catch(Exception e){} }finally{ s.restoreScreen(); } } public void paint(Graphics g) { g.drawString("This is FullScreen", 200, 200); } }
VIEWS ON THIS POST

117

Posted on:

Wednesday 26th September 2012
View Replies!

JCheckboxMenuItem won't change selection color

guy, Am I doing something wrong or what I want to change the color for the selection background of the JCheckboxMenuItem and it doesn't change at all. This is what I have, what am i doing wrong UIManager.put( "CheckBoxMenuItem.acceleratorForeground", Crawler.color_black); UIManager.put( "CheckBoxMenuItem.acceleratorSelectionForeground", Crawler.color_black); UIManager.put( "CheckBoxMenuItem.background", Crawler.color_white); UIManager.put( "CheckBoxMenuItem.border",BorderFactory.createLineBorder(Crawler.color_white, 1)); UIManager.put( "CheckBoxMenuItem.disabledBackground", Crawler.color_white); UIManager.put( "CheckBoxMenuItem.disabledForeground", Crawler.color_white); UIManager.put( "CheckBoxMenuItem.foreground", Crawler.color_black); UIManager.put( "CheckBoxMenuItem.selectionBackground", Crawler.color_blue); UIManager.put( "CheckBoxMenuItem.selectionForeground", Crawler.color_black);
VIEWS ON THIS POST

103

Posted on:

Wednesday 26th September 2012
View Replies!

Substitute one color with another on an image

Hi! I need to substitute one color with white on an image. I've read about IndexColorMmodel, ColorModel and RGBImageFilter, but I don't understand how they work. The color I want to substitute is: R: 113 G: 75 B: 96 And of course, white is 255,255,255. I've read several examples, but can't grasp all the concepts. I'm new working with images. How can I do it
VIEWS ON THIS POST

90

Posted on:

Thursday 27th September 2012
View Replies!

can't see the background color of a frame , why?

today in college i was trying to set the background color of a jframe but it only shows the color when i resize the frame and not when i just select the radio button but if i set the background color of a panel instead frame it works fine can you explain me why we cant see the background color of a frame /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javachallenge; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; /** * * @author Admin */ public class JavaChallenge extends JFrame implements ActionListener{ /** * @param args the command line arguments */ JRadioButton green,red; JPanel panel; void foo() { panel = new JPanel(); ButtonGroup btngroup = new ButtonGroup(); red = new JRadioButton("Red"); btngroup.add(red); green = new JRadioButton("Green"); btngroup.add(green); panel.add(red); panel.add(green); add(panel,BorderLayout.SOUTH); pack(); red.addActionListener(this); green.addActionListener(this); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { // TODO code application logic here new JavaChallenge().foo(); } @Override public void actionPerformed(ActionEvent e) { if(red.isSelected()) { setBackground(Color.RED); setExtendedState(JFrame.MAXIMIZED_BOTH); // panel.updateUI(); }else { setBackground(Color.GREEN); setExtendedState(JFrame.MAXIMIZED_BOTH); //panel.updateUI(); } } }
VIEWS ON THIS POST

186

Posted on:

Saturday 29th September 2012
View Replies!

Color Some particular rows in JTable

Hi need help I have a table and i have to implement a search functionality in that table for that i have created search button and performed search operation. Now i want that all rows who are having search values must change their color please help me with that problem example is here------ import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class TableRow implements ActionListener{ JTable table; public static void main(String[] args) { new TableRow(); } public TableRow(){ JFrame frame = new JFrame("Creating Table Component Example!"); JPanel panel = new JPanel(); JButton search=new JButton("Search"); String data[][] = {{"vinod","BCA","A"},{"Raju","MCA","b"}, {"Ranjan","MBA","c"},{"Rinku","BCA","d"}}; String col[] = {"Name","Course","Grade"}; table = new JTable(data,col); panel.add(table,BorderLayout.CENTER); panel.add(search); frame.add(panel); frame.setSize(300,200); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); search.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String s=JOptionPane.showInputDialog(null,"Please Enter the value to search"); int i=0,j=0; while(i
VIEWS ON THIS POST

70

Posted on:

Sunday 30th September 2012
View Replies!

how to use rgb color values to set JPanel background color

how to use RGB values to set JPanel Background color, which is not in the color list... i tried like this but not working for me.. int red = 100; int green = 100; int blue = 150; Color myBlue = new Color(red,green,blue); panel.setBackground(Color.myBlue);
VIEWS ON THIS POST

228

Posted on:

Monday 1st October 2012
View Replies!

change text area background color at run time.

I have text area which is initially disabled on a button click i am enabling it and I am trying to change background color at run time but its not working. Can any body help me I am doing the below: notesJTextArea.setEditable(editable); Color color = Color.white; notesJTextArea.setBackground(color);
VIEWS ON THIS POST

191

Posted on:

Monday 1st October 2012
View Replies!

Positioning slider relative to word in JtextPane.

I am hoping to get some advice on a problem I am trying to tackle. In my application, I have a single line textpane inside a scrollpane. The user will input some text (that could be longer than the length of the textpane - hence the scrollpane!). What I eventually want to achieve is that if the user clicks on any of the words in the text, I would like to have a slider popup right next to the word. So essentially, I need to find the exact position of the word and put the slider there. Please give me some tips to achieve this.
VIEWS ON THIS POST

146

Posted on:

Tuesday 2nd October 2012
View Replies!

how to turn off the word wrap in jeditorpane?

my jeditorpane automatically wrap the words ..i dont want that , all i want is a horizontal bar to appear and user can write as long as he can how to do that i have tried couple of methods like i have override the getScrollableTracksViewportWidth() but that didnt help , does any one know how i can turn off the word wrap
VIEWS ON THIS POST

103

Posted on:

Tuesday 2nd October 2012
View Replies!

Problem in passing color as a parameter

, below code is for bounce multiple balls, my code is working correctly, but when i m trying to add Color also as a parameter, it not changing the color of the balls, code is: Point.java import java.applet.*; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; public class Point extends Applet implements Runnable{ private Image i; private Graphics doubleG; Cfish f,f1,f2; public void init() { setSize(800,600); } public void start() { f = new Cfish(); f1 = new Cfish(250,250); f2 = new Cfish(350,350); Thread thread = new Thread(this);//if this confuses run method can also be done here... thread.start(); } public void run() { while(true) { f.update(this); f1.update(this); f2.update(this); repaint(); try { Thread.sleep(17); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void update(Graphics g) { if(i == null) { i = createImage(this.getSize().width, this.getSize().height); doubleG = i.getGraphics(); } doubleG.setColor(getBackground()); doubleG.fillRect(0, 0,this.getSize().width, this.getSize().height); doubleG.setColor(getForeground()); paint(doubleG); g.drawImage(i, 0, 0, this); } public void paint(Graphics g) { f.display(g); f1.display(g); f2.display(g); } }
VIEWS ON THIS POST

71

Posted on:

Wednesday 3rd October 2012
View Replies!

background color is not changing?

hello i m having some problem in the below code, my background color is not going to change to green, can anyone tell me why and also how can i set an image as my background here package game; import java.awt.*; import javax.swing.JFrame; public class gameMain extends JFrame { public static void main(String[] arg) { DisplayMode dm = new DisplayMode(800,600,16, DisplayMode.REFRESH_RATE_UNKNOWN); gameMain b = new gameMain(); b.run(dm); } public void run(DisplayMode dm) { setBackground(Color.GREEN); setForeground(Color.BLUE); setFont(new Font("Arial", Font.PLAIN, 24)); screen s = new screen(); try{ s.setFullScreen(dm, this); try{ Thread.sleep(5000); }catch(Exception ex){} }finally{ s.restoreScreen(); } } public void paint(Graphics g){ if(g instanceof Graphics2D){ Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } g.drawString(" it's me punit.", 200, 200); } }
VIEWS ON THIS POST

91

Posted on:

Wednesday 3rd October 2012
View Replies!

converting a string color to an object color

Would any one please shed a light. how to convert a String like: String colorStr = "Red"; to an Object Color.red
VIEWS ON THIS POST

130

Posted on:

Wednesday 3rd October 2012
View Replies!