JTextArea line numbers of menu item - java

I am trying to develop a project using AWT And SWING concepts of Java.
In that I have an one menu item called "Viewline Numbers (i.e. we have chosen a JCheckBox for that)". When I check the Check-box it is displaying line numbers in another Document. But, I want to display the line numbers in same using Document like as Editplus Editor.
Here is my code
private void ViewLineNumbersActionPerformed(java.awt.event.ActionEvent evt) {
lines = new JTextArea("");
lines.setBackground(Color.LIGHT_GRAY);
lines.setEditable(false);
lines.setSize(10,10);
tx.getDocument().addDocumentListener(new DocumentListener(){
public String getText(){
int caretPosition = tx.getDocument().getLength();
// System.out.println("caretPosition"+ caretPosition);
Element root = tx.getDocument().getDefaultRootElement();
// System.out.println("root"+ root);
String text = "1" + System.getProperty("line.separator");
int c=root.getElementIndex( caretPosition );
// System.out.println(c);
for(int i = 2; i < c + 2; i++){
text += i + System.getProperty("line.separator");
}
return text;
}
#Override
public void `enter code here`changedUpdate(DocumentEvent de) {
lines.setText(getText());
}
#Override
public void insertUpdate(DocumentEvent de) {
lines.setText(getText());
}
#Override
public void removeUpdate(DocumentEvent de) {
lines.setText(getText());
}
});
sp.getViewport().add(tx);
// sp.setViewportView(tx);
sp.setRowHeaderView(lines);
}

But, I want to display the line numbers in same using Document like as Editplus Editor.
I doubt very much that the line numbers are part of the Document. They may appear to be displayed as part of the same component, but I'm sure that when you copy/paste text you don't get the line numbers included.
Assuming my above statement is correct you can try using the Text Component Line Number. Since this a component displayed in the row header of the scroll pane you should be able to toggle the visibility of the component based on your checkbox.

Related

Java Listener for looped combo in Eclipse SWT

