How to know in which JTextPane the cursor is? - java

I have several JtextPanes and I want to create a method that set the value of a variable to the name of the TextPane which has been clicked because another methond is going to use it. There's also a button that adds a new jTextPane when the user clicks on it and I want those new TextPanes to inherit that method. Or if you know a simpler way to achieve that I'm open to read you. Let me know if you need more information or more code.
static JTextPane focus;
private void redColorActionPerformed(java.awt.event.ActionEvent evt) { //Ths is the method that works with the focus variable. It changes the color of the text in the clicked textpane.
TextEditor.cambiarColor(new java.awt.Color(255, 0, 0), focus);
}

It sound like you want to know the current Swing JTextPane component under the current mouse position? Then try to
Get current Mouse position
Point position = MouseInfo.getPointerInfo().getLocation();
Get the component under the mouse location
Component c = SwingUtilities.getDeepestComponentAt(
the-root-component,
position.getX(),
position.getY()
);
if (c instanceof JTextPane) {
// do your logic
}

Related

How to make a textarea filled with text (label) every time the button pressed?

I'm trying to make a text area record that every time the button is press, it means that it has been recorded and should be showing record1, record2, record3, etc. on it.
My goal is that, every button is pressed it will add text to the text area with different text label so that no redundancy.
I tried it with my own with this:
private void btnReqstRefreshActionPerformed(java.awt.event.ActionEvent evt) {
JLabel labelthis = new JLabel("record1");
label.setSize(label.getPreferredSize());
TextArea1.add(label);
TextArea1.revalidate();
TextArea1.repaint();
}
I know it is wrong, but is it possible?
text area is like a mini text editor - you add text to it not other components. Instead of adding labels - just add the text. Something like:
TextArea1.setText(TextArea1.getText() + "record1")
This should append record1 to the existing text in the text area.
According to my experience this is possible.
`private void btnReqstRefreshActionPerformed(java.awt.event.ActionEvent evt) {
i++;//i class level variable(static) to avoid redundancy
//labelThis initialized earlier should be accessible here
String oldText = labelThis.getText().toString();
oldText += "record "+i;
labelThis.setSize(labelThis.getPreferredSize());
TextArea1.add(labelThis);
TextArea1.revalidate();
TextArea1.repaint();
}`

Mouse position of JDialog relative to JTable

This is my code:
JTable1.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1)
{
JTable target = (JTable)e.getSource();
Point pMouse = new Point();
pMouse = target.getMousePosition();
}
}
}
So I am retrieving the point (coordinates) relative to the JTable. So let's say the user clicks somewhere in a cell and the returned Point is X=272 and Y=50. So now I want to position a JDialog exactly by those coordinates. I tried:
jDialog1.setLocation(pMouse);
jDialog1.setVisible(true);
But this positions the Dialog somewhere else (the coordinates of the screen instead of the Table). Does somebody have a suggestion on how I can position the JDialog relative to the cell?
You are using the co-ordinates in relation to the client area of the JTable content. You want the global co-ordinates in relation to the entire window. For this you can use:
Point location = MouseInfo.getPointerInfo().getLocation();
jDialog1.setLocation(location);
In general, a user should be able to use your application either by mouse or keyboard. What happens if the user tabs to that cell? Should they not be able to see the same dialog? So for a more general solution that works whether you use a mouse or not:
SwingUtilities.convertPointToScreen(point, table);
Check out the other convertXXX methods in SwingUtilities for future reference.
Or, you can always use:
Component.getLocationOnScreen();
and then add on the mouse point.

Get shown component in JScrollPane

