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!" ); } }
Posted On: Saturday 22nd of September 2012 05:37:44 AM Total Views:  206
View Complete with Replies

RELATED TOPICS OF Swing / AWT / SWT PROGRAMMING LANGUAGE




Any Key Press with KeyListener

Hi , I need a bit of help with this one. What I want to do is report when key has pressed. The issue is that do have I have to specify all possible keys individually or is there a method or some code that allows me to do this. I have a method that needs to send back a string to the user.
VIEWS ON THIS POST

175

Posted on:

Friday 21st September 2012
View Replies!

Problem with Jable with ResultSet

Everybody: im new in this forum and this is my first thread, i hope you can help me, i have a problem with JTable and ResultSetScrollable, the question is that i have a JTable with AbstractTableModel, in the class AbstractTableModel, i override the three methods, getvalueat, getcolumnname....also i have a ComboBox, when i select a value of the ComboBox, the JTable shows the data associated with the ComboBox. Well, the problem is that JTable only shows INTEGER data, but String not, i dont know why this could be. if someone knows anything about this, would be very grateful. this is a part of the code: **********This is the AbstractTableModel***************************************** public class PersonalTableModel extends AbstractTableModel{ ResultSet rs; public PersonalTableModel(ResultSet rs) { this.rs=rs; } public Object getValueAt(int ri, int ci) { Object ob=null; try{ rs.absolute(ri+1); ob=rs.getObject(ci+1); }catch(Exception e){ e.printStackTrace(); } return ob; }
VIEWS ON THIS POST

158

Posted on:

Friday 21st September 2012
View Replies!

Working with the Hebrew alphabet in JTextArea

On a Mac OSX system the application takes input from a file, keyboard, or from pasting into a JTextArea. The input is processed from the characters of the JTextArea's javax.swing.text.Document. works fine until Hebrew characters are entered (0590-05ff in Unicode). Pasting of Unicode Hebrew (from Firefox) looks correct, but the characters of the document are only single bytes, 0x3F, when taken from the document. When the JTextArea is filled from an input file, via a CharacterStream, the Hebrew characters are replaced by nonsense. A Hebrew keyboard typing into the JTextArea produces a correct appearance, but the results returned from the Document are still short, 8 bit. I've read somewhere that some AWT components aren't really Unicode compatible, but that Swing components are. Would you please point me towards a solution
VIEWS ON THIS POST

123

Posted on:

Friday 21st September 2012
View Replies!

Help me with alignment. GridBagLayout

hi. i want to align heading to the top centre and i want to align rest of my fields and labels to the left after heading. i have tried alot but cant do it. i want to do it like this public class Main { public static void main(String[] args) { Entry test = new Entry(); } } -------------------------- import java.awt.*; import javax.swing.*; public class Objects { JLabel top; // TextInput Fields JTextField SerialNo; JTextField RecDate; JTextField GatePassNo; JTextField BoxNo; public GridBagConstraints gbc = new GridBagConstraints(); public JPanel EntryPanel = new JPanel(new GridBagLayout()); JPanel HeadingPanel= new JPanel(); Objects() { top = new JLabel("Text1"); BoxNo = new JTextField(10); SerialNo = new JTextField(10); } } -------------------------- import java.awt.*; import javax.swing.*; public class Entry extends Objects{ public Entry() { JFrame entry= new JFrame("Text1"); entry.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); entry.setLocationRelativeTo(null); entry.setVisible(true); top.setFont(new Font("Serif",Font.BOLD,30)); entry.getContentPane().add(HeadingPanel,BorderLayout.PAGE_START); HeadingPanel.add(top); entry.getContentPane().add(EntryPanel,BorderLayout.WEST); gbc.gridx = 1; gbc.gridy=5; EntryPanel.add(BoxNo); entry.setSize(600,600); } }
VIEWS ON THIS POST

168

Posted on:

Friday 21st September 2012
View Replies!

Question about drop down lists from JComboBox within an applet

When I click on the down arrow of a standard JComboBox in an applet and the list of strings are displayed, if I then drag the browser window, the drop down list stays in the same place instead of either being closed or moving with the browser window. I started noticing this when I started using Java 7, but I think this also occurs with Java 6 and 5. When run within the applet viewer in Eclipse, moving the applet window there closes the drop-down during the process of moving the window. Anybody else noticing this If so are any suggestions for a possible solution. Ideally I'd want the list to move with the browser window without the drop-down closing. My example code that demonstrates the problem is as follows: import javax.swing.JApplet; import javax.swing.JComboBox; public class ComboApplet extends JApplet { public void init () { String [] testStrings = new String [] {"This", "is", "a", "test"}; JComboBox comboBox = new JComboBox(testStrings); add(comboBox); } }
VIEWS ON THIS POST

233

Posted on:

Friday 21st September 2012
View Replies!

How to make a JFrame transparent with solid border

Hi , I am wondering how to make the content pane of a JFrame transparent, but not its border. The border is still opaque and solid. Does anyone have ideas
VIEWS ON THIS POST

250

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!

How to disable a JButton without it turning gray.

, I'm writing a tic tac toe game, and have colored X and 0 icons which should appear on JButtons when the empty button is clicked. At the moment, I'm using setEnabled(false) to stop a player being able to click a square on the board that has already been used. But that makes the colored X and 0 icons gray. Is there a way to stop this happening
VIEWS ON THIS POST

181

Posted on:

Saturday 22nd September 2012
View Replies!

Synchronizing JTable with a non Observable in Netbeans

Hi all, I've been using netbeans to build a database application and it all seems to be working perfectly apart from 1 issue I'm experiencing. I have a JTable which is bound to a List of an entity class inside an entity class. The JTable itself isn't editable, but when you select a row from the list, I pass the object inside the List to a JDialog, where each field is bound to the entity objects attributes. The changes when being made are immediately reflected in the JTable. However if I cancel the database transaction, the database rollsback the transaction. However the JTable remains updated and out of synchronization with the database. Does anyone know any way around this Here is the code I am using to save / refresh the database @Action(enabledProperty = "recordSelected") public void editClub() { if (!entityManager.getTransaction().isActive()) { entityManager.getTransaction().begin(); } ClubEditor ce = new ClubEditor(this,true); ce.setCurrentClub(getCurrentLeague().getClubList().get(leagueTable.convertRowIndexToModel(leagueTable.getSelectedRow()))); ce.setVisible(true); if(ce.isClubConfirmed()) { save(); } else { refresh(); } } private void save() { try { entityManager.getTransaction().commit(); entityManager.getTransaction().begin(); } catch (RollbackException rex) { rex.printStackTrace(); entityManager.getTransaction().begin(); List merged = new ArrayList(currentLeagueList.size()); for (League l : currentLeagueList) { merged.add(entityManager.merge(l)); } currentLeagueList.clear(); currentLeagueList.add(merged); } } private void refresh() { entityManager.getTransaction().rollback(); entityManager.getTransaction().begin(); Collection data = currentLeagueQuery.getResultList(); for (Object entity : data) { entityManager.refresh(entity); } currentLeagueList.clear(); currentLeagueList.add(data); }
VIEWS ON THIS POST

189

Posted on:

Saturday 22nd September 2012
View Replies!

Problem with calculator

all! This is my first post on this forum I've got problem with making my calculator... Here is the code: GUI: import javax.swing.*; import java.awt.*; public class Calculator { JPanel windowContent; JTextField displayField; JButton button0; JButton button1; JButton button2; JButton button3; JButton button4; JButton button5; JButton button6; JButton button7; JButton button8; JButton button9; JButton buttonPlus; JButton buttonMinus; JButton buttonPuta; JButton buttonPodijeljeno; JButton buttonTocka; JButton buttonJednako; JButton buttonPrazan1; JButton buttonPrazan2; JButton buttonPrazan3; JButton buttonC; JPanel p1; public void setDisplayValue(String val){ displayField.setText(val); } public String getDisplayValue() { return displayField.getText(); } Calculator(){ windowContent= new JPanel(); BorderLayout b1= new BorderLayout(); windowContent.setLayout(b1); displayField= new JTextField(30); windowContent.add("North",displayField); button0=new JButton("0"); button1=new JButton("1"); button2=new JButton("2"); button3=new JButton("3"); button4=new JButton("4"); button5=new JButton("5"); button6=new JButton("6"); button7=new JButton("7"); button8=new JButton("8"); button9=new JButton("9"); buttonPlus=new JButton("+"); buttonMinus=new JButton("-"); buttonPuta=new JButton("x"); buttonPodijeljeno=new JButton("/"); buttonTocka= new JButton("."); buttonJednako=new JButton("="); buttonPrazan1=new JButton(""); buttonPrazan2=new JButton(""); buttonPrazan3=new JButton(""); buttonC=new JButton("C"); p1 = new JPanel(); GridLayout gl= new GridLayout(5,3); p1.setLayout(gl); p1.add(button0); p1.add(button1); p1.add(button2); p1.add(buttonPlus); p1.add(button3); p1.add(button4); p1.add(button5); p1.add(buttonMinus); p1.add(button6); p1.add(button7); p1.add(button8); p1.add(buttonPuta); p1.add(button9); p1.add(buttonTocka); p1.add(buttonJednako); p1.add(buttonPodijeljeno); p1.add(buttonPrazan1); p1.add(buttonPrazan2); p1.add(buttonPrazan3); p1.add(buttonC); CalculatorEngine calcEngine = new CalculatorEngine(this); button0.addActionListener(calcEngine); button1.addActionListener(calcEngine); button2.addActionListener(calcEngine); button3.addActionListener(calcEngine); button4.addActionListener(calcEngine); button5.addActionListener(calcEngine); button6.addActionListener(calcEngine); button7.addActionListener(calcEngine); button8.addActionListener(calcEngine); button9.addActionListener(calcEngine); buttonPlus.addActionListener(calcEngine); buttonMinus.addActionListener(calcEngine); buttonPuta.addActionListener(calcEngine); buttonPodijeljeno.addActionListener(calcEngine); buttonJednako.addActionListener(calcEngine); buttonTocka.addActionListener(calcEngine); buttonC.addActionListener(calcEngine); windowContent.add("Center", p1); JFrame frame = new JFrame("inditron"); frame.setContentPane(windowContent); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { new Calculator(); } }
VIEWS ON THIS POST

151

Posted on:

Saturday 22nd September 2012
View Replies!

Add Row with AbstractTableModel

I have searched this site for how to add and remove ROWS from a JTable using a AbstractTableModel, but every response replies with "Use DefaultTableModel". I have also searched On google for an example or some sort, but have come up empty handed. Does anyone know how to do this What I want is to basically add an Empty Row that I can type the data directly into the JTable. I do not want to prompt the user for the data first. here is my code so far public class ManageCommonProblemFrame extends JInternalFrame { JPanel mainPanel; JTabletheTable; JScrollPanelistScroll; JTextFieldnameField; JTextAreaproblemArea; JTextAreafixArea; JScrollPaneproblemScroll; JScrollPanefixScroll; MyTableModel model; public ManageCommonProblemFrame() { super("Common Problems", true, true, true, true); mainPanel = new JPanel(); setContentPane(mainPanel); mainPanel.setLayout(null); model = new MyTableModel(); theTable = new JTable(model); listScroll = new JScrollPane(theTable); listScroll.setBounds(5, 5, 150, 200); mainPanel.add(listScroll); JButton addButton = new JButton("Add Name"); addButton.setBounds(160, 6, 100, 20); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //Don't know what to do here. }}); mainPanel.add(addButton); } private void getInitialData() { } class MyTableModel extends AbstractTableModel { final String[] columnNames = {"Name"}; final Object[][] data = { {"Mary"}, {"Alison"}}; public int getColumnCount() { return columnNames.length; } public int getRowCount() { return data.length; } public String getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { return data[row][col]; } /* * Don't need to implement this method unless your table's * editable. */ public boolean isCellEditable(int row, int col) { //Note that the data/cell address is constant, //no matter where the cell appears onscreen. return true; } public void setValueAt(Object value, int row, int col) { System.out.println("Setting value at " + row + "," + col + " to " + value + " (an instance of " + value.getClass() + ")"); data[row][col] = value; fireTableCellUpdated(row, col); System.out.println("New value of data:"); } public void addRow(int row, int col) { //Don't know what to do here this.fireTableRowsInserted(row, col); } public void delRow(int row, int col) { //Don't know what to do here this.fireTableRowsDeleted(row, col); } } }
VIEWS ON THIS POST

127

Posted on:

Saturday 22nd September 2012
View Replies!

problem with JTextField null

, i've a problem when i try to return the object "JTextField" because this is empty (null) and i don't know wich is the structure to use. In my method i use a Queue but this structure can't contains null objects. Please HELP. public static JTextField checkJTextField(JPanel panel) { int i = 0; Boolean flag = true; Queue queue = null; JTextField objectReturned; java.awt.Component[] component = panel.getComponents(); try { while (i < component.length && flag) { if (component[i] instanceof JTextField) { if (((JTextField) component[i]).getText().equals("")) { queue.offer((JTextField) component[i]); flag = false; } } else if (component[i] instanceof JPanel) { queue.offer(WindowsMethods.checkJTextField((JPanel) component[i])); } i++; } } catch (NullPointerException NPE) { System.out.println("Error."); } objectReturned = (JTextField) queue.peek(); return objectReturned; }
VIEWS ON THIS POST

269

Posted on:

Saturday 22nd September 2012
View Replies!

Jcheckbox array with various Listener!

I get base source code in this. I change it as bellow import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.AbstractButton; import javax.swing.ButtonModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class SelectingCheckBox { static int number = 0; static AbstractButton abstractButton; static int numberCheckboxes = 4; static boolean selected; static ButtonModel buttonModel; static boolean armed; public static void main(String args[]) { JFrame frame = new JFrame("Selecting CheckBox"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { abstractButton = (AbstractButton) actionEvent.getSource(); selected = abstractButton.getModel().isSelected(); }}; ChangeListener changeListener = new ChangeListener() { public void stateChanged(ChangeEvent changeEvent) { abstractButton = (AbstractButton) changeEvent.getSource(); buttonModel = abstractButton.getModel(); }}; ItemListener itemListener = new ItemListener() { public void itemStateChanged(ItemEvent itemEvent) { abstractButton = (AbstractButton) itemEvent.getSource(); selected = abstractButton.getModel().isSelected(); int state = itemEvent.getStateChange(); abstractButton.setName(Integer.toString(number)); if (state == ItemEvent.SELECTED) { number = number + 1; abstractButton.setName(Integer.toString(number)); for (int i = 0; i < numberCheckboxes; i++) { if (Integer.parseInt(abstractButton.getName()) != i) { abstractButton.setEnabled(false); } else { abstractButton.setEnabled(true); System.out.println("abstractButton.getName() ="+ abstractButton.getName()); }}} else { number = number - 1; }}}; Container contentPane = frame.getContentPane(); frame.getContentPane().setLayout(null); JCheckBox[] checkBoxes = new JCheckBox[numberCheckboxes]; for (int i = 0; i < numberCheckboxes; i++) { checkBoxes[i] = new JCheckBox(); checkBoxes[i].setText("checkbox " + (i + 1)); checkBoxes[i].setBounds(5, (i + 2) * 25, 100, 30); checkBoxes[i].setSize(100, 30); checkBoxes[i].addActionListener(actionListener); checkBoxes[i].addChangeListener(changeListener); checkBoxes[i].addItemListener(itemListener); contentPane.add(checkBoxes[i]); } JButton btnOk = new JButton("OK"); btnOk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println(number); }}); btnOk.setBounds(343, 232, 89, 23); frame.getContentPane().add(btnOk); frame.setSize(450, 300); frame.setBounds(100, 100, 450, 300); frame.setVisible(true); }}
VIEWS ON THIS POST

266

Posted on:

Saturday 22nd September 2012
View Replies!

Is there a way to paint swing components without subclassing?

For instance, I could have the class public class JPanelSubClass extends javax.swing.JPanel { protected void paintComponent(java.awt.Graphics g) { super.paintComponent(g); g.drawLine(0, 0, 100, 0); g.drawLine(0, 0, 0, 100); g.drawLine(100, 0, 100, 100); g.drawLine(0, 100, 100, 100); } }
VIEWS ON THIS POST

210

Posted on:

Saturday 22nd September 2012
View Replies!

Keeping JTextField constrained within the frame

I have added a JLabel and JTextField to a JPanel which then goes in a JFrame. I have to use GridBagLayout to constraint all these and the other components. I am allowing the JTextField to fill in Horizontally gbc.fill = GridBagConstraints.HORIZONTAL;
VIEWS ON THIS POST

190

Posted on:

Saturday 22nd September 2012
View Replies!

How do I add text to a scrollable JTextPane without scrolling the JScrollPane?

I am using a JTextPane within a JScrollPane to display more text than the area provides. The controls live on a custom JDialog box and everything is fully initialized in the dialog's constructor. The scroll bars work and allow me to scroll around and view all of the text, but the problem is that the scrollbar is initialized at the lowest position. In other words, when my dialog appears the text field is scrolled down and displays the bottom of the block of text instead of the top. The first thing I tried to do was set the vertical scrollbar's value to 0 after setting up the dialog, but the request is ignored. I thought this might be the result of the dialog being resized with "pack()" so I called this after pack() and it is still ignored. As far as I can tell something happens after the dialog's constructor that changes this setting and wipes out mind, but I don't know what it is. // This is the code I call to move the scrollbar: scrollPane.getVerticalScrollBar().setValue(0);
VIEWS ON THIS POST

172

Posted on:

Saturday 22nd September 2012
View Replies!

File Menu with recently opened files menu items

Does anyone have an example of this, where when you click on the file menu, recently used files are displayed
VIEWS ON THIS POST

219

Posted on:

Saturday 22nd September 2012
View Replies!

Having some problem with FileDialog

Hi , I wrote a porgam where there is a textarea and two buttons ,one to load files into the textarea and other button to save what is written in the text area. I have two problems though 1)The methods filedialog.getDirectory(),filedialog.getFile() return nulll so i am not able to load any file in the text area 2)When i try to save a file ,i used filedialog.setDirectory("C:"+"\" ") and filedialog.setFile("untitled.txt").The problem is it doesnt show the c:\ as the default directory when the dialog box opens . import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class button3 { public static void main(String[]args) { test t=new test(); t.go(); } } class test {JFrame frame =new JFrame(); JTextArea area=new JTextArea(10,20); void go() { JButton button1=new JButton("open"); JButton button2=new JButton("save"); JScrollPane scroller=new JScrollPane(area); scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); frame.setVisible(true); frame.setSize(500, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new FlowLayout()); button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { FileDialog filedialog=new FileDialog(new Frame(),"Load",FileDialog.LOAD); String name=filedialog.getDirectory()+filedialog.getFile(); try { System.out.println(name); BufferedReader myreader=new BufferedReader(new FileReader(name)); try { while(myreader.readLine()!=null) { area.setText(myreader.readLine()); } } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } filedialog.setTitle("Load & Save"); filedialog.setVisible(true); } } ); button2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { FileDialog filedialog=new FileDialog(new Frame(),"Save",FileDialog.SAVE); filedialog.setDirectory("C:"+"\" "); filedialog.setFile("untitled.txt"); try { BufferedWriter mywriter=new BufferedWriter(new FileWriter("untitled.txt")); mywriter.write(area.getText()); mywriter.flush(); mywriter.close(); } catch (IOException e) { e.printStackTrace(); } filedialog.setTitle("Load & Save"); filedialog.setVisible(true); } } ); frame.add(button1); frame.add(button2); frame.add(scroller); } }
VIEWS ON THIS POST

