I am new to Vaadin.
I want to create a page where on the left side there are three options. Depending on the option selection combo boxes will appear on the right side which is specific to the option on the left. I want the combobox with label.
Name: "Combo box menu"
So far I can click the option on the left side and that displays the combo box on the right side but could not display the labels with the combo box. Label is a component and so is the combo box. When I add both to the panel. Expecting both label and combo box to showup but the last one (Combo Box) ignores the first one (Label). I am not sure why is that. I would really appreciate if someone could help me with that.
Thanks
Here is my code:
HorizontalLayout hLayout;
Panel hpanel;
HorizontalSplitPanel hsplit;
VerticalSplitPanel vsplit;
tree.setImmediate(true);
tree.addItem("OP1");
tree.addItem("OP2");
tree.addItem("OP3");
hsplit.setFirstComponent(tree);
tree.addListener(new Component.Listener() {
public void componentEvent(Component.Event event) {
Object o = tree.getValue();
System.out.println("selected = " + o);
showWindowtab(o);
}
});
hpanel.setContent(hsplit);
hLayout.addComponent(hpanel);
hLayout.setSpacing(true);
final VerticalLayout main = new VerticalLayout();
main.setMargin(true);
setContent(main);
main.addComponent(hLayout);
private void showWindowtab(Object itemClicked) {
Label label = new Label("Here is example of Combo Box");
hsplit.setSecondComponent(label);
String document[] = { "X", "Y", "Z" };
ComboBox cb = new ComboBox();
cb.setInputPrompt("Select values");
cb.setInvalidAllowed(false);
cb.setNullSelectionAllowed(false);
for (int i = 0; i < document.length; i++) {
cb.addItem(document[i]);
}
cb.setImmediate(true);
setFocusedComponent(cb);
hsplit.setSecondComponent(cb);
}
You call setSecondComponent() on both label and cb, so the second may override the first.
Maybe what you wanted was setfirstComponent(label)?
Another option is to call addComponent(label) on the component where you want to see your label.
Related
Let's say I made a swt and a button triggers this line of code:
Label Charname = new Label(shell, SWT.NONE);
Charname.setBounds(250,10+a,500,40);
Charname.setText("Hello");
a=a+40;
I press the button twice, so it makes 2 labels, like so:
hello
hello
If I wanted to .getText the FIRST label, how would I do so? I know these labels are both the same but this is just a example, in what I'm working in these labels are different.
You just need to remember the labels you have created so you can access them again. One way would be to save them in a list in your class.
public class MyClass {
List<Label> labels = new ArrayList<>();
.... other code
Label charname = new Label(shell, SWT.NONE);
...
// Save in the list
labels.add(charname);
.....
// Access old label
int index = ... index of label required
Label oldLabel = labels.get(index);
}
I am using a JList to display elements. I want to provide a popup menu to interact with the specific elements under the mouse. I am using a MouseInputListener, isPopupTrigger(), locationToIndex(), getCellBounds(), etc. I haven't posted code for this as it's not the point, just background for the question. What I ultimately want to do is only post the popup menu when the correct (platform- and UI-dependent) action occurs over the text in the JList cell - not just anywhere in the row. My JList is in a ScrollPane which is in a SplitPane. The width of the JList cells can be much larger than the text. If the user is able to post the popup by clicking far to the right of the text in the row when the SplitPane is much larger than the extent of the text, it will be unclear just which row is being operated on. I don't want to select the row that the user would be interacting with using the popup menu because selection has a different meaning in this context. So the basic question is: how can I determine if the mouse location when the popup trigger occurs is actually over the text in the row, rather than just in the row?
If the JList's cell renderer returns JLabels (which it will by default, or if you have set the renderer to a DefaultListCellRenderer), you can use SwingUtilities.layoutCompoundLabel to determine the bounds of the text:
static <E> boolean isOverText(Point location,
JList<E> list) {
int index = list.locationToIndex(location);
if (index < 0) {
return false;
}
E value = list.getModel().getElementAt(index);
ListCellRenderer<? super E> renderer = list.getCellRenderer();
Component c = renderer.getListCellRendererComponent(list, value, index,
list.isSelectedIndex(index),
list.getSelectionModel().getLeadSelectionIndex() == index);
if (c instanceof JLabel) {
JLabel label = (JLabel) c;
Icon icon = null;
if (!label.isEnabled()) {
icon = label.getDisabledIcon();
}
if (icon == null) {
icon = label.getIcon();
}
Rectangle listItemBounds =
SwingUtilities.calculateInnerArea(label, null);
Rectangle cellBounds = list.getCellBounds(index, index);
listItemBounds.translate(cellBounds.x, cellBounds.y);
listItemBounds.width = cellBounds.width;
listItemBounds.height = cellBounds.height;
Rectangle textBounds = new Rectangle();
Rectangle iconBounds = new Rectangle();
SwingUtilities.layoutCompoundLabel(label,
label.getFontMetrics(label.getFont()),
label.getText(),
icon,
label.getVerticalAlignment(),
label.getHorizontalAlignment(),
label.getVerticalTextPosition(),
label.getHorizontalTextPosition(),
listItemBounds,
iconBounds,
textBounds,
label.getIconTextGap());
return textBounds.contains(location);
}
I am trying to make a JTable with popup help menus for each column section. For instance, you right click on the first column title and a JTextArea pops up that explains what the column is for and what type of data should be put into it. I have the following code establishing the JTable and the mouselistener event. Is there a way I can write an If statement using ColumnAtPoint() so that if the right click happens at Column 1, then it opens up my JTextArea? Then I can create a second and third separate JTextAreas for my other columns.
final DefaultTableModel tblModel = new DefaultTableModel(null, colHdrs);
final JTable table = new JTable(tblModel);
table.getTableHeader().addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e))
{
JOptionPane.showMessageDialog(null, textArea1, "Type", JOptionPane.PLAIN_MESSAGE);
}
}
});
Try to use JToolTip I think it might be much more suited for your use ;) :)!
You can also add e.g. to a
JLabel label = new JLabel("My Number Label");
a tooltip text like :
label.setToolTipText("Only Numbers From 1-10 are allowed!");
This is also possible for other swing stuff, you can try it :).
The text will appear as soon as you hover over the label .
I have a JFrame extended class that implements a multi-tab chat. Every tab is a chat with someone or with a group of people. What I have implemented works fine, except when I assign a ToolTipText to the label of a tab. In this case I can't click anymore (and select) the tab that has a ToolTipText assigned. The others work fine.
Graphical example:
As you can see the tabs are properly being added, and the first two tabs ("Gruppo prova" and "Gruppo test") have a ToolTipText, the other two don't. I can switch between the last two, but I can't do the same with the first two. I thought that the icon next to the label could be a problem, but I removed it and still doesn't work. However I can still click all the 'X' (close) buttons (working properly).
This is a piece of the code I used to add a tab:
// Some stuff...
JChat chat = new JChat(gui.chatClient, email, name, group);
jTabbedPane.add(email, chat); // I instantiated this before
int index = jTabbedPane.indexOfTab(email);
JPanel pnlTab = new JPanel(new GridBagLayout());
pnlTab.setOpaque(false);
// Core function
JLabel lblTitle;
if (group == 1) {
// If it's a group and not a single chat I assign a name, an icon and a ToolTipText to the tab
lblTitle = new JLabel(name, icon, JLabel.LEFT);
lblTitle.setToolTipText(membersList.toString());
} else {
// otherwise I only assign a name to the tab
lblTitle = new JLabel(name);
}
jTabbedPane.setTabComponentAt(index, pnlTab);
// This applies the 'X' (close) button next to the tab name
CloseButton btnClose = new CloseButton(this, jTabbedPane, tabs, email);
lblTitle.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
pnlTab.add(lblTitle);
pnlTab.add(btnClose);
Is this a Swing bug or am I doing something wrong?
you can use :
void setToolTipTextAt(int, String) to set tool-tip text to specific tab.
void setIconAt(int index, Icon icon) to set the icon to specific tab.
No need to use JLabel for setting tool-tip text or icon.
The above solution, however doesn't however answer your question:
except when I assign a ToolTipText to the label of a tab. In this
case I can't click anymore (and select) the tab that has a ToolTipText
assigned
The only reason i am suspecting:
JLabel doesn't register to any mouse listener by default. When no mouse listener is set to JLabel any mouse clicked event will go through to the UI objects underneath: in this case the JTabbedPane. But when we are setting tool-tip text using setToolTipText(text), the ToolTipManger adds a mouse listener to this JLabel, which will continue to consume the mouse click event.
Check the following code snippets demonstrating the issue and providing a work around setSelectedIndex function:
JLabel label = new JLabel("a Label");
System.out.println(label.getMouseListeners().length); // length is printed as 0
label.setToolTipText("Danger: setting tool tip will consume mouse event");
System.out.println(label.getMouseListeners().length); // length is printed as 1
jTabbedPane1.setTabComponentAt(0, label);
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
int index = jTabbedPane1.indexOfTabComponent((Component)e.getSource());
jTabbedPane1.setSelectedIndex(index);
}
});
I'm finding the amount of helpful documentation/tutorials on the internet are lacking when it comes to the topic of JTextPanes. I'm trying to do a simple text processor, and I want it to be able to select a font family from a JComboBox that populates itself based on the fonts a user has installed on their system. However, no matter what I try with experimenting, I can't figure out how to make it work.
What I have is a toolbar class that is built off of a JTextPane. Currently, it has a bunch of style buttons that work to set alignment and bold, italics and underline.
Here's my code:
/**
* The StyleBar is used to customize styles in a Styled Document. It will take a
* JTextPane as an argument for its constructor and then all actions to be taken
* will affect the text in it.
*
* #author Andrew
*/
public class StyleBar extends JToolBar {
private JLabel fontLbl;
private JComboBox fontBox;
// ...Irrelevant stuff to the problem at hand.
/**
* The initEvents method is used to initialize the necessary events for the
* tool bar to actually do its job. It establishes the focus listener to the
* buttons on the bar, and gives each one its individual functionality. It
* also establishes the Font Selection interface.
*/
public void initEvents() {
//For each item in the tool bar, add the focus listener as well as the
//formatting listeners:
boldFormat.addActionListener(new StyledEditorKit.BoldAction()); //boldFormat is
boldFormat.addActionListener(resetFocus); //a JButton
//Ditto for my italicsFormat and underlineFormat button(s) in the toolbar
leftAlign.addActionListener(new StyledEditorKit.AlignmentAction(null,
StyleConstants.ALIGN_LEFT));
leftAlign.addActionListener(resetFocus); //This listener just resets focus
//back onto the TextPane.
//Ditto for my right and centerAlign buttons
//Set up the Font list, and add a listener to the combo box
buildFontMenu();
}
/**
* The buildFontMenu detects all of the SYstem's available fonts and adds
* them to the Font Selection box.
*/
public void buildFontMenu(){
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
final String[] fontNames = ge.getAvailableFontFamilyNames();
for (int i = 0; i < fontNames.length; i++){
//What do I do here to take the entry at String[i] and make it so that when
//the user selects it it sets the font Family in a similar way to that of
//pressing the boldFormat button or the leftAlign button?
}
}
//Everything else is irrelevant
So to sum up my problem: I have no idea how to properly set the listener to the ComboBox such that a) it's sensitive to the individual font selected and b) somehow uses StyledEditorKit.FontFamilyAction to make life easy?
Slash, if I'm approaching anything about this the wrong way, I'd love to hear the right way. As I said, my sources on the internet aren't very clear on the subject.
Thanks so much!
StyledEditorTest puts the Actions in a JToolBar, but the idea is the same. See also Charles Bell's HTMLDocumentEditor, mentioned here. For example,
bar.add(new StyledEditorKit.FontFamilyAction("Serif", Font.SERIF));
bar.add(new StyledEditorKit.FontFamilyAction("SansSerif", Font.SANS_SERIF));
Addendum: As you are using JComboBox, you can forward the event to the corresponding StyledEditorKit Action, which operates on the current selection by default.
JComboBox combo = new JComboBox();
combo.addItem("Serif");
combo.addItem("Sans");
combo.addActionListener(new ActionListener() {
Action serif = new StyledEditorKit.FontFamilyAction("Serif", Font.SERIF);
Action sans = new StyledEditorKit.FontFamilyAction("Sans", Font.SANS_SERIF);
#Override
public void actionPerformed(ActionEvent e) {
if ("Sans".equals(e.getActionCommand())) {
sans.actionPerformed(e);
} else {
serif.actionPerformed(e);
}
}
});
This may be a bit late, but I found myself stuck on the similar problem, and although the previous answer does help, here is a more complete answer for when you want to use all the fonts available on your computer..
Where "fonts" is a string array containing all the desired fonts to be used in your program
final JComboBox jcb = new JComboBox(fonts);
final Action [] actions = new Action[fonts.length];
for (int i = 0; i < actions.length; i++)
{
actions[i] = new StyledEditorKit.FontFamilyAction(fonts[i], fonts[i]);
}
jcb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
for (int i = 0; i < actions.length; i++)
{
if (fonts[i].equals((String)jcb.getSelectedItem()))
{
actions[i].actionPerformed(event);
break;
}
}
}
});