I have a JScrollPane containing a JPanel. I fill this JPanel with many buttons.
Is there any possibility to get the currently shown buttons?
I know I can access the children of a JPanel via jpanel.getComponents() but those are all components in this pane; I want only the ones that are currently on screen.
As already commented to #mKorbel's answer:
it's correct that you need the child bounds
it's correct that you need to intersect those bounds with "something"
it's wrong that you need the containing viewport (nor the scrollpane)
JComponents have an API to get their currently visible part independently of how/where exactly they are currently shown, so the "something" is the JComponent's visibleRect:
Rectangle visibleRect = myPanel.getVisibleRect();
for (Component child : myPanel.getComponents()) {
Rectangle childBounds = child.getBounds();
if (childBounds.intersects(visibleRect)) {
// do stuff
}
}
I assume that this container is already visible on the screen, then I suggest
1) to extract JViewPort from JScrollPane,
2) addChangeListener to JViewPort
3) each visible JComponent(s) returns Rectangle
4) and Rectangle#intersects returns Boolean value if is JComponent(s) visible or not in JViewPort
How about asking the components if they're visible:
for ( Component component : jpanel.getComponents() ) {
if ( component instanceof JButton && component.isShowing() ) {
// We've found a button that is showing...
}
}
Component#isShowing()
scrollPane.getViewport().getView()
scrollPane.getViewport().getViewRect()

Example text in JTextField

I am looking for a way to put example text into a swing JTextField and have it grayed out. The example text should then disappear as soon as any thing is entered into that text field. Some what similar to what stackoverflow does when a user is posting a question with the title field.
I would like it if it was already a extended implementation of JTextField so that I can just drop it in as a simple replacement. Anything from swingx would work. I guess if there is not an easy way to do this my option will probably be to override the paint method of JTextField do something that way maybe.
Thanks
The Text Prompt class provides the required functionality without using a custom JTextField.
It allows you to specify a prompt that is displayed when the text field is empty. As soon as you type text the prompt is removed.
The prompt is actually a JLabel so you can customize the font, style, colour, transparency etc..:
JTextField tf7 = new JTextField(10);
TextPrompt tp7 = new TextPrompt("First Name", tf7);
tp7.setForeground( Color.RED );
Some examples of customizing the look of the prompt:
If you can use external librairies, the Swing components from Jide software have what you are looking for; it's called LabeledTextField (javadoc) and it's part of the JIDE Common Layer (Open Source Project) - which is free. It's doing what mklhmnn suggested.
How about initialize the text field with default text and give it a focus listener such that when focus is gained, if the text .equals the default text, call selectAll() on the JTextField.
Rather than overriding, put a value in the field and add a KeyListener that would remove the value when a key stroke is registered. Maybe also have it change the foreground.
You could wrap this up into your own custom JTextField class that would take the default text in a constructor.
private JLabel l;
JPromptTextField(String prompt) {
l = new JLabel(prompt, SwingConstants.CENTER);
l.setForeground(Color.GRAY);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (this.getText().length() == 0) {
// Reshape the label if needed, then paint
final Rectangle mine = this.getBounds();
final Rectangle its = l.getBounds();
boolean resized = (mine.width != its.width) || (mine.height != its.height);
boolean moved = (mine.x != its.x) || (mine.y != its.y);
if (resized || moved)
l.setBounds(mine);
l.paint(g);
}
}
You can't do that with a plain text field, but you can put a disabled JLabel on top of the JTextField and hide it if the text field gets the focus.
Do it like this:
Define the string with the initial text you like and set up your TextField:
String initialText = "Enter your initial text here";
jTextField1.setText(initialText);
Add a Focus Listener to your TextField, which selects the entire contents of the TextField if it still has the initial value. Anything you may type in will replace the entire contents, since it is selected.
jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
if (jTextField1.getText().equals(initialText)) {
jTextField1.selectAll();
}
}
});

how to hide a text area in java swing form?

i used textarea1.setVisible(false); but still i can see the border of the text area at run time. i want the textarea to be completely invisible
Can anyone help in this issue?
It sounds like you have a Panel around your text area since setVisible(false) should definitely hide the entire component. If so, make the panel invisible. Care to post some code so we can examine and help?
You have to hide the scroll pane which your text area is sitting in. If for some reason you have no direct access to it here is the way to get it:
public static final JScrollPane getScrollPane( JComponent component ) {
Container p = component .getParent();
if (p instanceof JViewport) {
Container gp = p.getParent();
if (gp instanceof JScrollPane) {
return (JScrollPane)gp;
}
}
return null;
}
Find your textarea scrollpane, then set the visibility to false, like this:
jScrollPane4.setVisible(false);

Categories