How to disable automatic focus on textField - java

When I was creating a bunch of JTextFields I saw that first one is selected. I want to deselect it, because I have focus listener and it's running automatically. Any clues?
SSCCE:
JTextField tf = new JTextField("hello");
tf.setForeground(Color.decode("0x8C8C8C")); // for nice comment inside the text field
textFieldKwotaWplacona.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e)
{
if(tf.getForeground() != Color.BLACK)
{
tf.setText("");
tf.setForeground(Color.BLACK);
}
} #Override
public void focusLost(FocusEvent arg0) {}});
//for deleting "nice comment" after click
tf.setBounds(//some bounds);
add(tf);
Repeat that process for another text field
EDIT2 :
actual code (I believe its sscce :P)
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class Main extends JFrame implements ActionListener
{
JTextField textFieldKwotaWplacona, textFieldOprocentowanie, textFieldDlugoscLokaty, textFieldKwotaOtrzymana;
Main()
{ setSize(500,300);
setLayout(null);
setTitle("Program do liczenia procentu składanego");
setDefaultCloseOperation(EXIT_ON_CLOSE);
textFieldKwotaWplacona = new JTextField("Ilość pieniędzy wpłaconych");
textFieldKwotaWplacona.setForeground(Color.decode("0x8C8C8C"));
textFieldKwotaWplacona.addActionListener(this);
textFieldKwotaWplacona.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e)
{
if(textFieldKwotaWplacona.getForeground() != Color.BLACK)
{
textFieldKwotaWplacona.setText("");
textFieldKwotaWplacona.setForeground(Color.BLACK);
}
} #Override
public void focusLost(FocusEvent arg0) {}});
textFieldKwotaWplacona.setBounds(10, 10, 100, 20);
add(textFieldKwotaWplacona);
textFieldOprocentowanie = new JTextField("Oprocentowanie");
textFieldOprocentowanie.setForeground(Color.decode("0x8C8C8C"));
textFieldOprocentowanie.addActionListener(this);
textFieldOprocentowanie.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e)
{
if(textFieldOprocentowanie.getForeground() != Color.BLACK)
{
textFieldOprocentowanie.setText("");
textFieldOprocentowanie.setForeground(Color.BLACK);
}
}
#Override
public void focusLost(FocusEvent arg0) {}});
textFieldOprocentowanie.setBounds(10, 40, 100, 20);
add(textFieldOprocentowanie);
}
#Override
public void actionPerformed(ActionEvent arg0)
{
// TODO Auto-generated method stub
}
public static void main(String[] args)
{
Main a=new Main();
a.setVisible(true);
}
}
I want to set focus to window or sth else, in order to prevent text from disappearing.

As discussed in the comments, I added a radio button to take the focus instead:
public class Main extends JFrame {
JTextField textFieldKwotaWplacona, textFieldOprocentowanie;
Main() {
setTitle("Program do liczenia procentu składanego");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
textFieldKwotaWplacona = new JTextField("Ilość pieniędzy wpłaconych");
textFieldKwotaWplacona.setForeground(Color.decode("0x8C8C8C"));
textFieldKwotaWplacona.addFocusListener(new FieldFocusListener(textFieldKwotaWplacona));
add(textFieldKwotaWplacona);
textFieldOprocentowanie = new JTextField("Oprocentowanie");
textFieldOprocentowanie.setForeground(Color.decode("0x8C8C8C"));
textFieldOprocentowanie.addFocusListener(new FieldFocusListener(textFieldOprocentowanie));
add(textFieldOprocentowanie);
JRadioButton btn = new JRadioButton("text");
add(btn);
pack();
btn.requestFocusInWindow();
}
private class FieldFocusListener extends FocusAdapter {
private JTextField field;
FieldFocusListener(JTextField field) {
this.field = field;
}
#Override
public void focusGained(FocusEvent e) {
if (field.getForeground() != Color.BLACK) {
field.setText("");
field.setForeground(Color.BLACK);
}
}
}
public static void main(String[] args) {
Main a = new Main();
a.setVisible(true);
}
}
Explanation
From the tutorial:
If you want to ensure that a particular component gains the focus the first time a window is activated, you can call the requestFocusInWindow method on the component after the component has been realized, but before the frame is displayed.
That means btn.requestFocusInWindow() must appear after pack() and before a.setVisible(true).
The reason you need another component to take the focus is that when a window is focused, a component inside it must gain the focus.
Notes:
If you want a better text field hint, see #camickr's answer.
Don't use null layout. Pick one that serves your GUI design (I picked FlowLayout just because it's fast to use, though probably not what you need).
Instead of setting the size of the frame, pack() after all components had been added.
Instead of creating the same focus listener for every text field, just create it as a class and reuse it. I show one way with passing the component to a constructor, but you can get rid of that and use e.getComponent() to get the text field instance.

