how to fit text within jtextcomponent [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to develop an editor without scrollbars using jtextarea, so if the text is too long to fit within jtextarea it should be splitted into smaller substrings which could be edited within the jtextarea without showing vertical scrollbar because it is easy to get rid of horizontal one by using setLineWrap and setWrapStyleWord. I have tried to use vertical scrollbar adjusmentListener to listen to its changes but it doesnt work because jtextarea append and setText methods activated at the end of business logic, so I tried to use multithreaded and SwingWorker to invoke these methods but also doesnt work. I also tried to invoke repaint, revalidate and update methods with no hope. please help me to pass this issue and thanks in advance.

As Hovercraft Full Of Eels already suggested, you have to take a look at the Document, DocumentFilter and/or DocumentListener interfaces.
By adjusting those you have full control over what text is displayed when somebody wants to append text. You could for example remove the first part of the text before/after appending new text, hence limiting the number of lines/characters in the document.
The Swing tutorial about textcomponents contains such an example in the Implementing a DocumentFilter section, where the DocumentSizeFilter class is the one you are looking for (not part of the JDK, part of the Swing tutorial code). As already suggested as a comment in that sample code, it would be an option to remove the first part of the document when appending new text which would make the contents too long, but I leave that up to you since it is tagged as homework.

I am trying to develop an editor without scrollbars using jtextarea, so if the text is too long to fit within jtextarea it should be splitted into smaller substrings which could be edited within the jtextarea without showing vertical scrollbar because it is easy to get rid of horizontal one by using setLineWrap and setWrapStyleWord.
I'm not sure I fully understand this. Perhaps you can explain further? Why not place the JTextarea inside of a JScrollPane? What is your desired behavior if the text it contains is greater than that which the JTextArea can display?
I have tried to use vertical scrollbar adjusmentListener to listen to its changes but it doesnt work because jtextarea append and setText methods activated at the end of business logic, so I tried to use multithreaded and SwingWorker to invoke these methods but also doesnt work. I also tried to invoke repaint, revalidate and update methods with no hope.
If you want to trap entered text before it is committed to the text component, consider setting a DocumentFilter to the JTextArea's associated Document (a PlainDocument).

Thank you both Hovercraft and Robin I got it, your answers trend me to the correct way, I found the accurate answer at "Core Swing: advanced programming" book by using JTextArea.modelToView() passing the JTextArea Document Length as parameter this method returns a Rectangle object whose coordination represent the final character coordination and then compare these coordination with the bottom corner of the JTextArea to see if this final char reachs to this bottom or not.

Related

Notifying user in case of wrong input in JFrame in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm creating frame which asks user to enter his information. I want to notify user using labels or something else when he does not give required input. Like here is the screenshot when all fields are empty:
As when wrong input is entered and i move to the next text field text appears in red color below the text field. here is the screenshot:. i want to do this. Does anyone tell me how to do this..????
There are few ways to achieve this...
The first thing you need to do is valid the field...
You Could...
Use an InputVerifier which allows to validate a field when it loses focus as demonstrated here.
This method also allows you to determine if focus should be continue to the next field or remain with the current field.
You Could...
Use a FocusListener and valid the field when focus is lost. This is pretty much the same thing as the above suggestion, just know you have to do the work yourself
You Could...
Use a DocumentListener on text fields to monitor changes to the fields contents and perform real time validation of the field.
Next, you need to determine the best way to display the state...
You can use:
A LineBorder to change the field's border state. Be careful though, some look and feels won't like you doing this (looking at you MacOS). Take a look at How to use borders for more details
The tool tip API
setVisible to toggle the visibility of JLabels to display error messages, but to be honest, I might be tempted to use a full alpha color to hide the text and a full opaque color to show as this won't effect the layout
Ballon Tip
GridBagLayout would probably be my choice of layout manager, but you could also use compound layouts to make things eaiser

Custom swing JTextComponent [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want to create a JTextArea which looks like JTextArea, acts like JTextArea, responds like JTextArea, speaks like JTextArea, moves like JTextArea, etc, but is not JTextArea.
To make it short, I'd like to create a custom swing component based 100% on JTextArea. Once I do that, I'll be able to change different otherwise hard-coded properties of a JTextArea and make my own customised JTextArea. There are no predefined swing components that are designed the way I need them to be, but JTextArea is the closest, that why I choose it.
I'd like to change the spacing inbetweem the rows of a JTextArea. And no, I don't want to use JtextPane, I've tried, it doesn't work with my program, it calcualtes it position diferently, it look diferently, and applying the JtextArea border just messes thing up further.
I'm not trying to extend the JTextArea, I'm trying to create a custom JTextArea, as in custom swing component, with changed hard-coded properties that are not configurable trought JTextAreas methods.
However, I have no idea how to do it. I've been looking it up on the internet, but there is only an extensive guide about building your own component from stracth...
Figuring that out will take a lot of time and will not really solve my problem.
Only thing I have to do is create a class (or several classes) that will contain everyting that builds JTextArea. Start from JTextComponent level and copy all the lower level classes that are used in creating JTextArea. I'd also like to note that I use Nibus look and feel, I think that there may be some classes that would need to be included for the custom JTextArea to function properly under that LAF.
I've looked into the swing source code, and it's full of everyting. Figuring out what classes or their parts are used in creating a JTextArea would be a time consuming nightmare, given that I have no knowledge about core swing structure and mechanics.
That's why I'm asking somebody who has the knowledge to at least list the classes that I need to replicate the JTextArea, and I'll then figure out how to compose them.
Because, if I start learning now about swing core mechanics, it'll take days and weeks before I figure it all out, but for someone who knows, it would take only a couple of minutes to list all classes that I need to focus my attention onto.
I'm trying to take a shortcut here. I don't want to fully understand swing, I just want this thing to work. Default spacing is one pixel too low, and all I want to do is just make it that pixel higher. I don't want to know how the painter paints component onto screen, I just want to know where is it called from and what does it call itself...
Thanks to anyone who takes the time.
I'd like to change the spacing inbetweem the rows of a JTextArea
My first thought was that overriding javax.swing.JTextArea#getRowHeight would be sufficient. The javadoc clearly states
Defines the meaning of the height of a row. This defaults to the height of the font.
So I was hoping that by overriding this method, you would adjust the definition and you would get more spacing between the rows. Bummer, didn't work. A quick search on the usages of that method in the JDK revealed the same. It is mainly used to calculate some sizes, but certainly not used when painting text inside the component.
By looking at the source code of the javax.swing.text.PlainView#paint method, I saw that the FontMetrics are used, and those you can easily override in the JTextArea. So second approach was to extend the JTextArea (bwah, extending Swing components but it is for a proof-of-concept)
private static class JTextAreaWithExtendedRowHeight extends JTextArea{
private JTextAreaWithExtendedRowHeight( int rows, int columns ) {
super( rows, columns );
}
#Override
public FontMetrics getFontMetrics( Font font ) {
FontMetrics fontMetrics = super.getFontMetrics( font );
return new FontMetricsWrapper( font, fontMetrics );
}
}
The FontMetricsWrapper class basically delegates everything, except the getHeight method. In that method I added 10 to the result of the delegate
#Override
public int getHeight() {
//use +10 to make the difference obvious
return delegate.getHeight() + 10;
}
And this results in more row spacing (and a caret which is way too long, but that can probably be adjusted).
A little screenshot to illustrate this (not as nice as some of the other ones, but it shows that this approach might work):
Small disclaimer: this feels like an ugly hack and might result in unexpected issues. I do hope somebody comes with a better solution.

How to create separate screens in Swing? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am constantly finding myself building programs where there are multiple screens. For example, consider a program where the initial layout offers two buttons: create file or edit file. Upon clicking one, it takes the user to a new screen supporting whatever button they press. Then they click a back button and it takes them back to the main screen of the program. I am wondering how to best do separate menus like this. Would it be best just to create separate methods setting up each screen, then call the appropriate one when a button (like "back" button) is clicked? This is what I was thinking of doing, but seeing as there are many ways to do this, I want to get opinions on a possibly better way of changing the screen displayed.
Thanks, AJ
Based on your 2nd comment to the original question, I think it is best to look at using Panels.
Look at using multiple panels for each of the activities you want:
JPanel firstPanel = new JPanel();
JPanel secondPanel = new JPanel();
JPanel thirdPanel = new JPanel();
Ensure all panels are hidden when initialised, and then simply swap a panel for another one upon a button click event using:
firstPanel.hide();
secondPanel.show();
Depending on the layout you use, there are also other techniques. For example, rather than removing and adding (or showing and hiding multiple panels), if you use BorderLayout you can simple "replace" a BorderLayout area with another panel and then revalidate:
container.add(BorderLayout.CENTER, thirdPanel);
container.validate();
Note also that different Operating Systems (Windows, Mac etc) will have different styles they like to adhere to. For example you mentioned a typical Windows installer; people have come to expect an installer to look and work in a certain way, but on a different OS there are a completely different set of expectations and looks.
Further reading:
Tutorial on using panels
Java SE 7 (JPanel API)
Edit:
I am wondering how to best do separate menus like this. Would it be best just to create separate methods setting up each screen, then call the appropriate one when a button (like "back" button) is clicked?
This comes down to personal preference. Do you want to initalise everything on startup and have quicker swaps between panels (or as you called them: "screens"), OR do you want a quicker inital startup and essentially have "lazy loading" of each component as and when you need it.
Personally I opt for everything during initalisation (unless there is a lot of things to do or load during your applications startup). This really comes down to personal preference.
Another edit:
Speaking about layouts, perhaps a different layout style would also help you out, something like this:
CardLayout tutorial
Hope this helps out somewhat.
Take a look at the Actions framework, it's a great way of developing common level actions for re-use
If the state of the screen depends on the state of the previous screen (e.g. like in a wizard) you can follow the steps described in this article

I need to make an typing tutor, where to start? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I'm making a typing tutor in java (netbeans).
Now i have made an keyboard in gui .
A simple example of how I want it: the B and A are buttons and in the text field you can type.
Now there are some lessons to do
Lesson 1: abb ab abb (example)
So the A button needs to be red then you press A, B becomes red you press B.
How can I import this lessons into my application ? (notepad)
And how can I make the A becomes red when it needs to be?
I do not have some codes yet because I don't know where to start.
Make a class Lesson with a collection of characters.
You can make for each Lesson a file.
Read the files into Lesson objects and then go over the collection to the next char when the user has pressed the right button.
I'm not really sure what this question is about. It seems you want help to program the tutor and learning Java in the go. Stackoverflow is a Q&A-Platform, you should ask every concrete problem in a single question.
Anyways, I can see two questions packaged in the post:
1. How can I read a textfile in my program?
At least that is what I understand with 'importing the lesson'. Use a BufferedReader. With readLine() you can read one line after the other into a String.
2. How to color something I painted red?
I don't know how you painted the keyboard. But most likely you used the Graphics-object in the paint()-method. Graphics has a setColor()-method, so you can type something like this: setColor(Color.RED); before painting the element.
I would think you would do one of two options:
Add a listener for each key press (say an InputMethodListener) to the text field. In the listener, update the GUI to change the appropriate key's color.
JTextComponent.addImputMetherListener
Add a Keymap where for each key you have an Action that will change the background color of the appropriate section of the GUI.
JTextComponent.setKeymap

How do I prevent button surround from displaying in Java?

Sorry for the odd choice of words for the title, however, "border" seems to be the inappropriate term. While it is true that the visible line surrounding an icon in a JToggleButton can be made invisible by using setBorderPainted(false), the same is not true for JCheckBox and JRadioButton.
I can not use the JToggleButton and therefore need to use either the JCheckBox or JRadioButton (or some derivative of JToggleButton I am not aware of), but need the square or circle, respectively, to be non-visible when there is no icon on the button. Also, using setVisible(false) eliminates the button from the layout, however, I need the space to be reserved and not have the component layout change (using GroupLayout).
Any suggestions? Am I going to have to create a custom renderer? I will be looking at that in the mean time.
The route into this would be through customising the look at feel by changing some of the UI properties in the UImanager (the sort of thing that allows you to make simple tweaks with fonts and colours and presumably the images used for the checkboxes or radiobuttons) -- but it's many years since I last did that sort of thing and can't remember the details.
A little Googling turned up this project to inspect current property values, so might at least help with indicating the right part of the APIs to be looking at.
You have to choices here:
1) Customize Look and Feel as described in previous entry.
2) Create your own custom controls by inheriting from existing ones and overriding component painting.
I found a cheap and easy (read hack) for this. I created an empty transparent icon and used it when I didn't want any item to be displayed.

Categories