My question is the inverse of this one: Is there a way to only have the OK button in a JOptionPane showInputDialog (and no CANCEL button)?
One solution to that was (if I read correctly) to add an arbitrary JPanel, in that instance a label. My problem is that I need a JComboBox object in the message window, and (in the same way that solved Coffee_Table's problem) having the JComboBox seemingly removes the cancel button. It doesn't matter if I replace YES_NO_CANCEL_OPTION with OK_CANCEL_OPTION or QUESTION_MESSAGE.
I'm still at the mindless-copying stage of learning about the JOptionPane family, so I presume the solution is obvious and I just don't know it because I haven't seen any specific examples to mindlessly copy. (Which also means that once I learn how to add a cancel button, I'll need to work on how to access whether the user hit it. EDIT: And I'm half-sure how I'd do it, so you don't need to answer it if you don't want to.)
public static void main(String[] args) {
int numCh1 = 1;
String[] moves = {"rock","paper","scissors"};
JComboBox<?> optionList = new JComboBox<Object>(moves);
JOptionPane.showMessageDialog(
null,
optionList,
"Player One: Choose a Move",
JOptionPane.YES_NO_CANCEL_OPTION
);
numCh1 = optionList.getSelectedIndex();
System.out.println(moves[numCh1]);
}
Note: The combo box is non-negotiable (as opposed to, say, three buttons) because my actual project is to simulate rps101; I just figured you didn't need to see all 100 moves (or anything else irrelevant to this question).
You're using the showMessageDialog() method, which shows just that: a message. It doesn't have a cancel option. For that, use one of the other methods.
In fact, that last parameter isn't even valid. It's not looking for an option type like you provided, it's looking for a message type (ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, or PLAIN_MESSAGE).
As always, the API is your best friend: http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
Related
I have an issue where I am trying to make "player" icon move around my JFrame using keyboard controls. I have one object that I want to move around with the w, a, s, and d keys. I am using key bindings because in my research it seems that they are better suited to this task.
I have managed to attach all the desired keys to my icon, and they all call the action, the only issue is that I have no way to distinguish which button is being pressed. I was hoping this could be accomplished in some way by using the getActionCommand() on my action event. So far it hasn't worked.
Other examples that I have seen seem to have a solution to this, but they also have a lot of extra code with few comments, making it extremely difficult to determine what is actually happening. They all seem to involve multiple classes, with methods and fields. I am hoping to make this code a little less involved.
What I want to know: What is the best way to get this to work? Can I do it with key bindings? Does it need to be really complicated?
I really appreciate any help, even if it's just sources that I can use to help find an answer on my own.
Here's my existing code:
//My method that gets called by the constructor
//This is all based on a tutorial I found: ftp://ecs.csus.edu/clevengr/133/handouts/UsingJavaKeyBindings.pdf
//player is just an image icon
public static void setUpKeys() {
InputMap playerMap = player.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
KeyStroke wKey = KeyStroke.getKeyStroke('w');
KeyStroke aKey = KeyStroke.getKeyStroke('a');
KeyStroke sKey = KeyStroke.getKeyStroke('s');
KeyStroke dKey = KeyStroke.getKeyStroke('d');
KeyStroke wSprint = KeyStroke.getKeyStroke((char) ('w' + KeyEvent.SHIFT_DOWN_MASK)); //As a side note, what's the best way to get it to move faster when the shift key is held down? Not that important, but if someone happens to know, that'd be great
playerMap.put(wKey, "moveUp");
playerMap.put(aKey, "moveLeft");
playerMap.put(sKey, "moveDown");
playerMap.put(dKey, "moveRight");
playerMap.put(wSprint, "moveFast");
ActionMap playerAction = player.getActionMap();
playerAction.put("moveUp", playerMoved);
playerAction.put("moveLeft", playerMoved);
playerAction.put("moveDown", playerMoved);
playerAction.put("moveRight", playerMoved);
playerAction.put("moveFast", playerMoved);
}
And here is my playerMoved action:
static Action playerMoved = new AbstractAction() {
//This isn't important, just put it in instead of suppressing the warning
private static final long serialVersionUID = 2L;
//This doesn't do anything yet, just gives console confirmation
public void actionPerformed(ActionEvent e) {
System.out.println("Activated");
//Here's what I was talking about with the getActionCommand() not working
if (e.getActionCommand().equals("moveUp")) {
System.out.println("up");
}
}
};
If anyone needs any other parts of my code, I can provide it. I just wanted to cut it down to what I feel is important for this question
I was hoping this could be accomplished in some way by using the getActionCommand() on my action event.
You don't want to do this because you would be attempting to use the "action command" for "processing". That is not a good design as it will result in nested if/else statements.
Instead you need to create an Action that accepts parameters to control the movement. So you will need 4 separate Actions to control the movement. See the MotionWithKeyBindings example found in Motion Using the Keyboard, for a complete working example of this approach.
It demonstrates how a simple Action can be made reusable by specifying parameters for the Action. This provides far more flexibility than your current Action.
Note 1:
You use the following debug code in your Action:
System.out.println("Activated");
Instead of simply displaying a hard coded value it would be better to do something like
System.out.println( e.getActionCommand() );
In which case you should notice the value is "a, s, w, d", which is the KeyStroke you use to invoke the Action.
So this would mean the if statement should be testing for either of the above characters, not the String "moveUp" which is the String used to identify the Action in the ActionMap.
However, as mentioned above, this is not the solution you should be using, I just wanted to better explain how the "action command" is determined.
Note 2:
The only time you might want to use a single Action and the getActionCommand() method is when you want to use the "action command" as "data" for the Action.
For an example of this approach check out: how to put actionlistenerand actioncommand to multiple jbuttons. It is an example of a simple numeric entry panel where the number key pressed is added to a text field. So therefore the key character becomes the data for the text field and no special processing is required.
I have a problem about modify button background. I am using netbeans gui builder for build form. I am trying change button background when the second frame is open and turn it back when second frame close.
public void update(boolean x){
if(x==true){
circleButton.setOpaque(true);
circleButton.setBackground(new java.awt.Color(0, 0, 0));
System.out.println("testoutput");
}
}
this is my update method from first class.
I added window listener to second frame.
private void formWindowOpened(java.awt.event.WindowEvent evt) {
isitopen = true;
//this is first class which includes button
homework hwork = new homework();
hwork.update(isitopen);
System.out.println("testoutput2");
}
I got 2 testoutput but color of the button didn't change.
What can i do to fix this issue ?
You're creating a new homework object in your formWindowOpened(...) method, one completely unrelated to the homework object that is displayed, and changing the state of the new object will have no effect on the displayed one.
A simple and WRONG solution is to use static fields or methods.
Instead one simple solution is to give the calss with your formWindowOpened(...) method a valid reference to the displayed homework object, something that can be done with a constructor parameter or a setHomework(...) method.
A much better and even simpler solution:
Make the 2nd window a modal JDialog, not a JFrame
This way homework will know when the window is open and can set its own button colors. When the 2nd window opens, program flow in the calling class is put on hold, and only resumes when the 2nd window closes -- just like using a JOptionPane.
For more on this, please see The Use of Multiple JFrames, Good/Bad Practice?
As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
I'm working on something in NetBeans, and I want to create an actionListener in a jTextPane for when the user presses Enter. However, I also need to input a String array (from a different subroutine within the source code) into the listener. But in NetBeans, events are generated automatically and I'm not allowed to edit this apparently extremely sensitive code. So, then, I tried typing up my own event thing (sorry about my terminology; I'm very new to GUI programming):
private void jTextPaneEnterPressed(KeyEvent evt, String[] stringArray)
{
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER)
{
// do something when the user presses enter that involves the program knowing what stringArray is
}
}
But when I run the program, pressing Enter in the text pane does nothing. I understand that this is because there is no actionListener associated with jTextPaneEnterPressed, but NetBeans gives no option for such customized code.
So what I want to know is either how I can pass in my own parameters when NetBeans creates an event handler, or how I can write my own actionListener alongside this actionPerformed block.
(And for the record, this is not an import problem)
I have tried looking this up, but have found nothing specific, as all other similar issues are not relevant to NB. Any help would be greatly appreciated.
*EDIT: This may seem like a trivial problem to most, but I'm open to any actual answers that tell me how to get done what I am trying to do, though I would prefer to stick with NetBeans. All I need is for the action listener to know that this string array exists, because the program needs to deal with that array when the user presses Enter. I'm sorry I can't give any specific context, but it's too much to get into.
I wanted a button to show a pop-up window, I tried using the
JOptionPane.showMessageDialog(null,"");
But I can't put my desired object such as the Table and List. Is it possible?
This is really poorly documented in the Java Docs, because all that tells you is that the "message" parameter is an Object, which can be anything - but does not go into specifics about what happens with different types of objects that may warrant special case handling.
As far as I have gathered from experimenting with it, the "message" can be a subtype of Component - then it will just place the component in the message area of the dialog box as-is, like:
JOptionPane.showMessageDialog(null, new JCheckBox("I'm a checkbox!"));
Otherwise, it will just call the toString method on the object, converting it into a string, which it then will just wrap in a label and place that in the dialog as the message.
But you can also pass in an Array of Objects, in which case it will just place each element in a separate row in the message area:
JOptionPane.showMessageDialog(null, new Object[] {
new JCheckBox("check"),
new JRadioButton("radio"),
"plain text"});
There might be other special cases, but I haven't found them yet.
That said, if what you want to display is a subclass of Component (or JComponent), just passing it in as the message parameter should work. If it doesn't, you might want to edit your question to describe whatever problems you are encountering in more detail, perhaps also providing some sample code.
Start by taking a closer look at the JOptionPane JavaDocs, showMessageDialog clearly states that it accepts a Object as the message parameter
One of the nice features of this, is if the Object is Component, it will be added to the dialog.
For example: JOptionPane displaying HTML problems in Java and How do i make the output come in different columns?
I've almost got my asignment done. Yayy! But.... I have two problems in my handler. For one, I have a public void itemStateChanged(ItemEvent e) method that is supposed to print a registrants name to a text field, plus the type of registration he is (student, business, complimentary). I have this working, only it prints twice to the text area. I don't get that. Also, there is a 'calculate charges' button which is used to...well, calculate the charges. When the button is clicked, the action event is supposed to check to make sure that a combo box (in a class called regPanel) does not have "Please select a registration type" which is element 0 in an object array. The way I have it now, if I don't pick something from the combobox (leaving it on element 0), I get the error message, but then the program prints to the textfield anyways. It is not supposed to. It is only supposed to print the error box, then allow the user to make the proper selections. Any advice would be appreciated. Here is the class:
public class ConferenceHandler implements ActionListener, FocusListener, ItemListener
{
protected final static String ERROR_TEXT = "Please enter a name";
protected ConferenceGUI gui; //reference the ConferenceGUI panel
/**Constructor*/
public ConferenceHandler(ConferenceGUI gui) {this.gui = gui;}
if (gui.regPanel.getRegType() == "Please select a type")
JOptionPane.showMessageDialog(null, "Please select a registration type",
"Type Error",JOptionPane.ERROR_MESSAGE);
//prints to textarea if registrant will be attending keynote or not
else if (gui.regPanel.regCheckBox.isSelected())
gui.textArea.append("\nKeynote address will be attended");
else
Did a little more googling, and figured out the problem with the double firing of the itemStateChanged affair. Trimmed all of the extra code out, because I'm pretty sure that all I need is a loop of some sort around here. When I put a while or do-while loop, all that happens is the JOptionPane comes up and won't go away. I need to validate that the user has entered an appropriate checkbox selection, though.
I have this working, only it prints twice to the text area.
You still haven't posted a SSCCE that demonstrates the problem as you where asked in a previoius question.
Copying and pasting a few lines of code from your real problem does not help you isolate the problem.
As a beginner, you need to learn how to simplify problems. Once you simplify the problem it is easier to find and solve the problem.
In this case a working SSCCE will be about 20 lines of code. A couple lines to create the GUI, a few more to add the compnonents and a few more to create the ItemListener.
Post your SSCCE and I'll post the answer to your question. This is a common mistake when working with an ItemListener. I could probably give you the answer without seeing your SSCCE, but you need to learn how to create a SSCCE for when you encounter more complex problems. So this question is a good place to start.
Maybe looking at the section from the Swing tutorial on How to Write an Item Listenerwill help you understand what is happening.