In your constructor, you could use the method requestFocusInWindow().
This is what was working for me here-
After creating the JFrame, call frame.requestFocusinWindow();. This will make sure your text field is not focused.
Then, when you focus on the text field, the event is being fired.

tf.setForeground(Color.decode("0x8C8C8C")); // for nice comment inside the text field
Maybe you are trying to set a prompt for the text field that disappears when the text field gains focus?
If so, check out Text Field Prompt for a solution.
If not, then post a proper SSCCE, because I still can't guess what you are trying to do.

Related

Updating JPanel content in JFrame by using a frame state variable

I'm trying to find a way how to update a panel content after changing a state variable.
Concretely in the example below, there is simple JPanel inside JFrame with two buttons. When the app starts, its state variable ("window") equals "home" so home button should be invisible. After clicking on the page button the state variable change and so both buttons visibility should change after frame repainting. (i.e. the page button should disappear and the home button should appear).
In this case, it is possible to solve it without the state variable just using setVisibility() method for buttons. But in my app, I would like to have more JComponetns connected to the state variable. Is there a way how to do it?
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class JPanelUpdateTest {
private JFrame frame;
private String window = "home";
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JPanelUpdateTest window = new JPanelUpdateTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public JPanelUpdateTest() {
initialize();
}
private void initialize() {
frame = new JFrame("JPanelUpdateTest");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
JButton btnHome = new JButton("home");
btnHome.setVisible(window == "home" ? false : true);
btnHome.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
window = "page";
panel.revalidate();
frame.repaint();
}
});
panel.add(btnHome);
JButton btnPage = new JButton("page");
btnPage.setVisible(window == "page" ? false : true);
btnPage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
window = "home";
panel.revalidate();
frame.repaint();
}
});
panel.add(btnPage);
}
}
The problem is that initialize is only being called once, at object creation, and it should only be called once, and because of this the setVisible(...) code is not being called from the ActionListeners. Instead you need to put the mechanisms for changing the views within the ActionListeners themselves, not just changing state, not unless you are using a "bound property" and PropertyChangeListeners.
Myself, I'd recommend using a CardLayout to assist you in your swapping, and rather than directly changing Strings, call a public method of your class -- planning for when and if the ActionListener (controller) code is ever removed from the view class.
Also, regarding:
btnPage.setVisible(window == "page" ? false : true);
don't compare Strings using == or !=. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two object references are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here.
Also, if all you want to do is change the text and behavior that a JButton is doing, then you can change this easily by using setText(...) to change only the text, and for a deeper change, call setAction(Action action) to change text and state.

Why can't I get KeyEvent.VK_TAB when I use Key Binding for a JPanel