I have a Java SWT GUI that I've built using Eclipse. I'm using a while loop to reference a text file. The while loop iterates through each line of the text file and builds a series of combo or text boxes for specific items on each line. Each line represents one visual column in the GUI and, depending on how many items I have in the text file, the GUI builds to the right. For simplicity's sake I am including just the code that I am trying to figure out.
For instance, assume I have three lines that create six combo boxes in the GUI (three columns by two rows). I would like a change on the top row in the second column to execute a Listener on the bottom row, also in the second column. However, right now the Listener loops through all of the combo's and makes a change to all three, not just the one I want. I can't figure out how to make this work. See the code below. I appreciate the help.
private void buildMultipleSatPulldowns() {
try {
FileReader fr = new FileReader("MultipleSatellites.txt");
BufferedReader br = new BufferedReader(fr);
String line = null;
String[] tempS;
String constellation = null;
String satellite = null;
while ((line = br.readLine()) != null) {
tempS = line.split("~");
constellation = tempS[4];
satellite = tempS[6];
constNameCombo = new Combo(satellitesComposite2, SWT.NONE);
constNameCombo.setToolTipText("Pulldown constellation name");
constNameCombo.setBounds(startX + x2, 71, 125, 28);
constNameCombo.setItems(constNameArray);
constNameCombo.setText(constellation);
constNameCombos.add(constNameCombo);
constNameCombo.addModifyListener(new ModifyListener() { // captures changed combo values
public void modifyText(ModifyEvent arg0) {
setConstellationPD();
}
});
sPullDown(constellation); // builds the satellite array for the constellation and populates each pulldown
satNameCombo = new Combo(satellitesComposite2, SWT.NONE);
satNameCombo.setToolTipText("Pulldown satellite name");
satNameCombo.setBounds(startX + x2, 106, 125, 28);
satNameCombo.setItems(satNameArray);
satNameCombo.setText(satellite);
satNameCombos.add(satNameCombo);
startX = startX + nextX;
}
br.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void setConstellationPD() {
int constellations = 0;
for (Combo constNameCombo : constNameCombos) {
// What do I do here so that only the desired satNameCombo changes to reflect the desired pull down?
setSatellitesPD(constellations, constNameCombo)
constellations++;
}
}
private void setSatellitesPD(int c, String cN) {
int satellites = 0;
for (Combo satNameCombo : satNameCombos) {
if (c == satellites) {
satNameCombo.setText(satNameCombos.get(satellites).toString());
satNameCombo.removeAll();
sPullDown(cN);
satNameCombo.setText("select Satellite");
}
satellites++;
}
}
private void sPullDown(String cName) {
// sPullDown takes the constellation name and returns a String Array of all objects in the constellation. This code works correctly when called.
}
If I understood correctly, you need a way to know which combo fired the event in order to affect some other components.
SWT events like ModifyEvent have the method getSource() which will return the object on which the event occurred.
Having that you just need to properly identify it; for example you could simply use constNameCombos.indexOf(eventCombo) to retrieve its index.
Or, more efficiently, you could attach some data to your combos with the method setData and retrieve it inside the event with getData, for example inside the loop:
// "i" would be the index of the combo
constNameCombo.setData("index", i);
i++;
and in the event:
Combo eventCombo = (Combo) arg0.getSource();
int index = eventCombo.getData("index");
With these information you should be able to identify the other components that you want to change.

I am implementing focus listener to my suduku game but its not working

if user enter any alphabet in my suduku board it will not allow to go to other cells until he change that alphabet to digit.if he press tab also doesnot move .if he makes use of mouse also does not get into other cell until he changes that alphabet.also if alphabet enters a message want to display alphabets are not allowed.i my code the message displaying three time and repetdly .how to avoid this.i want to display message once untill user changes the alphabet and focus is on the current alphabet entered cell only.
Code:
private void setPuzzle(){
for(int row=0;row<size;row++){
for(int col=0;col<size;col++){
cell[row][col]=new JTextField(3);
cell[row][col].setHorizontalAlignment(JTextField.CENTER);
cell[row][col].addFocusListener(this);
panel.add(cell[row][col]);
}
}
}
#Override
public void focusGained(FocusEvent e) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void focusLost(FocusEvent e) {
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
String value=(cell[i][j].getText());
if(value.equals("")){
cell[i][j].setBackground(Color.WHITE);
}
else if (!value.matches("[1-9]+")){
cell[i][j].setBackground(Color.red);
cell[i][j].requestFocus();
JOptionPane.showMessageDialog(getParent(),"Alphabetsare not allowed");
}
}
}
}
}
In the else condition where your are validating the numbers, you are requesting focus and then showing the message box. So it will obviously will trigger the lostFocus event.
Try swapping the code as:
else if (!value.matches("[1-9]+"))
{
cell[i][j].setBackground(Color.red);
JOptionPane.showMessageDialog(getParent(),"Alphabetsare not allowed");
cell[i][j].requestFocus();
}
You can use e.getSource() to get the cell that triggered the focus event.
Do the check on this cell only, this way the message will be displayed only once even if there are other cells that don't contain a numerical value.
Also, to be able to get the text from the cell you will have to cast the object returned by e.getSource() to JTextField.
For exanple:
JTextField cell = (JTextField) e.getSource()
#Override
public void focusLost(FocusEvent e) {
JTextField cell = (JTextField) e.getSource();
String value = cell.getText();
if(!value.matches("\\d+") && value.length() > 0){
cell.setText("");
cell.setBackground(Color.red);
cell.requestFocus();
JOptionPane.showMessageDialog(getParent(),"Alphabetsare not allowed");
}else{
cell.setBackground(Color.WHITE);
}
}

How to find out line numbers of selected text?

