How would i program a dynamic menubar in Swing? - java

Basically i want to be able to allow the user to save bookmarks which are then put into a list on a submenu on a menubar. How would i go about programming a general function for any number of bookmarks that may be added, i basically want the items to put the URL into a textbox when clicked. Would i need to create a new class for this, or is there an inbuilt function?
My program is a simple RSS reader written in Java using Swing.

You need to add a MenuListener to the menu item that you want to be dynamic.
In the void menuSelected(MenuEvent e) method, implement the construction of the submenus.
In a first implementation, you can first reset the content of your menu and then rebuid it from scratch instead of updating it :
JMenu menu = new JMenu("Bookmarks");
menu.addMenuListener(new MyMenuListener());
private class MyMenuListener implements MenuListener {
public void menuCanceled(MenuEvent e) { }
public void menuDeselected(MenuEvent e) { }
public void menuSelected(MenuEvent e) {
JMenu menu = (JMenu) e.getSource();
populateWindowMenu(menu);
}
}
void populateWindowMenu(JMenu windowMenu) {
windowMenu.removeAll();
// Populate the menu here
}

Related

Disable button in Java until all fields filled

I'm new to Java and developing a small project. I'm making a program where the user has to register themselves. I have 3 different tabs on my Tabbed Pane. I want to be able to disable the next button on the first pane making it impossible for the user to continue to pane 2 unless all the text fields on pane 1 have been filled. I have been Searching online and found various examples but none of them would work in run time.
I am using Netbeans.
private void txtFirstNameActionPerformed(java.awt.event.ActionEvent evt) {
if(txtFirstName.getText().trim().length() > 0)
btnNext1.setEnabled(true);
else
btnNext1.setEnabled(false);
}
Create a List of all the text fields on your pane:
List<JTextField> list = new ArrayList<>();
Add all your text fields to that list.
Then, create a universal DocumentListener that listens for text change events, and every time a text update happens, scan through all your text fields to see if they have all been filled:
DocumentListener listener = new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) { changedUpdate(e); }
#Override
public void insertUpdate(DocumentEvent e) { changedUpdate(e); }
#Override
public void changedUpdate(DocumentEvent e) {
boolean canEnable = true;
for (JTextField tf : list) {
if (tf.getText().isEmpty()) {
canEnable = false;
}
}
btnNext1.setEnabled(canEnable);
}
};
And add that listener to every text field you have in the list:
for (JTextField tf : list) {
tf.getDocument().addDocumentListener(piecesListener);
}

Processing a buttonclick in Oracle forms programticly for an implementation class

