I'm trying to center a JMenu's popup so I can use it on a JPanel and it doesn't look off. Here is some code that demos what I am trying to do:
import javax.swing.*;
public class Menu extends JMenu{
public static void main(String[] args) {
JFrame f = new JFrame("Menu Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
menuBar.add(new Menu());
JPanel background = new JPanel();
background.add(menuBar);
f.setContentPane(background);
f.setSize(250, 100);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public Menu() {
super("I'm a Menu");
add(new JMenuItem("Can This Popup be Centered?"));
add(new JMenuItem("Not To the Right?"));
}
}
Here's the current output
Here's what I want (or close to)
If there is a better way to do this other than using a JMenu, please let me know.
Thanks.
I figured out the answer. I override processMouseEvent to know when the menu was clicked, and than simply set the location of the popup menu relative to the location of the menu.
#Override
protected void processMouseEvent(MouseEvent e) {
super.processMouseEvent(e);
if(e.getID() == MouseEvent.MOUSE_PRESSED)
getPopupMenu().setLocation(
getLocationOnScreen().x+getWidth()/2-getPopupMenu().getWidth()/2,
getLocationOnScreen().y+getHeight());
}
Related
In a sample program I have one class that places:
GUI components on a JPanel which is inside a JFrame.
A method makeMenu to create a menu bar
An ActionListener inside the makeMenu method to change the JPanels background color when called.
Main method.
public class GUI extends JFrame {
private JPanel jPanelRight;
private JPanel jPanelLeft;
JMenuBar menuBar;
JMenu file, help;
JMenuItem changeColor;
public GUI() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setJMenuBar(makeMenu()); // call constructor to create the menu
this.setSize(800, 600); // set frame size
this.setVisible(true); // display frame
this.setTitle("understanding objects");
setLayout(new BorderLayout()); // layout manager
jPanelLeft = new JPanel(); //left jpanel
jPanelLeft.setPreferredSize(new Dimension(400, 800)); // to set the size of the left panel
jPanelLeft.setBackground(Color.blue);
jPanelRight = new JPanel(); //right jpanel
jPanelRight.setPreferredSize(new Dimension(400, 600)); // to set the size of the right panel
jPanelRight.setBackground(Color.green);
this.add(jPanelLeft, BorderLayout.WEST); //add jpanel to the left side of the frame
this.add(jPanelRight, BorderLayout.EAST); //add jpanel to the right side of the frame
}//end constructor
public JMenuBar makeMenu() {
menuBar = new JMenuBar(); //menu bar
file = new JMenu("File"); //menu item
menuBar.add(file);
help = new JMenu("Help"); //menu item
menuBar.add(help);
changeColor = new JMenuItem("Change Colour"); //sub menu item
changeColor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jPanelRight.setBackground(Color.red);
}
});
file.add(changeColor);
return menuBar;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GUI();
}
});
} // end
}//end class
I am trying to separate the code into 3 or 4 classes.
GUI class
ActionListener class
MakeMenu class
Main class (to run program)
one problem that keeps occurring is that i when i separate the code i can only change using System.out.println(); and can not change the GUI i.e. i can print out that the jPanelRight is now red but can not actually change the jPanelRight to red.
I am possibly going about this the wrong way.
A GUI to use a different class to create its menu and another different class to control the actions for the GUI's menu.
I'm trying to make a little game that will first show the player a simple login screen where they can enter their name (I will need it later to store their game state info), let them pick a difficulty level etc, and will only show the main game screen once the player has clicked the play button. I'd also like to allow the player to navigate to a (hopefully for them rather large) trophy collection, likewise in what will appear to them to be a new screen.
So far I have a main game window with a grid layout and a game in it that works (Yay for me!). Now I want to add the above functionality.
How do I go about doing this? I don't think I want to go the multiple JFrame route as I only want one icon visible in the taskbar at a time (or would setting their visibility to false effect the icon too?) Do I instead make and destroy layouts or panels or something like that?
What are my options? How can I control what content is being displayed? Especially given my newbie skills?
A simple modal dialog such as a JDialog should work well here. The main GUI which will likely be a JFrame can be invisible when the dialog is called, and then set to visible (assuming that the log-on was successful) once the dialog completes. If the dialog is modal, you'll know exactly when the user has closed the dialog as the code will continue right after the line where you call setVisible(true) on the dialog. Note that the GUI held by a JDialog can be every bit as complex and rich as that held by a JFrame.
Another option is to use one GUI/JFrame but swap views (JPanels) in the main GUI via a CardLayout. This could work quite well and is easy to implement. Check out the CardLayout tutorial for more.
Oh, and welcome to stackoverflow.com!
Here is an example of a Login Dialog as #HovercraftFullOfEels suggested.
Username: stackoverflow Password: stackoverflow
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
public class TestFrame extends JFrame {
private PassWordDialog passDialog;
public TestFrame() {
passDialog = new PassWordDialog(this, true);
passDialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new TestFrame();
frame.getContentPane().setBackground(Color.BLACK);
frame.setTitle("Logged In");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
});
}
}
class PassWordDialog extends JDialog {
private final JLabel jlblUsername = new JLabel("Username");
private final JLabel jlblPassword = new JLabel("Password");
private final JTextField jtfUsername = new JTextField(15);
private final JPasswordField jpfPassword = new JPasswordField();
private final JButton jbtOk = new JButton("Login");
private final JButton jbtCancel = new JButton("Cancel");
private final JLabel jlblStatus = new JLabel(" ");
public PassWordDialog() {
this(null, true);
}
public PassWordDialog(final JFrame parent, boolean modal) {
super(parent, modal);
JPanel p3 = new JPanel(new GridLayout(2, 1));
p3.add(jlblUsername);
p3.add(jlblPassword);
JPanel p4 = new JPanel(new GridLayout(2, 1));
p4.add(jtfUsername);
p4.add(jpfPassword);
JPanel p1 = new JPanel();
p1.add(p3);
p1.add(p4);
JPanel p2 = new JPanel();
p2.add(jbtOk);
p2.add(jbtCancel);
JPanel p5 = new JPanel(new BorderLayout());
p5.add(p2, BorderLayout.CENTER);
p5.add(jlblStatus, BorderLayout.NORTH);
jlblStatus.setForeground(Color.RED);
jlblStatus.setHorizontalAlignment(SwingConstants.CENTER);
setLayout(new BorderLayout());
add(p1, BorderLayout.CENTER);
add(p5, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
jbtOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (Arrays.equals("stackoverflow".toCharArray(), jpfPassword.getPassword())
&& "stackoverflow".equals(jtfUsername.getText())) {
parent.setVisible(true);
setVisible(false);
} else {
jlblStatus.setText("Invalid username or password");
}
}
});
jbtCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
parent.dispose();
System.exit(0);
}
});
}
}
I suggest you insert the following code:
JFrame f = new JFrame();
JTextField text = new JTextField(15); //the 15 sets the size of the text field
JPanel p = new JPanel();
JButton b = new JButton("Login");
f.add(p); //so you can add more stuff to the JFrame
f.setSize(250,150);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Insert that when you want to add the stuff in. Next we will add all the stuff to the JPanel:
p.add(text);
p.add(b);
Now we add the ActionListeners to make the JButtons to work:
b.addActionListener(this);
public void actionPerforemed(ActionEvent e)
{
//Get the text of the JTextField
String TEXT = text.getText();
}
Don't forget to import the following if you haven't already:
import java.awt.event*;
import java.awt.*; //Just in case we need it
import java.x.swing.*;
I hope everything i said makes sense, because sometimes i don't (especially when I'm talking coding/Java) All the importing (if you didn't know) goes at the top of your code.
Instead of adding the game directly to JFrame, you can add your content to JPanel (let's call it GamePanel) and add this panel to the frame. Do the same thing for login screen: add all content to JPanel (LoginPanel) and add it to frame. When your game will start, you should do the following:
Add LoginPanel to frame
Get user input and load it's details
Add GamePanel and destroy LoginPanel (since it will be quite fast to re-create new one, so you don't need to keep it memory).
I am coding Java Swing Calculator in NetBeans. I have JFrame, calculator buttons and JTextField called display. I need to support the copy (and also CTRL+C) option. Does anyone have an idea on how to do this?
If you want to add a right-click menu for cut/copy/paste, you can use the Cut/Copy/Paste actions that your components already have, although I prefer to rename them to give them simpler easier to read names, since it's easier to read "Cut" rather than "cut-to-clipboard".
For instance, if you call this method and pass in any text component, it should add a right-click pop-up menu for cut-copy-paste:
// allows default cut copy paste popup menu actions
private void addCutCopyPastePopUp(JTextComponent textComponent) {
ActionMap am = textComponent.getActionMap();
Action paste = am.get("paste-from-clipboard");
Action copy = am.get("copy-to-clipboard");
Action cut = am.get("cut-to-clipboard");
cut.putValue(Action.NAME, "Cut");
copy.putValue(Action.NAME, "Copy");
paste.putValue(Action.NAME, "Paste");
JPopupMenu popup = new JPopupMenu("My Popup");
textComponent.setComponentPopupMenu(popup);
popup.add(new JMenuItem(cut));
popup.add(new JMenuItem(copy));
popup.add(new JMenuItem(paste));
}
For example:
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.text.JTextComponent;
public class AddCopyAndPaste extends JPanel {
private JTextField textField = new JTextField("Four score and seven years ago...");
private JTextArea textArea = new JTextArea(15, 30);
public AddCopyAndPaste() {
addCutCopyPastePopUp(textField);
addCutCopyPastePopUp(textArea);
setLayout(new BorderLayout());
add(textField, BorderLayout.PAGE_START);
add(new JScrollPane(textArea), BorderLayout.CENTER);
}
// allows default cut copy paste popup menu actions
private void addCutCopyPastePopUp(JTextComponent textComponent) {
ActionMap am = textComponent.getActionMap();
Action paste = am.get("paste-from-clipboard");
Action copy = am.get("copy-to-clipboard");
Action cut = am.get("cut-to-clipboard");
cut.putValue(Action.NAME, "Cut");
copy.putValue(Action.NAME, "Copy");
paste.putValue(Action.NAME, "Paste");
JPopupMenu popup = new JPopupMenu("My Popup");
textComponent.setComponentPopupMenu(popup);
popup.add(new JMenuItem(cut));
popup.add(new JMenuItem(copy));
popup.add(new JMenuItem(paste));
}
private static void createAndShowGui() {
AddCopyAndPaste mainPanel = new AddCopyAndPaste();
JFrame frame = new JFrame("Add Copy And Paste");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I would like that when I click on a button it open a Frame containing a combo box, but the frame does not appears. I'm using AWT.
public class ActionF extends Frame implements ActionListener {
public void actionPerformed(ActionEvent evt) {
setLayout(null);
setBackground(Color.blue);
setBounds(100, 200, 900, 450);
Choice choice = new Choice();
choice.addItem("Choice 1");
choice.addItem("Choice 2");
choice.addItem("Choice 3");
add(choice);
setVisible(true);
}
}
Can you tell me what's wrong?
Thanks in advance.
The code you provided is missing some essential information, e.g. the button that is supposed to open your frame.
A shot in the dark: Could it be possible, that you forgot to add the ActionListener to the actual button instance? This should do it:
public static void main(String[] args) {
Frame f = new Frame();
Button button = new Button();
ActionF actionF = new ActionF();
button.addActionListener(actionF);
f.add(button);
f.setVisible(true);
}
i want to add icons in jframe which does some action while click like buttons.
You'll probably want to create a JLabel with an Icon and add a MouseListener to the JLabel, like so:
import javax.swing.*;
import java.awt.event.*;
public class Foo {
public static void main(String args[]) {
// Create a "clickable" image icon.
ImageIcon icon = new ImageIcon("path/to/image.jpg");
JLabel label = new JLabel(icon);
label.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
System.out.println("CLICKED");
}
});
// Add it to a frame.
JFrame frame = new JFrame("My Window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
}
You can create a JButton which takes an icon as a parameter and displays it.
JButton
I highly suggest trying that out first. Hopefully that will help