I will print related info if users focus on current window and press a key. However, it works for some keys like 'a' but not for 'tab'. Here is a simple demo:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class KeyBindingTest {
public static void main(String[] args) {
KeyBindingTest test = new KeyBindingTest();
test.createUI();
}
public void createUI(){
JFrame frame = new JFrame("KeyBinding Test");
MainPanel mainPanel = new MainPanel();
frame.add(mainPanel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#SuppressWarnings("serial")
class MainPanel extends JPanel{
public MainPanel(){
setPreferredSize(new Dimension(200, 200));
//========================key binding============================
requestFocusInWindow();
String aString = "aStr";
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), aString);
getActionMap().put(aString, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("a is typed");
}
});
String tabString = "tabStr";
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), tabString);
getActionMap().put(tabString, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("tab is typed");
}
});
}
}
}
What can I do to reach it? Thanks in advance.
Quote from How to Use the Focus Subsystem (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features) (suggested by #alex2410(link to #camickr post) and #mKorbel):
In most Look and Feel models, components are navigated using the Tab and Shift-Tab keys. These keys are the default focus traversal keys and can be changed programmatically.
...
Tab shifts the focus in the forward direction. Shift-Tab moves the focus in the backward direction. Tabbing moves the focus through the buttons into the text area. Additional tabbing moves the cursor within the text area but not out of the text area because, inside a text area, Tab is not a focus traversal key. However, Control-Tab moves the focus out of the text area and into the first text field. Likewise, Control-Shift-Tab moves the focus out of the text area and into the previous component.
...
The Control key is used by convention to move the focus out of any component that treats Tab in a special way, such as JTable.
You have just received a brief introduction to the focus architecture. If you want more details, see the specification for the Focus Subsystem.
So if you want to make the Tab KeyBinding action work in the panel, you need to remove the Tab key focus navigation from the panel.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
//http://stackoverflow.com/q/24800417/714968
public class KeyBindingTest3 {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame("KeyBinding Test");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new MainPanel());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class MainPanel extends JPanel {
public MainPanel() {
super();
//#see JTable constructor
Set<KeyStroke> forwardKeys = new HashSet<KeyStroke>(1);
forwardKeys.add(KeyStroke.getKeyStroke(
KeyEvent.VK_TAB, InputEvent.CTRL_MASK));
setFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, forwardKeys);
Set<KeyStroke> backwardKeys = new HashSet<KeyStroke>(1);
backwardKeys.add(KeyStroke.getKeyStroke(
KeyEvent.VK_TAB, InputEvent.SHIFT_MASK | InputEvent.CTRL_MASK));
setFocusTraversalKeys(
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, backwardKeys);
setPreferredSize(new Dimension(200, 200));
String aString = "aStr";
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), aString);
getActionMap().put(aString, new AbstractAction() {
#Override public void actionPerformed(ActionEvent e) {
System.out.println("a is typed");
}
});
String tabString = "TAB";
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), tabString);
getActionMap().put(tabString, new AbstractAction() {
#Override public void actionPerformed(ActionEvent e) {
System.out.println("tab is typed");
}
});
}
}
interesting issue with TAB, looks like as bug, because isn't possible to get, capture the KeyChar from TAB without using Shift_TAB before, event from TAB is somehow consumed elsewhere, no idea whats happened
my view - there is an issue with Focus because key TAB is used by Native OS and as built_in KeyBindings in Swing,
opposite issue with TAB and Shift_TAB in question Java Swing: how to stop unwanted shift-tab keystroke action
maybe someone has explanation how to catch a TAB event
TAB is used as KeyBindings (built_in in API) for many JComponents or navigations inside Container contains more than one JComponent
funny output from AWTEventListener (win8_64b/Java7_xxx)
is typed //tab is pressed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed //shift is pressed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed
is typed // tab is pressed again
is typed
is typed
is typed
is typed //:-) nobody knows something from milky way
is typed
is typed
shift tab is typed //now is tab event unlocked for Container in Swing
shift tab is typed
shift tab is typed
ctrl tab is typed
ctrl tab is typed
ctrl tab is typed
tab is typed // now is possible, finally TAB is unlocked and firing an event
tab is typed
tab is typed
from code
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
//https://stackoverflow.com/q/24800417/714968
public class KeyBindingTest {
public static void main(String[] args) {
KeyBindingTest test = new KeyBindingTest();
test.createUI();
}
public void createUI() {
JFrame frame = new JFrame("KeyBinding Test");
MainPanel mainPanel = new MainPanel();
frame.add(mainPanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
#Override
public void eventDispatched(AWTEvent event) {
if (event instanceof KeyEvent) {
KeyEvent ke = (KeyEvent) event;
System.out.println(ke.getKeyChar() + " is typed");
}
}
}, AWTEvent.KEY_EVENT_MASK);
}
#SuppressWarnings("serial")
class MainPanel extends JPanel {
public MainPanel() {
setPreferredSize(new Dimension(200, 200));
//========================key binding============================
//requestFocusInWindow();
String aString = "aStr";
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), aString);
getActionMap().put(aString, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("a is typed");
}
});
String tabString = "TAB";
this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(tabString), tabString);
//getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), tabString);
this.getActionMap().put(tabString, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("tab is typed");
}
});
String tabShiftString = "shift TAB";
this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(tabShiftString), tabShiftString);
//getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), tabString);
this.getActionMap().put(tabShiftString, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("shift tab is typed");
}
});
String ctrlShiftString = "ctrl TAB";
this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(ctrlShiftString), ctrlShiftString);
//getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), tabString);
this.getActionMap().put(ctrlShiftString, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("ctrl tab is typed");
}
});
}
}
}
I think it should work if you put
setFocusTraversalKeysEnabled(false);
in your MainPanel constructor. At least it works for e.g. addKeyListener(...);