Assume this very small program:
1. package ex1;
2. public interface Resizable {
3. void resize();
4. }
In my editor, if I select line 2-3 using mouse and say click on a button, I want to highlight these texts and also print, which line numbers were selected exactly for the button.
I can do the highlighting part, but I don't know how to find the line numbers of highlighted texts, As I think, I should use a listener, which will detect any changes in editor.
I think I should use an action listener, which will detect when the button is pressed after selecting text blocks. But how I will know, which lines are selected exactly?
The start and end of the highlight can be taken from the caret position dot and mark respectively. These are offsets in the Document. You must then calculate the number of newlines from the start of the document until the mark/do
textArea.addCaretListener(new CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
int startLine = getLine(e.getDot());
int endLine = getLine(e.getMark());
...
}
});
private int getLine(int offset) {
String text = textArea.getDocument().getText(0, offset);
int linenr = 0;
int idx = text.indexOf("\n");
while (idx != -1) {
linenr++;
idx = text.indexOf("\n", idx);
}
return linenr;
}

How to change Style of the next characters that will be typed in JTextPane

I have a problem, I am not able to change style for next characters that will be typed in JTextPane, so I don't want to change Style for whole JTextPane, but only for next characters.
For example if I use this:
tekst.getStyledDocument().setCharacterAttributes(0, tekst.getStyledDocument().getLength() + 1, at, false);
whole text is styled, but I don't want this to happen.
Can anyone tell me what to do.
I am trying to change style from my cursor position to future letters entered in JTextPane
tekst1.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
selektovaniTxt = tekst1.getSelectedText();
pozicija = tekst1.getCaretPosition();
System.out.println("Pozicija je: "+pozicija);
//some style
Style st1= tekst1.addStyle("default1", null);
StyleConstants.setFontSize(st1, new Integer(30));
StyleConstants.setFontFamily(st1, "Verdana");
tekst1.getStyledDocument().setCharacterAttributes(pozicija, tekst1.getStyledDocument().getLength()+1, tekst1.getStyle("default1"), true);
if(selektovaniTxt!=null){
//selektovan=true;
//tekst1.replaceSelection("");
}
}
});

JTextArea - Highlight Text While Scrolling Up or Down

I'm trying to work with a non-editable JTextArea added to a JScrollPane. I want a line to be highlighted when the user clicks on that specific line. I could implement this part using the following code:
public static void initHighlightOption(final JTextArea textArea){
textArea.setFont(new Font("Courier New", Font.PLAIN, 12));
textArea.setEditable(false);
final Action selectLine = getAction(textArea, DefaultEditorKit.selectLineAction);
textArea.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 1) {
selectLine.actionPerformed(null);
}
});
textArea.setSelectionStart(0);
textArea.setSelectionEnd(0);
}
public static Action getAction(JTextArea textArea, String name) {
Action action = null;
Action[] actions = textArea.getActions();
for (int i = 0; i < actions.length; i++) {
if (name.equals(actions[i].getValue(Action.NAME).toString())) {
action = actions[i];
break;
}
}
return action;
}
What I want to add is that once a line is highlighted and user scrolls up/down using keyboard up/down key, i want the current line to be highlighted. Is this possible by adding a keyListener? I'm stuck on how highlight data while scrolling up.
The text area contains data like this:
Line1
Line2
Line3
Line4
Line5
(i.e. there might be new lines between two particular lines of data)
What your asking for is not so easy to do. First off use a JTextPane instead of a JTextArea, it'll be much easier to handle. You will be need to get the Highlighter object from it
Highlighter hl = textPane.getHighlighter();
and you would probably have to keep track of your caret position each time the user scrolls with the arrow keys. When doing that you need to programatically change the highlights; something like:
Highlighter.Highlight myHighlight = null;
Highlighter.Highlight[] highlights = textPane.getHighlighter().getHighlights();
myHighlight = highlights[0]; //assuming there is one only
try {
hl.changeHighlight(myHighlight, myHighlight.getStartOffset()+1, myHighlight.getEndOffset());
}
catch(BadLocationException e) {
e.printStackTrace();
}
You can probably put this in your onKeyReleased() method. You kind of get the idea of what you're going to have to do. Read up on using JTextPane and Highlighter classes in the Java API docs, it will really help you alot.

Categories