289

Posted on:

Saturday 22nd September 2012
View Replies!

Checking whether the date entered within textfield does comply with the format given

have a text field, named "datedtext", which accepts date from user. The property associated with date is of Date datatype in my entity class. What i want is that when the user enters the date and press enter, it should check whether it complies to format given. Here is what i tried public void keyPressed(KeyEvent e) { if(e.getSource()==datedtext){ if(e.getKeyCode()==KeyEvent.VK_ENTER){ String s1 = datedtext.getText(); //gets me the date, but its a string datatype. // here is the problem. I should check whether its a "dd-MMM-yyyy" format, and if yes, i need to convert it into date object and insert into db } } }
VIEWS ON THIS POST

172

Posted on:

Saturday 22nd September 2012
View Replies!

Doubt in a program that deals with paintComponent

I basically copied a program from a book and ran it .In the porgram a circle moves from one position to the other slowly .I have a doubt as to how the program is running ,I dont understand how or where the method paintComponent is being called in the program. import javax.swing.*; import java.awt.*; public class SimpleAnimation { int x=70; int y=70; public static void main(String[]args) { SimpleAnimation gui=new SimpleAnimation(); gui.go(); } public void go(){ JFrame frame=new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); MyDrawPanel drawpanel=new MyDrawPanel(); frame.getContentPane().add(drawpanel); frame.setSize(500,500); frame.setVisible(true); for(int i=0;i
VIEWS ON THIS POST

227

Posted on:

Saturday 22nd September 2012
View Replies!