Swing and events

Well, this is a very newie cuestion. Im stating to write by myself the code of my GUI applications with the help of window builder, i have decided to stop using netbeans couse ive read some peope in here that said that would be good. You may think i havent investigate, but trust me, i did my homework...
I tryed the way oracle says:
Declare an event handler class and specify that the class either implements an ActionListener interface or extends a class that implements an ActionListener interface. For example:
public class MyClass implements ActionListener {
Register an instance of the event handler class as a listener on one or more components. For example:
someComponent.addActionListener(instanceOfMyClass);
Include code that implements the methods in listener interface. For example:
public void actionPerformed(ActionEvent e) {
...//code that reacts to the action...
}
and my own way (wrong, off course, but i dont know whats wrong)
package Todos;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Main extends JFrame {
private JPanel contentPane;
protected JButton btnNewButton;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(new BorderLayout());
//setDefaultLookAndFeelDecorated(false);
//setIconImage(Image imagen);
setTitle("");
setSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());
setPreferredSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());
setLocationRelativeTo(null);
this.btnNewButton = new JButton("New button");
this.btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
asd(arg0);
}
});
this.getContentPane().add(this.btnNewButton, BorderLayout.NORTH);
}
public void asd(ActionEvent arg0) {
this.getContentPane().add(new JButton("asd"));
}
}
The cuestion is, why this code doesnt work, the JButton im trying to add to the JFrame with the ActionPerformed event is not visible after i click.
This is an example code, may look silly, but i think it simplifies the cuestion, since my problem is in a few lines of code its not neccesary to show you the hole proyect.
Thank you in advance!
Your problem is here:
public void asd(ActionEvent arg0) {
this.getContentPane().add(new JButton("asd"));
}
Form Container.add() javadoc:
This method changes layout-related information, and therefore,
invalidates the component hierarchy. If the container has already been
displayed, the hierarchy must be validated thereafter in order to
display the added component.
You need to call validate() method to make added button visible:
public void asd(ActionEvent arg0) {
this.getContentPane().add(new JButton("asd"));
this.getContentPane().validate();
}

Displaying a TextField on user interaction

I want to display a TextField only when user has entered a value in Input field
Here is my code:
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class PlayingAround {
JFrame frame;
JTextField display;
JTextField input;
public static void main(String[] args) {
PlayingAround obj = new PlayingAround();
obj.create();
}
private void create() {
frame = new JFrame();
display = new JTextField();
input = new JTextField();
display.setEditable(false);
display.setVisible(false);
input.addKeyListener(new Listener());
frame.add(BorderLayout.NORTH, display);
frame.add(BorderLayout.SOUTH, input);
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class Listener implements KeyListener {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
display.setVisible(true);
display.setText(input.getText());
}
}
}
But my problem is that the Display JTextField doesn't becomes visible until there are some events like Resizing the Window, Minimizing and maximizing the Window.
I tried calling frame.repaint() in the keyReleased Method but even it has not helped.
You should call revalidate() and repaint() on the container that holds the JTextField after placing the text field component in the container. The revalidate() call sends a request to the container's layout managers to re-layout its components. The repaint() then requests that the JVM request of the paint manager to redraw the newly laid out container and its child components. The repaint() is not always needed but is usually a good idea.
Also, don't use a KeyListener for this, but rather a DocumentListener on the first text component's Document. This way, if the user empties the first text component, you can make the second text component disappear if desired. Also, text can be entered without key presses, and you want to allow for that.

Adding mouselistener to JLabel/JButton inserted in JTextPane

