Java in NetBeans - Adding actionEvents with custom parameters - java

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.

Related

How do you append both pre-established text and user responses into a text area in Java?

I will do my best to explain-- I am trying to make a choose-your-own-adventure type game while using a TextField and a TextArea, where what is written in the TextField is appended into the TextArea (this I know how to do via ActionListener).
However, I need to have the TextArea start with a pre-written 'intro', which asks the user at the end if they want to continue or not. Therefore, I need it to be able to scan the user's response ('yes' or 'no') and choose the appropriate selection of pre-written text to follow.
I don't want to overwrite what is already in the TextArea, I want to add to it. I suppose what I'm confused about it how I'm supposed to lay out the entire file so that it functions properly, because the different choices for the adventure span different methods. Having
"String text = textField.getText();" only within the actionPerformed method means I can't use 'text' elsewhere, but moving that line up with my other variables tells me it can't reference the field before it's defined.
I am fairly new to Java and am working on this as a project for a non-programming school course. I've been through many iterations thus far and this is what seems to be my final attempt, as I've remade it repeatedly and don't have much time left. :(
Your questions/comments and my attempts to answer:
I am trying to make a choose-your-own-adventure type game while using a TextField and a TextArea, where what is written in the TextField is appended into the TextArea (this I know how to do via ActionListener).
As per my comment, be sure to create a Swing GUI which would use a JTextField and a JTextArea. You would then add your java.awt.event.ActionListener to the JTextArea, and the ActionListener would respond whenever the user pressed <ENTER> within the JTextField.
However, I need to have the TextArea start with a pre-written 'intro', which asks the user at the end if they want to continue or not. Therefore, I need it to be able to scan the user's response ('yes' or 'no') and choose the appropriate selection of pre-written text to follow.
This can be done easily, but sounds as if you may be trying to shoe-horn a linear console type program into a GUI. If so, consider reconsidering your program design since what works best for one often doesn't work well for another. If you do re-write, then you should consider redoing most including your program flow, but excepting perhaps the "model" portion of your previous program, the "business logic" that underlies everything.
I don't want to overwrite what is already in the TextArea, I want to add to it. I suppose what I'm confused about it how I'm supposed to lay out the entire file so that it functions properly, because the different choices for the adventure span different methods. Having "String text = textField.getText();" only within the actionPerformed method means I can't use 'text' elsewhere, but moving that line up with my other variables tells me it can't reference the field before it's defined.
Again as per comments a JTextArea has an append(String text) method that will add new text to existing text that is already displayed in your JText Area. So on that note, your ActionListener's actionPerformed method could be very simple and look something like:
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
textArea.append(text):
}
Although you may need to add line feeds, "\n" either before and/or after the text you are going to append.

How to make GUI wait for user input? [duplicate]

This question already has an answer here:
How to stop Java from running the entire code with out waiting for Gui input from The user
(1 answer)
Closed 5 years ago.
I'm a rather basic programmer who has been assigned to make a GUI program without any prior experience with creating a GUI. Using NetBeans, I managed to design what I feel the GUI should look like, and what some of the buttons should do when pressed, but the main program doesn't wait for the user's input before continuing. My question is, how do I make this program wait for input?
public class UnoMain {
public static void main(String args[]) {
UnoGUI form = new UnoGUI(); // GUI class instance
// NetBeans allowed me to design some dialog boxes alongside the main JFrame, so
form.gameSetupDialog.setVisible(true); // This is how I'm trying to use a dialog box
/* Right around here is the first part of the problem.
* I don't know how to make the program wait for the dialog to complete.
* It should wait for a submission by a button named playerCountButton.
* After the dialog is complete it's supposed to hide too but it doesn't do that either. */
Uno Game = new Uno(form.Players); // Game instance is started
form.setVisible(true); // Main GUI made visible
boolean beingPlayed = true; // Variable dictating if player still wishes to play.
form.playerCountLabel.setText("Players: " + Game.Players.size()); // A GUI label reflects the number of players input by the user in the dialog box.
while (beingPlayed) {
if (!Game.getCompleted()) // While the game runs, two general functions are repeatedly called.
{
Player activePlayer = Game.Players.get(Game.getWhoseTurn());
// There are CPU players, which do their thing automatically...
Game.Turn(activePlayer);
// And human players which require input before continuing.
/* Second part of the problem:
* if activePlayer's strategy == manual/human
* wait for GUI input from either a button named
* playButton or a button named passButton */
Game.advanceTurn();
// GUI updating code //
}
}
}
}
I've spent about three days trying to figure out how to integrate my code and GUI, so I would be grateful if someone could show me how to make this one thing work. If you need any other information to help me, please ask.
EDIT: Basically, the professor assigned us to make a game of Uno with a GUI. There can be computer and human players, the numbers of which are determined by the user at the beginning of the game. I coded the entire thing console-based at first to get the core of the game to work, and have since tried to design a GUI; currently this GUI only displays information about the game while it's running, but I'm not sure how to allow the code to wait for and receive input from the GUI without the program charging on ahead. I've investigated other StackOverflow questions like this, this, this, or this, but I cannot comprehend how to apply the answers to my own code. If possible, I'd like an answer similar to the answers in the links (an answer with code I can examine and/or use). I apologize if I sound demanding or uneducated and confusing; I've been working diligently on this project for a couple weeks and it's now due tomorrow, and I've been stressing because I can't advance until I figure this out.
TL;DR - How do I get my main program to wait and listen for a button click event? Should I use modal dialog boxes, or is there some other way to do it? In either case, what code needs to be changed to do it?
Unlike console based programming, that typically has a well defined execution path, GUI apps operate within a event driven environment. Events come in from the outside and you react to them. There are many types of events that might occur, but typically, we're interested in those generate by the user, via mouse clicks and keyboard input.
This changes the way an GUI application works.
For example, you will need to get rid of your while loop, as this is a very dangerous thing to do in a GUI environment, as it will typically "freeze" the application, making it look like your application has hung (in essence it has).
Instead, you would provide a serious of listeners on your UI controls that respond to user input and update some kind of model, that may effect other controls on your UI.
So, to try and answer your question, you kind of don't (wait for user input), the application already is, but you capture that input via listeners and act upon them as required.

