I cant see my JMenu in the frame when I run it, what should i do?
I removed the panel where it was before, then i just want to put it in my frame
package app.ui;
import java.awt.Color;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.WindowConstants;
import app.model.User;
import app.util.JMenusss;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
public class JMenus {
private JFrame menuu;
private SecurityQuestion securityQuestion;
private User user;
private JMenu mnAccount;
public JMenus(JFrame menuu) {
this.menuu = menuu;
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
final JLabel lblHome = new JLabel("");
lblHome.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
Welcome myWelcome = new Welcome();
menuu.dispose();
}
});
lblHome.setIcon(new ImageIcon(JMenus.class.getResource("/app/resources/home-icon.png")));
lblHome.setBounds(780, 4, 88, 83);
menuu.getContentPane().add(lblHome);
final JLabel lblItem = new JLabel("");
lblItem.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
ItemManagement myItemManagement = new ItemManagement();
myItemManagement.ItemManagement();
menuu.dispose();
}
});
lblItem.setIcon(new ImageIcon(JMenus.class.getResource("/app/resources/items.png")));
lblItem.setBounds(860, 4, 88, 83);
menuu.getContentPane().add(lblItem);
final JLabel lblGroupManagement = new JLabel("");
lblGroupManagement.setIcon(new ImageIcon(JMenus.class.getResource("/app/resources/group11.png")));
lblGroupManagement.setBounds(940, 4, 88, 83);
menuu.getContentPane().add(lblGroupManagement);
lblGroupManagement.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
GroupManagement myGroupManagement = new GroupManagement();
myGroupManagement.groupManagement();
menuu.dispose();
}
});
final JLabel lblInventory = new JLabel("");
lblInventory.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
IOStock myInventory = new IOStock();
myInventory.InventoryWindow();
menuu.dispose();
}
});
lblInventory.setIcon(new ImageIcon(JMenus.class.getResource("/app/resources/IO.png")));
lblInventory.setBounds(1020, 4, 88, 83);
menuu.getContentPane().add(lblInventory);
final JLabel lblLogout = new JLabel("");
lblLogout.setIcon(new ImageIcon(JMenus.class.getResource("/app/resources/lock.png")));
lblLogout.setBounds(1100, 4, 120, 83);
menuu.getContentPane().add(lblLogout);
lblLogout.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
int selectedOption = JOptionPane.showConfirmDialog(null,"You are about to logout, are you sure?","Choose",JOptionPane.YES_NO_OPTION);
if (selectedOption == JOptionPane.YES_OPTION) {
Login window = new Login();
window.frmLogin.setVisible(true);
menuu.dispose();
}
}
});
This is where my JMenu is
JMenuBar mnbMenu = new JMenuBar();
mnbMenu.setBackground(Color.WHITE);
mnbMenu.setBounds(100, 4, 80, 89);
menuu.getContentPane().add(mnbMenu);
mnAccount = new JMenu();
mnAccount.setBackground(Color.WHITE);
mnAccount.setForeground(Color.WHITE);
mnAccount.setIcon(new ImageIcon("/app/resources/Settings-icon.png"));
mnAccount.setBounds(1180, 4, 100, 100);
mnbMenu.add(mnAccount);
JMenuItem mntmChangeUsername = new JMenuItem("Change Username");
mntmChangeUsername.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
UpdateUserName updateUsername = new UpdateUserName(user);
updateUsername.setVisible(true);
}
});
//mntmChangeUsername.setBackground(Color.WHITE);
mnAccount.add(mntmChangeUsername);
JMenuItem mntmChangePassword = new JMenuItem("Change Password");
mntmChangePassword.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
ChangeUsername changeUsername = new ChangeUsername(menuu);
changeUsername.changeAcc();
}
});
mntmChangePassword.setBackground(Color.WHITE);
mnAccount.add(mntmChangePassword);
JMenuItem mntmChangeSecurityQuestion = new JMenuItem("Change Security Question");
mntmChangeSecurityQuestion.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
ChangeSecurityQuestion changeSecurity = new ChangeSecurityQuestion(user, securityQuestion);
changeSecurity.setVisible(true);
changeSecurity.setLocationRelativeTo(null);
changeSecurity.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
changeSecurity.setAlwaysOnTop(true);
}
});
mntmChangeSecurityQuestion.setBackground(Color.WHITE);
mnAccount.add(mntmChangeSecurityQuestion);
}
}
This is my code...
I want to add the JMenu on my Frame,,, but its not visible, why?
Here:
JMenuBar mnbMenu = new JMenuBar();
...
menuu.getContentPane().add(mnbMenu);
The correct way to set the menu bar to a JFrame is through setJMenuBar() method:
JMenuBar mnbMenu = new JMenuBar();
...
menuu.setJMenuBar(mnbMenu);
Take a look to How to Use Menus tutorial. Additionaly you may want to see this topic Why JMenuBar is not place in the JFrame content pane(...)
Side note
Take a look to all #AndrewThompson's tips:
MCTaRE (Minimal Complete Tested and Readable Example)
Nowhere in those code snippets is a call to method setJMenuBar
Don't add a mouse listener to a menu. Add an ActionListener or an Action instead.
To organize the components for a robust GUI, instead use layout managers, or combinations of them, along with layout padding & borders for white space.
Related
So, I have this task where the user guess the correct number just by clicking on the JLabel I have presented for them. What I was trying to is to generate a random number then use if (e.getSource() == random) { } but it seems object and int isn't a compatible operand and I was hoping if someone has any solution to this.
Anyways, here is the source code of what I am doing nothing good since I don't have any solution on my first problem yet.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Font;
import java.util.Random;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Test123 {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test123 window = new Test123();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test123() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Random generator = new Random();
int num;
num = generator.nextInt(9) + 1;
int count = 0;
frame = new JFrame();
frame.setBounds(100, 100, 405, 195);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel NO1 = new JLabel("1");
NO1.setBounds(20, -26, 43, 183);
NO1.setFont(new Font("Arial", Font.BOLD, 75));
frame.getContentPane().add(NO1);
JLabel NO2 = new JLabel("2");
NO2.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO2.setFont(new Font("Arial", Font.BOLD, 75));
NO2.setBounds(60, -26, 43, 183);
frame.getContentPane().add(NO2);
JLabel NO3 = new JLabel("3");
NO3.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO3.setFont(new Font("Arial", Font.BOLD, 75));
NO3.setBounds(102, -26, 43, 183);
frame.getContentPane().add(NO3);
JLabel NO4 = new JLabel("4");
NO4.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO4.setFont(new Font("Arial", Font.BOLD, 75));
NO4.setBounds(143, -26, 43, 183);
frame.getContentPane().add(NO4);
JLabel NO5 = new JLabel("5");
NO5.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO5.setFont(new Font("Arial", Font.BOLD, 75));
NO5.setBounds(184, -26, 43, 183);
frame.getContentPane().add(NO5);
JLabel NO6 = new JLabel("6");
NO6.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO6.setFont(new Font("Arial", Font.BOLD, 75));
NO6.setBounds(223, -26, 43, 183);
frame.getContentPane().add(NO6);
JLabel NO7 = new JLabel("7");
NO7.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO7.setFont(new Font("Arial", Font.BOLD, 75));
NO7.setBounds(264, -26, 43, 183);
frame.getContentPane().add(NO7);
JLabel NO8 = new JLabel("8");
NO8.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO8.setFont(new Font("Arial", Font.BOLD, 75));
NO8.setBounds(304, -26, 43, 183);
frame.getContentPane().add(NO8);
JLabel NO9 = new JLabel("9");
NO9.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
}
});
NO9.setFont(new Font("Arial", Font.BOLD, 75));
NO9.setBounds(345, -26, 43, 183);
frame.getContentPane().add(NO9);
JLabel CorrectAns = new JLabel("Correct!");
CorrectAns.setEnabled(false);
CorrectAns.setBounds(181, 132, 46, 14);
frame.getContentPane().add(CorrectAns);
NO1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getSource() == num) {
count++;
CorrectAns.setText("Correct!" + count + " attempts");
}
}
});
}
}
MouseEvent#getSource will return the object which trigged the event, in your case, the JLabel.
A "generally" better solution might be to use JButton instead, then take advantage of the ActionListener. I'd attach a single ActionListener to the "correct" button to handle the correct workflow and a ActionListener to the others to handle the incorrect state
See How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener for more details
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Twst {
public static void main(String[] args) {
new Twst();
}
public Twst() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
randomButtons();
}
protected void randomButtons() {
removeAll();
List<JButton> buttons = new ArrayList<>(4);
Random rnd = new Random();
Set<Integer> numbers = new HashSet<>();
while (numbers.size() < 4) {
int number = rnd.nextInt(99) + 1;
numbers.add(number);
}
for (Integer number : numbers) {
JButton btn = new JButton(Integer.toString(number));
add(btn);
buttons.add(btn);
}
Collections.shuffle(buttons);
JButton correct = buttons.remove(0);
correct.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(TestPane.this, "Correct");
randomButtons();
}
});
ActionListener wrong = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() instanceof JButton) {
JButton btn = (JButton) evt.getSource();
btn.setEnabled(false);
}
JOptionPane.showMessageDialog(TestPane.this, "Wrong");
// You could keep a counter or do what ever else you
// want with a wrong guess
}
};
for (JButton btn : buttons) {
btn.addActionListener(wrong);
}
revalidate();
repaint();
}
}
}
This is the code.
The button doesnt work with key, if i dont click it first. It would
be great if you could help me.
I used eclipse when i created this frame
This is just an example code, but I just want to know how it functions
For any more detalis, ask here.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JTextField;
public class ExampleApp {
private JFrame frmHi;
private JTextField textField;
private JButton btnAnother;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ExampleApp window = new ExampleApp();
window.frmHi.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ExampleApp() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmHi = new JFrame();
frmHi.setTitle("Hi");
frmHi.setBounds(100, 100, 450, 300);
frmHi.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmHi.getContentPane().setLayout(null);
JButton btnEnter = new JButton("Enter");
btnEnter.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
textField.setText("You pressed enter");
}
}
});
btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("Hi there from button");
}
});
btnEnter.setBounds(119, 63, 89, 23);
frmHi.getContentPane().add(btnEnter);
textField = new JTextField();
textField.setEnabled(false);
textField.setEditable(false);
textField.setBounds(108, 30, 173, 20);
frmHi.getContentPane().add(textField);
textField.setColumns(10);
btnAnother = new JButton("Backspace");
btnAnother.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent arg0) {
if (arg0.getKeyCode() == KeyEvent.VK_BACK_SPACE){
textField.setText("you pressed backspace");
}
}
});
btnAnother.setBounds(119, 119, 89, 23);
frmHi.getContentPane().add(btnAnother);
}
}
Your KeyListener addded to JButton so it works only when the button has focus (after click).
It's better to define KeyBindings for the keys you have to process.
based on my understanding,
`list_1.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
}}
will do something when something in the list was selected, and
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
do something when the button have been pushed.
I want to write a code to delete the selected item from one list and add it to another one.
I can't use Jlist methods because it is not in the scope of button.
I am not sure how to do it. and I can't find something that solve my problem on net or books.
Thank you so much
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;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JList;
import java.awt.GridLayout;
import javax.swing.JSplitPane;
import java.awt.Component;
import javax.swing.Box;
import java.awt.Dimension;
import javax.swing.JSeparator;
import java.awt.Panel;
import java.awt.List;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.Color;
import java.awt.Font;
public class Window {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application. This is the constructor for this Window class.
* All of the code here will be executed as soon as a Window object is made.
*/
public Window() {
initialize();
}
/**
* Initialize the contents of the frame. This is where Window Builder
* will generate its code.
*/
public void initialize() {
//creates an array for the list of components
String pclist[]={"case","moderboard","CPU","GPU","PSU","RAM","HDD"};
frame = new JFrame();
frame.setBounds(100, 100, 600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmLoad = new JMenuItem("Load");
mnFile.add(mntmLoad);
JMenuItem mntmSave = new JMenuItem("Save");
mnFile.add(mntmSave);
JMenuItem mntmExit = new JMenuItem("Exit");
mnFile.add(mntmExit);
frame.getContentPane().setLayout(null);
JButton button = new JButton(">>");
button.setBounds(244, 170, 82, 36);
button.setFont(new Font("Tahoma", Font.BOLD, 15));
frame.getContentPane().add(button);
JButton button_1 = new JButton("<<");
button_1.setBounds(244, 219, 82, 36);
button_1.setFont(new Font("Tahoma", Font.BOLD, 15));
frame.getContentPane().add(button_1);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 205, 493);
panel.setBackground(Color.WHITE);
frame.getContentPane().add(panel);
panel.setLayout(null);
JList list = new JList();// implements ActionListener;
list.setBounds(0, 0, 205, 493);
list.setListData(pclist); //populate the Jlist
list.setFont(new Font("Tahoma", Font.BOLD, 18));
panel.add(list);
JPanel panel_1 = new JPanel();
panel_1.setBounds(358, 0, 212, 493);
panel_1.setBackground(Color.WHITE);
frame.getContentPane().add(panel_1);
panel_1.setLayout(null);
JList list_1 = new JList();
list_1.setBounds(203, 0, -200, 480);
list_1.setSelectedIndex(0);
list_1.setFont(new Font("Tahoma", Font.BOLD, 18));
panel_1.add(list_1);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//list_1.addElement("hi");
System.out.println("hoi");
}
});
list.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent arg0) {
}});
list_1.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
}
}
);
}
}
Start by making your JLists instance variables
public class Window {
private JFrame frame;
private JList list;
private JList list_1;
Make sure you're initialising the instance variables and not creating new local variables...
//JList list = new JList();// implements ActionListener;
list = new JList();// implements ActionListener;
//...
panel.add(list);
//JList list_1 = new JList();
list_1 = new JList();
//...
panel_1.add(list_1);
This now means that the JLists are accessible from within the context of an instance of the class...
Then in your ActionListeners, you can simple do something like...
Object selected = list.getSelectedValue();
or...
int index = list.getSelectedIndex();
You can then use these values to modify the state of the underlying ListModel...if it supports those operations...
I would like to programmatically expand a particular JMenuItem in a JPopup. For example in the code below
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
public class AutoExpandSubMenusDemo extends JFrame {
private final JPopupMenu popup = new JPopupMenu("Popup");
public AutoExpandSubMenusDemo() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
JMenu menuB = new JMenu("B");
menuB.add(new JMenuItem("X"));
JMenuItem menuY = menuB.add(new JMenuItem("Y"));
menuB.add(new JMenuItem("Z"));
popup.add(new JMenuItem("A"));
popup.add(menuB);
popup.add(new JMenuItem("C"));
final JButton button = new JButton("Show Popup Menu");
button.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
popup.show(button, 0, button.getHeight());
// Show menuY
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(button);
getContentPane().add(buttonPanel);
}
public static void main(String[] args) {
AutoExpandSubMenusDemo f = new AutoExpandSubMenusDemo();
f.setSize(500, 300);
f.setVisible(true);
}
}
I would like to expand the popup menu so that the items B(menuB)/Y(menuY) are expanded and selected when the button is pressed.
Sorry if this is something that's easy to do but I've searched around and can't figure it out.
I did find the
MenuSelectionManager.defaultManager().setSelectedPath(...)
however this didn't work when I tried it and the javadoc specifies that it is called from the LaF and should not be called by clients.
Any help is much appreciated.
While I don't recommend doing this, since the documentation itself advises against it, here's how you could do it:
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.MenuElement;
import javax.swing.MenuSelectionManager;
import javax.swing.SwingUtilities;
public class AutoExpandSubMenusDemo extends JFrame {
private final JPopupMenu popup = new JPopupMenu("Popup");
public AutoExpandSubMenusDemo() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
final JMenu menuB = new JMenu("B");
menuB.add(new JMenuItem("X"));
final JMenuItem menuY = menuB.add(new JMenuItem("Y"));
menuB.add(new JMenuItem("Z"));
popup.add(new JMenuItem("A"));
popup.add(menuB);
popup.add(new JMenuItem("C"));
final JButton button = new JButton("Show Popup Menu");
button.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
popup.show(button, 0, button.getHeight());
SwingUtilities.invokeLater(new Runnable() {
public void run() {
menuB.setPopupMenuVisible(true);
MenuSelectionManager.defaultManager().setSelectedPath(new MenuElement[]{popup, menuB, menuY});
}
});
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(button);
getContentPane().add(buttonPanel);
}
public static void main(String[] args) {
AutoExpandSubMenusDemo f = new AutoExpandSubMenusDemo();
f.setSize(500, 300);
f.setVisible(true);
}
}
Most of this code is yours. I only added:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
menuB.setPopupMenuVisible(true);
MenuSelectionManager.defaultManager().setSelectedPath(new MenuElement[]{popup, menuB, menuY});
}
});
which seems to work.
You could avoid abusing MenuSelectionManager via 'MenuItem.setArmed(boolean)'.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
menuB.setPopupMenuVisible(true);
menuB.setArmed(true);
menuY.setArmed(true);
}
});
The popup staying visible after selecting another menu item or dismissing the JPopupMenu still needs to be addressed though.
Another way is to fake a mouse event... :D
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MouseEvent event = new MouseEvent(
menuB, MouseEvent.MOUSE_ENTERED, 0, 0, 0, 0, 0, false);
menuB.dispatchEvent(event);
menuY.setArmed(true);
}
});
This way it is as if the user actually used the mouse.
Another example:
MenuSelectionManager.defaultManager().setSelectedPath(
new MenuElement[] {popup, menuB, menuB.getPopupMenu()});
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AutoExpandSubMenusDemo2 extends JFrame {
private final JPopupMenu popup = new JPopupMenu("Popup");
public AutoExpandSubMenusDemo2() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
final JMenu menuB = new JMenu("B");
menuB.add(new JMenuItem("X"));
final JMenuItem menuY = menuB.add(new JMenuItem("Y"));
menuB.add(new JMenuItem("Z"));
popup.add(new JMenuItem("A"));
popup.add(menuB);
popup.add(new JMenuItem("C"));
JPanel buttonPanel = new JPanel();
buttonPanel.add(new JButton(new AbstractAction("Show menuB Popup") {
#Override public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
popup.show(button, 0, button.getHeight());
//[Bug ID: JDK-6949414 JMenu.buildMenuElementArray() endless loop]
//( http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6949414 )
//menuB.doClick();
MenuSelectionManager.defaultManager().setSelectedPath(
new MenuElement[] {popup, menuB, menuB.getPopupMenu()});
}
}));
buttonPanel.add(new JButton(new AbstractAction("Select menuY") {
#Override public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
popup.show(button, 0, button.getHeight());
MenuSelectionManager.defaultManager().setSelectedPath(
new MenuElement[] {popup, menuB, menuB.getPopupMenu(), menuY});
}
}));
getContentPane().add(buttonPanel);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new AutoExpandSubMenusDemo2();
f.setSize(500, 300);
f.setVisible(true);
}
}
Ok so I'm trying to get familier with Java, and I've made a simple thing where if you click a button then some text appears. How can I make it so the button and label are created in one class file, and put the code for when the button is clicked in another? Sorry if it sounds like a silly question.
Pastebin code:
package com.nate.derp;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Derp {
private JFrame frmHello;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Derp window = new Derp();
window.frmHello.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Derp() {
initialize();
}
public void initialize() {
frmHello = new JFrame();
frmHello.setTitle("Hello");
frmHello.setBounds(100, 100, 225, 160);
frmHello.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmHello.getContentPane().setLayout(null);
final JLabel helloLabel = new JLabel("Hello World!");
helloLabel.setVisible(false);
helloLabel.setBounds(40, 89, 145, 16);
frmHello.getContentPane().add(helloLabel);
final JButton btnClickMe = new JButton("Click Me!");
btnClickMe.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
helloLabel.setVisible(true);
}
});
btnClickMe.setBounds(54, 29, 117, 29);
frmHello.getContentPane().add(btnClickMe);
}
}
You can do this by creating a JButton and adding an ActionListener, which can be implemented by another class.
So you first create the JButton:
Jbutton button = new JButton("hello");
Then add the Actionlistener:
button.addActionListener(new MyListener());
Where MyListener is your implementation class
class MyListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
...
}
}