I have a problem where when I try and add a mouselistener to a JLabel or JButton in a JTextPane I get the error "cannot be converted to Mouselistener by invocation conversion". I would prefer to have the component in a JEditorPane. I also heard a HyperlinkEvent could be used.
Basicly I want a component that can be right/left clicked in a JEditorPane(preffered)/JTextPane. Any help would be appreciated
Now it works (sortof) it only recives right clicks and I need to not draw button edges. Can I underline the button's text?
Example code follows...
import java.awt.*;
import javax.swing.*;
import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.JButton;
import java.applet.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class jlabeltest extends Applet {
public void init() {
jlabeltest editorPaneExample = new jlabeltest();
editorPaneExample.setSize(550, 300);
// editorPaneExample.setText("tutorialData.com");
editorPaneExample.setVisible(true);
}
public jlabeltest() {
JTextPane editorPane = new JTextPane();
editorPane.setSelectedTextColor(Color.red);
editorPane.setText("<p color='#FF0000'>Cool!</p>");
InlineB label = new InlineB("JLabel");
label.setAlignmentY(0.85f);
label.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e)
{
if (e.isPopupTrigger())
{
JOptionPane.showMessageDialog(null,"Hello!");
// do your work here
}
}
});
editorPane.insertComponent(label);
this.add(editorPane);
}
}
InlineB.java
import javax.swing.JButton;
public class InlineB extends JButton {
public InlineB( String caption ) {
super( caption );
}
}
I'm not sure what you want the question is everywhere.
But look too underline text of a JButton simply set the text of the button with HTML tags:
//added <u></u> to underlone button
InlineB label = new InlineB("<html><u>JLabel</u></html>");
as for the left click add a check to your if statement for the MouseEvent.BUTTON1 or SwingUtilities.isLeftMouseButton(MouseEvent me):
//added check for MouseEvent.BUTTON1 which is left click
if (e.isPopupTrigger() || e.getButton() == MouseEvent.BUTTON1) {
}
To not draw the borders of the JButton simply call setBorder(null); either in the InlineB class or on the InlineB instance (I did it within the class):
  public InlineB(String caption) {
super(caption);
    setBorder(null);//set border to nothing
}
also I see that you dont set the content type of the JTextPane, which you should:
//set content as html
editorPane.setContentType("text/html");
I did a small example though I did not use an Applet but its very easy to port:
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class Test {
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test().createAndShowUI();
}
});
}
private void createAndShowUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents(frame);
frame.pack();
frame.setVisible(true);
}
private void initComponents(JFrame frame) {
JTextPane editorPane = new JTextPane();
editorPane.setSelectedTextColor(Color.red);
//set content as html
editorPane.setContentType("text/html");
editorPane.setText("<p color='#FF0000'>Cool!</p>");
//added <u></u> to underlone button
InlineB label = new InlineB("<html><u>JLabel</u></html>");
label.setAlignmentY(0.85f);
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
//added check for MouseEvent.BUTTON1 which is left click
if (e.isPopupTrigger() || e.getButton() == MouseEvent.BUTTON1) {
JOptionPane.showMessageDialog(null, "Hello!");
// do your work here
}
}
});
editorPane.insertComponent(label);
frame.getContentPane().add(editorPane);
}
}
class InlineB extends JButton {
public InlineB(String caption) {
super(caption);
setBorder(null);//set border to nothing
}
}
I have a problem where when I try and add a mouselistener to a JLabel or JButton in a JTextPane I get the error "cannot be converted to Mouselistener by invocation conversion".
The object you are passing to addMouseListener() implements the MouseListener interface. Right? (Just seen the code sample. Mouse adapter seems right).
You now say Now it works (sortof). Does it mean you have corrected that error?
BTW if that is resolved and you have subsequent problems, and they are reusable by the community, then i would advise to open a separate question: https://meta.stackexchange.com/questions/48345/what-is-the-etiquette-for-changing-the-substance-of-a-question
I would prefer to have the component in a JEditorPane.
I guess you mean the component you are listening. Anyway I'm not sure the JEditorPane is meant to be used as other components' container.
I also heard a HyperlinkEvent could be used.
HyperLinkEvent is meant for ENTERED, EXITED, and ACTIVATED event types. You are intending to handle Hyperlink events or mouse events?
Basicly I want a component that can be right/left clicked in a JEditorPane(preffered)/JTextPane. Any help would be appreciated
I would advise next time give the scope/context of the question first. I guess you mean you want something (can you be more specific?) on top of a text pane that can be clicked. Anyway I'm surprise you intend to use JEditorPane that way.

Categories

Resources