I am having the following problem which is exclusive to the oracle forms framework and custom implementation classes provided in java. I modified a VButton to display a custom menue as soon as i am pressing the right mouse button.
The following was accomplished by inheriting from the VButton and providing a custom behavior.
The popup will be displayed by a JPopupMenu. This JPopupMenu will be filled dynamicly by a HashMap<String, JMenuItem> which represents each option in this JPopupMenu and it´s representing key. To accomplish this i wrote an abstract class which contains everything that needs to be done to create a custom right click menu, with two abstract methods. These methods will be overriden by subclasses of this class and will create two representing lists of Keys for the Map and theyr representing JMenuItem.
This is how the abstract class is designed.
public abstract class AbstractRightClickButton extends VButton{
// The PopupMenu for this item;
private JPopupMenu popup = new JPopupMenu();
// The HashMap that stores the Menuitems and it´s keys
private HashMap<String, JMenuItem> menuItems = new HashMap<String, JMenuItem>();
// Stores the current selected key.
private String choice= "";
public AbstractRightClickButton() {
this.menuItems = generateHashmap();
initMouseListener();
initPopUp();
}
// Abstract method to create an ArrayList of all JMenuItem
public abstract ArrayList<JMenuItem> generateJMenuItemSide();
// Abstract method to create an ArrayList for each key in the HashMap
public abstract ArrayList<String> generateStringSide();
private void initPopUp() {
ArrayList<String> list = generateStringSide();
for (String counter : list) {
popup.add(menuItems.get(counter));
}
}
private void initMouseListener() {
this.addMouseListener(new MouseListener() {
public void mousePressed(MouseEvent e) {
if(SwingUtilities.isRightMouseButton(e)) {
// If the width of the popup is 0 then it wasn´t displayed yet. Just show it once and make it invisible again to get the width and height of the popup.
if (popup.getWidth() == 0) {
popup.show(AbstractRightClickButton.this, AbstractRightClickButton.this.getWidth(), 0);
popup.setVisible(false);
}
popup.show(AbstractRightClickButton.this, AbstractRightClickButton.this.getWidth()-popup.getWidth(), 0);
}
}
public void mouseExited(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
});
protected HashMap<String, JMenuItem> generateHashmap() {
HashMap<String, JMenuItem> map = new HashMap<String, JMenuItem>();
ArrayList<String> key = generateStringSide();
ArrayList<JMenuItem> value = generateJMenuItemSide();
for (int i = 0;i < key.size();++i) {
map.put(key.get(i), value.get(i));
}
return map;
};
// This method is a helper method that can be called by subclasses of AbstractRightClickButton
// It creates a JMenutButton based on the parameter
protected JMenuItem generateJMenuItem(final String key, final boolean click) {
JMenuItem item = new JMenuItem(new AbstractAction(key) {
#Override
public void actionPerformed(ActionEvent e) {
choice = key;
if (click) {
ActionEvent act = new ActionEvent((Object)AbstractRightClickButton.this, ActionEvent.ACTION_PERFORMED, ""); // Button Event erstellen
AbstractRightClickButton.this.processEvent(act); // Event Processen um den Buttondruck Formsseitig auch auszulösen
}
}
});
return item;
}
}
A concrete class would look like this
public class ConcreteRightClickButton extends AbstractRightClickButton{
#Override
public ArrayList<String> generateStringSide() {
ArrayList<String> basis = new ArrayList<String>(0);
basis.add("OPTION1");
basis.add("OPTION2");
return basis;
}
#Override
public ArrayList<JMenuItem> generateJMenuItemSide() {
ArrayList<JMenuItem> basis = new ArrayList<JMenuItem>(0);
basis.add(generateJMenuItem("OPTION1", true));
basis.add(generateJMenuItem("OPTION2", true));
return basis;
}
}
The problem i am facing depends on the type of button, espacially how this button is defined in the forms builder. If the button property iconic is defined as No, then the call of AbstractRightClickButton.this.processEvent(act) correctly processes this event and can be handelt by the When-Button-Pressed Event in Oracle Forms. But if the button property iconic is defined as Yes then the processing of the event somehow doesn´t work. While Debugging everything looks fine, there is no exception and it reaches the AbstractRightClickButton.this.processEvent(act) without any problem. But the representing When-Button-Pressed Trigger in Oracle Forms doesn´t react. Am i processing the Event incorrectly or is there something else that stops oracle forms from recieving this event?
I am using Oracle forms 11g to create a mask containing this specific button.
1 year 8 months later, maybe this isn't an "answer" but its an alternative way to do the same thing.
Create a class that extends VBean, and create a JButton.
Add the jar to the classpath, and call it within a Bean Area.
It's called java pluggable components.
This page is useful:
JPC
EDIT:
import java.awt.Color;
import javax.swing.JButton;
import oracle.forms.ui.VBean;
public class TryButton extends VBean {
JButton button = new JButton();
public TryButton() {
this.setSize(500, 500);
this.setVisible(true);
this.add(button);
button.setSize(500, 500);
button.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/imagen2.png")));
}
}
Then, add the jar to: oracle_home/forms/java
and add it to classpath
In oracle forms in a new canvas create a Bean Area
Go to Item Properties and add the class package and name to: implementation class.

JPopupMenu not showing text of JMenuItem

I'm trying to create a JPopupMenu, but for some reason, it doesn't show the text I've set on the JMenuItems. The menu itself works, there are menuitems in it and they are responsive, but the text is not showing. I'm creating the menu like this:
private void createPopupMenu() {
this.popupMenu = new JPopupMenu();
this.addMouseListener(new PopupListener(this));
JMenuItem addPlaceMenuItem = new JMenuItem(SketchPad.ADD_PLACE_POPUP_TEXT);
addPlaceMenuItem.setAction(new PopupAction(ActionType.AddPlace));
this.popupMenu.add(addPlaceMenuItem);
JMenuItem addTransitionMenuItem = new JMenuItem(SketchPad.ADD_TRANSITION_POPUP_TEXT);
addTransitionMenuItem.setAction(new PopupAction(ActionType.AddTransition));
this.popupMenu.add(addTransitionMenuItem);
}
In case it matters, here is the PopupListener:
class PopupListener extends MouseAdapter {
SketchPad pad;
public PopupListener(SketchPad pad)
{
this.pad = pad;
}
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1)
{
this.pad.getController().deselectAllNodes();
}
else
{
maybeShowPopup(e);
}
}
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
pad.popupPosition = new Point(e.getX(), e.getY());
pad.popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
}
What am I missing here?
but for some reason, it doesn't show the text I've set on the JMenuItems.
addPlaceMenuItem.setAction(new PopupAction(ActionType.AddPlace));
The setAction(...) method reset the properties of the menu item with the properties of the Action. So you need to make sure you set the NAME property of the Action to set the text of the menu item.
So in your case it looks like the value of the NAME property should be:
SketchPad.ADD_PLACE_POPUP_TEXT
Or the other approach is to reset the text of the menu item after you set the Action
JMenuItem addPlaceMenuItem = new JMenuItem( new PopupAction(ActionType.AddPlace) );
addPlaceMenuItem.setText(SketchPad.ADD_PLACE_POPUP_TEXT);
The effect is platform specific. In particular, "In Microsoft Windows, the user by convention brings up a popup menu by releasing the right mouse button while the cursor is over a component that is popup-enabled." Your implementation of mouseReleased() precludes even checking isPopupTrigger(). Instead, handle the selection and check the trigger. A similar approach is shown in GraphPanel in order to handle multiple selection and a context menu.

