JPanel titled border with tooltip text for the title - java

I am using setBorder(BorderFactory.createTitledBorder(title)) in my JPanel in order to group its content in a rectangle with a title above it. How can I set a tooltip text for the title?

A possible approach is nesting components. As Borders are not components they can not have tooltips, but you can have a component with the sole purpose of holding border and the tooltip:
JPanel outer = new JPanel();
outer.setBorder(BorderFactory.createTitledBorder("Title"));
outer.setToolTipText("sample text");
JPanel inner = new JPanel();
outer.add(inner);
and then use inner as the container for the components you want to group.

You can override the getToolTipText() method of the panel to check if the mouse of over the title text:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class TitledBorderTest
{
private static void createAndShowUI()
{
UIManager.getDefaults().put("TitledBorder.titleColor", Color.RED);
Border lowerEtched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
TitledBorder title = BorderFactory.createTitledBorder(lowerEtched, "Title");
// title.setTitleJustification(TitledBorder.RIGHT);
Font titleFont = UIManager.getFont("TitledBorder.font");
title.setTitleFont( titleFont.deriveFont(Font.ITALIC + Font.BOLD) );
JPanel panel = new JPanel()
{
#Override
public String getToolTipText(MouseEvent e)
{
Border border = getBorder();
if (border instanceof TitledBorder)
{
TitledBorder tb = (TitledBorder)border;
FontMetrics fm = getFontMetrics( tb.getTitleFont() );
int titleWidth = fm.stringWidth(tb.getTitle()) + 20;
Rectangle bounds = new Rectangle(0, 0, titleWidth, fm.getHeight());
return bounds.contains(e.getPoint()) ? super.getToolTipText() : null;
}
return super.getToolTipText(e);
}
};
panel.setBorder( title );
panel.setToolTipText("Title With ToolTip");
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( panel );
frame.setSize(200, 200);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
This code assumes the title is on the left. If you want the title on the right then you would need to adjust the X value of the text bounds.

I don't think you can add setToolTipText to TitledBorder. you can provide tooltip for JComponent but TitledBorder is not derived from JComponent.
You can try to use JPanel instead:
ToolTipManager.sharedInstance().registerComponent(new JPanel());
//ToolTipManager.sharedInstance().setDismissDelay(800000);

TollTip isn't right Components for experiments, all goog workaround for popup or tooltips are based on JWindow/ undecorated JDialog
maybe not necessary, keys in UIManager are accesible, but in this case all TollTips has the same settings
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.*;
public class ColoredToolTipExample extends JFrame {
private static final long serialVersionUID = 1L;
public ColoredToolTipExample() {
Border line, raisedbevel, loweredbevel, title, empty;
line = BorderFactory.createLineBorder(Color.black);
raisedbevel = BorderFactory.createRaisedBevelBorder();
loweredbevel = BorderFactory.createLoweredBevelBorder();
title = BorderFactory.createTitledBorder("");
empty = BorderFactory.createEmptyBorder(1, 1, 1, 1);
Border compound;
compound = BorderFactory.createCompoundBorder(empty, line);
UIManager.put("ToolTip.foreground", new ColorUIResource(Color.red));
UIManager.put("ToolTip.background", new ColorUIResource(Color.yellow));
UIManager.put("ToolTip.font", new FontUIResource(new Font("Verdana", Font.PLAIN, 18)));
UIManager.put("ToolTip.border", new BorderUIResource(compound));
JButton button = new JButton("Hello, world");
button.setToolTipText("<html> - myText <br> - myText <br> - myText <br>");
getContentPane().add(button);
JFrame frame = new JFrame("Colored ToolTip Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 100);
frame.setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ColoredToolTipExample();
}
});
}
}

Related

Make TitledBorder editable upon double click