Almost done...one problem with an error JPaneOption box

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.

java: fully controlled input on JTextField

I want to have a JTextField (or another text-like input which supports focus and a cursor -- or maybe I should code my own?) where I want to have full control over the immediate input. I.e. I want to ignore most inputs and handle the rest specifically. It seems that JFormattedTextField is not what I want because it does the verification not on the immediate input but when the focus is lost.
I tried to add a key listener but it's a bit non-obvious how I should use it. It seems I can catch up events like cursor changes (via keys) or copy/paste (via key-shortcuts) in keyPressed and I can catch all normal key input in keyTyped. I am not sure how I can catch cursor changes or copy/paste made via mouse (for some reason, right click does not work anyway, so copy/paste via mouse in the context menu seems not possible but I am not sure if that might be a different issue or if it should work and just does not for some reason).
I basically want something like the following handler:
interface InputHandler {
void addStringAt(int pos, String s);
void deleteSubString(int pos, int len);
void setFocusTo(int pos);
}
And it should be absolutely impossible for the user to get any stuff onto the textbox which are not going through this handler.
Right now, it seems like I have to take care about a lot of specific cases (like on some architectures, there may be some context menu where they could copy/paste or input something, handle all mouse events manually, etc).
Or the other way, which also involves a lot of special handlings: To recode such input field myself. This still seems saver because I can know for sure that there are no tricky methods how the user could bypass the handler (and I really must know that for sure). Btw., how would I do this? I thought of extending a JLabel. How can I extend it so that it can get a focus?
I wonder how you would implement something like this.
It sounds like you need a DocumentFilter. A couple of existing questions that will help with this:
Cut and Paste in JTextArea
Help on writing your own javax.swing.text.Document

Switching from GUI to Command Prompt in Java?

My professor assigned a project where a simulation is ran through a GUI. To edit it, we need to create a "New" menu item. We haven't learned how to get data from a GUI, and our book does not cover it at all.
What I'm trying to do, is when the "New" command is hit, focus gets shifted back to the CMD prompt, where System.out. starts working again and prompts the user for input.
However, when I try to implement this, my program crashes. What can I do to solve this problem?
It doesn't look like you're keeping the reference to your newly created GUI. As far as I remember, Java will garbage collect the FoxGui object (as well as any other object) if there are no references to that object. Try creating a global variable to store the reference to your newly created FoxGui object. Something like...
FoxGui MyGUIRef;
public void actionPerformed(ActionEvent event)
{
System.out.println("Item: " + event.getActionCommand());
// File Menu Controls
if (event.getActionCommand().equals("New"))
{
MyGUIRef = runNew();
}
}
//Now returns a reference to FoxGui
private FoxGui runNew()
{
return new FoxGui(....)
}
Is the System.out in a terminal (non Java) window? If so, I think this would be much harder than you'd think.
I'd be tempted to redirect the System.in / System.out to a JTextPane on the GUI (That way, it would be much easier to change the focus etc. I think you need to try and explain what you're doing a little better in your question and perhaps post a stack trace when your program crashes.
Anyway, to do something when the "new" menu item is clicked you'd need to do:
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Code here to be performed when the item is clicked
}
});
You know what? I found a real simple solution, JOptionPane. I just needed to find a good example. It'll work fine for what I want. Thanks for all the help. I'll checkmark everyone who helped.
I know that it is very late answer, but anywhere...
There is only one way to do exactly what you want.
First you need to remember to run you project from CMD by java -jar jarname.jar
Catch click action and perform system.in
Information:
It is the only solution, because GUI never give focus to CMD, but if GUI runned from CMD you can use easily System.in.
Regards, Greg

Categories