Editable JComboBox with dynamic entries

I made my JComboBox editable using:
myCombo.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
I encounter multible problems with the following task:
When writing into the combobox, the new content of the box should be taken and compared with a list and all entries starting with this text should be shown in the popupmenu.
So if i have a list with: "Aban" "Aben" "Aber" "Acen" "Aden"
and enter "Ab" into the box, then the pop-up should display the first 3 entries.
When clicking one of the entries (Either by keyboard selecting and pressing enter/tab or by clicking with a mouse) The ComboBox should get that value and the Popup should hide. I need to find this action as some of the elements have a note at the end (In backets which I require) but only when one of the entries is selected
Here are the most imporant parts of my code:
final JTextComponent tcA = (JTextComponent) myCombo.getEditor().getEditorComponent();
tcA.getDocument().addDocumentListener(new DocumentListener() {
public void methodUsedByinsertUpdateAndremoveUpdate(DocumentEvent e) {
String item = ((JTextComponent) myCombo.getEditor().getEditorComponent()).getText();
//Routine to get the new list in a vector, not pasted for readability
DefaultComboBoxModel newMyComboModel = new DefaultComboBoxModel(myVectorList);
myCombo.setModel(newMyComboModel);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
myCombo.showPopup();
}
});
}
}
myCombo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(myCombo.getModel().getSize() == 1) {
//Special logic to find out if the selected item has a note
SwingUtilities.invokeLater(new Runnable() {
public void run() {
myCombo.hidePopup();
}
});
}
}
With this, i have:
Trouble with the first character (Caret position not working correctly)
Popup not automatically shown and hides when entering new character into the field
Problems with Swing GUI not being actualised
If you require more information just ask
The Glazed List recommended by peeskillet did exactly what I wanted

Java swt treeview popup menu

Hiho,
currently I have a working popup menu which appears when I click on a treeview item.
But I want to show different popups for different tree view entries. I don't get a idea how to do so...
Here is my code for creating the menu:
MenuManager menuMgr = new MenuManager("#PopupMenu");
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
#Override
public void menuAboutToShow(IMenuManager manager) {
Action action = new Action() {
public void run() {
// So something
}
};
action.setText("Set as working file");
manager.add(action);
}
});
Menu menu = menuMgr.createContextMenu(getTree());
getTree().setMenu(menu);
You should propably use a MouseListener on the tree:
final Tree tree = new Tree(parent, ...);
tree.addMouseListener(new MouseAdapter() {
#override
public void mouseDown(MouseEvent me) {
if(tree.getSelection() instanceof MySpecificTreeNode) {
// create menu...
}
}
});
Two ideas. For both you need to listen to selections on the TreeView, because that's the only way to determine which Menu (or special content) you want to show.
Then you could either set the correct menu to the the tree right after you know which one to use or contribute the needed items to the existing menu (that's how it's done in the eclipse framework).

Categories