This is an extension of : Make a TitledBorder title editable
To be more specific, I want the TitledBorder to be editable when the title is double clicked. I'm placing the Border around a java Box that uses BoxLayout. The double click would preferably open a JTextField right there, but if that cannot be done, opening another window to edit the title is acceptable.
TitledBorder editableBorder = new TitledBorder(editableString);
editableBorder.setTitleJustification(TitledBorder.CENTER);
Box containerBox = new Box(BoxLayout.PAGE_AXIS);
containerBox.setBorder(new CompoundBorder(editableBorder, new EmptyBorder(10, 0, 10, 0)));
Box insideBox = new Box(BoxLayout.PAGE_AXIS);
insideBox.add(new JLabel(new ImageIcon(new BufferedImage(200,40,BufferedImage.TYPE_INT_RGB))));
containerBox.add(insideBox);
Here is an example. The MouseListener uses a JPopupMenu to display the text field. This means you can cancel editing by using the Escape key.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class TitledBorderListener extends MouseAdapter
{
private JPopupMenu editPopup;
private JTextField editTextField;
private TitledBorder titledBorder;
#Override
public void mouseClicked(MouseEvent e)
{
if (e.getClickCount != 2)
return;
// Edit the border on a double click
JComponent component = (JComponent)e.getSource();
Border border = component.getBorder();
if (border instanceof TitledBorder)
{
titledBorder = (TitledBorder)border;
FontMetrics fm = component.getFontMetrics( titledBorder.getTitleFont() );
int titleWidth = fm.stringWidth(titledBorder.getTitle()) + 20;
Rectangle bounds = new Rectangle(0, 0, titleWidth, fm.getHeight());
if (bounds.contains(e.getPoint()))
{
if (editPopup == null)
createEditPopup();
// Position the popup editor over top of the title
editTextField.setText( titledBorder.getTitle() );
Dimension d = editTextField.getPreferredSize();
d.width = titleWidth;
editPopup.setPreferredSize(d);
editPopup.show(component, 0, 0);
editTextField.selectAll();
editTextField.requestFocusInWindow();
}
}
}
private void createEditPopup()
{
editTextField = new JTextField();
// Add an Action to the text field to save the new title text
editTextField.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String value = editTextField.getText();
titledBorder.setTitle( value );
editPopup.setVisible(false);
editPopup.getInvoker().revalidate();
editPopup.getInvoker().repaint();
}
});
// Add the editor to the popup
editPopup = new JPopupMenu();
editPopup.setBorder( new EmptyBorder(0, 0, 0, 0) );
editPopup.add(editTextField);
}
private static void createAndShowUI()
{
JPanel panel = new JPanel();
panel.setBorder( new TitledBorder("Double Click to Edit") );
panel.addMouseListener( new TitledBorderListener() );
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( panel );
frame.setSize(200, 200);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

Is there anyway to add text inside picture in JFrame?

EDIT:Damn, my english is a bit off. I meant to ask how to add text "inside" picture not over(above) it , with the text be at the center of picture.
thank you for previous helps anyway :).
One way is to use OverlayLayout. For the text to be at the center of the image in both axes an alignment value of 0.5 should be used for both X & Y for both JLabel components shown below.
public class OverlayLabelApp {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Overlay App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
LayoutManager overlay = new OverlayLayout(panel);
panel.setLayout(overlay);
JLabel label1 = new JLabel("Centered Text");
label1.setForeground(Color.GREEN);
label1.setFont(new Font("SansSerif", Font.BOLD, 16));
label1.setAlignmentX(0.5f);
label1.setAlignmentY(0.5f);
panel.add(label1);
JLabel label2 =
new JLabel(new ImageIcon(OverlayLabelApp.class.getResource("/images/sunset.png"))); label2.setAlignmentX(0.5f);
label2.setAlignmentY(0.5f);
panel.add(label2);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
});
}
}
Sure. Paint the text direct to the picture. Display the picture in a label.
E.G.
How to edit a text that is converted into image?
How to resize text in java
Of course, if you want it 'simpler' there are other options. One is OverlayLayout as described by #Reimeus. Here is another. It utilizes the fact that we can set a layout for a label, and show components within it. This technique was popularized by #mKorbel.
import java.awt.*;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
class TextOnImage {
public static void main(String[] args) throws Exception {
URL url = new URL("http://i.stack.imgur.com/zJ8am.png");
final BufferedImage image = ImageIO.read(url);
Runnable r = new Runnable() {
#Override
public void run() {
JPanel gui = new JPanel(new BorderLayout());
JLabel l = new JLabel(new ImageIcon(image));
l.setLayout(new FlowLayout(FlowLayout.CENTER));
JLabel text = new JLabel("Hi!");
l.add(text);
JOptionPane.showMessageDialog(null, l);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
with the text be at the center of picture.
4 more approaches. The first is the easiest and sounds like what you want:
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class LabelImageText extends JPanel
{
public LabelImageText()
{
JLabel label1 = new JLabel( new ColorIcon(Color.ORANGE, 100, 100) );
label1.setText( "Easy Way" );
label1.setHorizontalTextPosition(JLabel.CENTER);
label1.setVerticalTextPosition(JLabel.CENTER);
add( label1 );
//
JLabel label2 = new JLabel( new ColorIcon(Color.YELLOW, 200, 150) );
label2.setLayout( new BoxLayout(label2, BoxLayout.Y_AXIS) );
add( label2 );
JLabel text = new JLabel( "More Control" );
text.setAlignmentX(JLabel.CENTER_ALIGNMENT);
label2.add( Box.createVerticalGlue() );
label2.add( text );
label2.add( Box.createVerticalStrut(10) );
//
JLabel label3 = new JLabel( new ColorIcon(Color.GREEN, 200, 150) );
add( label3 );
JLabel text3 = new JLabel();
text3.setText("<html><center>Text<br>over<br>Image<center></html>");
text3.setLocation(20, 20);
text3.setSize(text3.getPreferredSize());
label3.add( text3 );
//
JLabel label4 = new JLabel( new ColorIcon(Color.CYAN, 200, 150) );
add( label4 );
JTextPane textPane = new JTextPane();
textPane.setText("Add some text that will wrap at your preferred width");
textPane.setEditable( false );
textPane.setOpaque(false);
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
StyledDocument doc = textPane.getStyledDocument();
doc.setParagraphAttributes(0, doc.getLength(), center, false);
textPane.setBounds(20, 20, 75, 100);
label4.add( textPane );
}
public static class ColorIcon implements Icon
{
private Color color;
private int width;
private int height;
public ColorIcon(Color color, int width, int height)
{
this.color = color;
this.width = width;
this.height = height;
}
public int getIconWidth()
{
return width;
}
public int getIconHeight()
{
return height;
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
g.setColor(color);
g.fillRect(x, y, width, height);
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("LabelImageText");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new LabelImageText() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

JRadioButton Will not appear until Mouse over

import java.awt.Frame;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
public class IndicatorWindow implements ItemListener {
JRadioButton RMA, EMA, SMA, Williams, Stochastic;
JPanel IndPan, RadioPanel, title;
JLabel Lab;
JButton OK;
public JPanel createContentPane() {
JPanel GUI = new JPanel();
GUI.setLayout(null);
title = new JPanel();
title.setLayout(null);
title.setLocation(0, 0);
title.setSize(500, 145);
GUI.add(title);
Lab = new JLabel("Please Select Indicator Type");
Lab.setLocation(5, 0);
Lab.setSize(200, 30);
title.add(Lab);
ButtonGroup bg1 = new ButtonGroup();
RadioPanel = new JPanel();
RadioPanel.setLayout(null);
RadioPanel.setLocation(10, 30);
RadioPanel.setSize(190, 220);
GUI.add(RadioPanel);
RMA = new JRadioButton("RMA");
RMA.setLocation(0, 0);
RMA.addItemListener(this);
RMA.setSize(110, 20);
bg1.add(RMA);
RadioPanel.add(RMA);
EMA = new JRadioButton("EMA");
EMA.setLocation(0, 30);
EMA.addItemListener(this);
EMA.setSize(110, 20);
bg1.add(EMA);
RadioPanel.add(EMA);
SMA = new JRadioButton("SMA");
SMA.setLocation(0, 60);
SMA.addItemListener(this);
SMA.setSize(110, 20);
bg1.add(SMA);
RadioPanel.add(SMA);
Stochastic = new JRadioButton("Stochastic");
Stochastic.setLocation(0, 90);
Stochastic.addItemListener(this);
Stochastic.setSize(110, 20);
bg1.add(Stochastic);
RadioPanel.add(Stochastic);
Williams = new JRadioButton("Williams");
Williams.setLocation(0, 120);
Williams.addItemListener(this);
Williams.setSize(110, 20);
bg1.add(Williams);
RadioPanel.add(Williams);
OK = new JButton();
OK.setText("Confirm");
OK.setLocation(45, 150);
OK.addItemListener(this);
OK.setSize(90, 30);
RadioPanel.add(OK);
//GUI.setOpaque(true);
return GUI;
}
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
if (source == RMA) {
System.out.print("Browse");
} else if (source == EMA) {
System.out.print("EMA");
} else if (source == SMA) {
System.out.print("SMA");
} else if (source == Williams) {
System.out.print("Williams");
} else if (source == Stochastic) {
System.out.print("Stochastic");
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Indicators");
IndicatorWindow ind = new IndicatorWindow();
frame.setContentPane(ind.createContentPane());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(200, 250);
frame.setLayout(null);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setAlwaysOnTop(true);
frame.setState(Frame.NORMAL);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
My problem is that when i compile and run this code, the jFrame appears but there is only one problem, 3 JRadioButtons dont appear until you put your mouse over them. The RMA and Williams radiobuttons appear, the 3 in the middle do not though, any thoughts on why this is?
http://i.stack.imgur.com/gNnIb.jpg
You should be using layout managers. People think using a "null layout" is easier, but it is not and you are more prone to having errors with your code. Layout managers will position and size components properly to make sure all components are displayed. Sometimes you even use multiple different layout managers to achieve the layout you desire.
Your problem in this case is that you have two components occupying the same space in your container. So one component gets painted over top of the other. After you mouse over your radio button, the button is repainted because of the rollover effect of the button. However, now try resizing the frame and the radio buttons will disappear because all the components are repainted and the component is painted over top of the buttons again.
The following line of code is the problem:
// title.setSize(500, 145);
title.setSize(500, 20);
But the real solution is to rewrite the code and use layout managers. While you are at it use proper Java naming conventions. Variable names do NOT start with an uppercase letter. You got "title" and "bg1" correct. So fix "EMA", "RMA" etc...
#camickr is correct. Note how using layout managers (and a little re-factoring) can actually simplify your code. Also, the relevant tutorial suggests using an action listener, rather than an item listener.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/** #see http://stackoverflow.com/questions/5255337 */
public class IndicatorWindow implements ActionListener {
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
JRadioButton rma, ema, sma, stochastic, williams;
ButtonGroup bg = new ButtonGroup();
public JPanel createContentPane() {
JPanel gui = new JPanel(new BorderLayout());
JPanel title = new JPanel();
JLabel lab = new JLabel("Please Select Indicator Type");
title.add(lab);
gui.add(title, BorderLayout.NORTH);
createRadioButton(rma, "RMA");
createRadioButton(ema, "EMA");
createRadioButton(sma, "SMA");
createRadioButton(stochastic, "Stochastic");
createRadioButton(williams, "Williams");
gui.add(radioPanel, BorderLayout.CENTER);
JButton ok = new JButton();
ok.setText("Confirm");
ok.addActionListener(this);
radioPanel.add(ok);
return gui;
}
private void createRadioButton(JRadioButton jrb, String name) {
jrb = new JRadioButton(name);
bg.add(jrb);
jrb.addActionListener(this);
radioPanel.add(jrb);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Indicators");
frame.add(new IndicatorWindow().createContentPane());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setAlwaysOnTop(true);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
You should add your JRadioButtons with a method:
private void bgAdd (String name, int y)
{
JRadioButton rb = new JRadioButton (name);
rb.setLocation (0, y);
rb.addItemListener (this);
rb.setSize (110, 19);
bg1.add (rb);
radioPanel.add (rb);
}
Calling code:
bgAdd ("RMA", 0);
bgAdd ("EMA", 30);
bgAdd ("SMA", 60);
bgAdd ("Stochastic", 90);
bgAdd ("Williams", 120);
Action:
public void itemStateChanged (ItemEvent e) {
Object button = e.getItemSelectable ();
String source = ((JRadioButton) button).getText ();
System.out.print (source + " ");
}
Then add BoxLayout to the page, for example.

How can I measure/calculate the size a Document needs to render itself?

I have a javax.swing.text.Document and I want to calculate the size of the bounding box that document needs to render itself.
Is that possible?
It is almost trivial for plain text (height = line count * line height, width = max width over each line) But how can I do this with RTF, HTML or any other document?
This code might give you some ideas:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class TextPanePerfectSize extends JFrame
{
JTextField textField;
JTextPane textPane;
public TextPanePerfectSize()
{
textField = new JTextField(20);
textField.setText("add text");
getContentPane().add(textField, BorderLayout.NORTH );
textField.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
Document doc = textPane.getDocument();
doc.insertString(doc.getLength(), " " + textField.getText(), null);
textField.setText("");
Dimension d = textPane.getPreferredSize();
Rectangle r = textPane.modelToView( textPane.getDocument().getLength() );
d.height = r.y + r.height;
textPane.setPreferredSize( d );
getContentPane().validate();
// pack();
}
catch(Exception e2) {}
}
});
JLabel label = new JLabel("Hit Enter to Add Text to Text Pane");
getContentPane().add(label);
JPanel south = new JPanel();
textPane = new JTextPane();
textPane.setText("Some text");
textPane.setEditable( false );
// textPane.setPreferredSize( new Dimension(120, 23) );
south.add( textPane );
// getContentPane().add(south, BorderLayout.SOUTH);
getContentPane().add(textPane, BorderLayout.SOUTH);
}
public static void main(String[] args)
{
JFrame frame = new TextPanePerfectSize();
frame.setSize(200, 200);
frame.setLocationRelativeTo( null );
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
The Document interface is a model for a text component, so the Document doesn't really have a boundary; but the View has a number of methods that "translate between the model and view coordinate systems." Depending on the goal, something there may help.
Try to use this to measure height for fixed widht.
http://java-sl.com/tip_text_height_measuring.html
The getPreferred will return you the width and height.

Make JTextPane adjust height to content

I'm trying to get a JTextPane to adjust its height according to whatever content I feed it. All I can do is to set a fixed height in pixels using Dimension.
How do I make the JTextPane collapse/expand so it will fit to contents?
I might add that I use this in a GridBagLayout'ed JPanel that has been added to a JScrollPane.
I don't know any direct way to do it, but this may give you some ideas:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class TextPanePerfectSize extends JFrame
{
JTextField textField;
JTextPane textPane;
public TextPanePerfectSize()
{
textField = new JTextField(20);
textField.setText("add text");
getContentPane().add(textField, BorderLayout.NORTH );
textField.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
Document doc = textPane.getDocument();
doc.insertString(doc.getLength(), " " + textField.getText(), null);
textField.setText("");
Dimension d = textPane.getPreferredSize();
Rectangle r = textPane.modelToView( textPane.getDocument().getLength() );
d.height = r.y + r.height;
textPane.setPreferredSize( d );
getContentPane().validate();
// pack();
}
catch(Exception e2) {}
}
});
JLabel label = new JLabel("Hit Enter to Add Text to Text Pane");
getContentPane().add(label);
JPanel south = new JPanel();
textPane = new JTextPane();
textPane.setText("Some text");
textPane.setEditable( false );
textPane.setPreferredSize( new Dimension(120, 23) );
south.add( textPane );
getContentPane().add(south, BorderLayout.SOUTH);
}
public static void main(String[] args)
{
JFrame frame = new TextPanePerfectSize();
frame.setSize(200, 200);
frame.setLocationRelativeTo( null );
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
JTextPane tp = new JTextPane();
setLayout(new BorderLayout()); // set layout on parent
add(tp, BorderLayout.CENTER);
This works for me.

Categories