I have an application that is developed in Java swing and the NetBens 7 IDE
Steps:
I want to use a Jbutton to perform two different functions depending on the user mode.
for example I want to label a single button with the following text "New Record" and
"Exit New Record"
The default text is the "New Record". This will enable the user enter new record.
Whiles in the new record mode, the text on the jButton changes to "Exit New Record".
To exit the new record mode the user clicks on the same button to exit.
This will then change the text on button to the default enter "Enter New Record"
Is there any suggestion on how to do this with the netbeans IDE or do I manually
override a method?
Implement Action Listener on JButton (code not tested, just for your hint):
public class MyButton extends JButton implements ActionListener{
boolean pressed = false;
public MyButton(String name){
super(name);
this.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e){
if(pressed){
pressed = !pressed;
_change_text_on_button_
_do_job_
}
}
Than use customized MyButton.
As shown in examples here and here, a button's text can be changed in its ActionListener. The NetBeans GUI editor generates the code to invoke the ActionListener, but it lets you edit the code in the method that is called. The method name will be something like nameActionPerformed().
See also How to Use Buttons, Check Boxes, and Radio Buttons and this suggestion.
Related
I am working with a java swing form that contains a JTextField. The text field needs input validation , validation is performed when the field losses focus . i.e clicking anyware apart from the field itself.
The form also contains a JButton to clear(cancel) the form . Now whenever I press the cancel button and the Textfield is the currently focused component the validation function is invoked. This should not happen.
I have tried InputVerifier and Focuslistener
Is there a way I can know what component caused the focus to change ?
This is fine but the form contains a JButton to clear(cancel) the form
You can use:
clearButton.setVerifyInputWhenFocusTarget(false);
to prevent the InputVerifier from being invoked when you click on the button.
You can use a FocusListener to react to a focusLost event. There you can retrieve the destination of the focus via getOppositeComponent() from the FocusEvent. If the destination is the clear/cancel/whatever button do nothing, otherwise validate.
A very basic example for this:
JTextField textField = new JTextField(15);
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent e) {
Component comp = e.getOppositeComponent();
if (comp instanceof JButton) {
JButton button = (JButton) comp;
String buttonText = button.getText();
if (buttonText.equals("Cancel")) {
return;
}
}
// do the validation
System.out.println("validate");
}
});
Actually camickr's solution is a lot simpler than mine above. I had no idea that there was built in solution for this.
BACKGROUND INFO: I want to make a 9x9 grid of buttons that act as empty beds. All buttons say "Add bed" and when clicked open up a window to write data about the occupant. Once saved the button will change to an occupied bed image.
QUESTION: Is it possible to create an event listener that does the same thing for each button, but applies it to the button being pressed? Im new to java but I understand that good code should be able to do this in a few lines rather than 100+
CODE:
//button1 (inside the gui function)
addBed1 = new JButton("Add bed"); //button 1 of 9
addBed1.addActionListener(new room1Listener());
class room1Listener implements ActionListener{
public void actionPerformed(ActionEvent event){
addBed1.setText("Adding bed..);
addBedGui(); //Generic window for adding bed info.
}
}
Is it possible to create an event listener that does the same thing for each button, but applies it to the button being pressed? Im new to java but I understand that good code should be able to do this in a few lines rather than 100+
Absolutely. In fact you can create one ActionListener object and add this same listener to each and every button in a for loop. The ActionListener will be able to get a reference to the button that pressed it via the ActionEvent#getSource() method, or you can get the JButton's actionCommand String (usually its text) via the ActionEvent#getActionCommand() method.
e.g.,
// RoomListener, not roomListener
class RoomListener implements ActionListener{
public void actionPerformed(ActionEvent event){
AbstractButton btn = (AbstractButton) event.getSource();
btn.setText("Adding bed..);
addBedGui(); //Generic window for adding bed info.
}
}
and
RoomListener roomListener = new RoomListener();
JButton[] addButtons = new JButton[ADD_BUTTON_COUNT];
for (int i = 0; i < addButtons.length; i++) {
addButtons[i] = new JButton(" Add Bed "); // make text big
addButtons[i].addActionListener(roomListener);
addBedPanel.add(addButtons[i]);
}
I am developing a Java Swing App, and I want to use JRadioButton objects to show state. I don't want the user to have the ability to select them. If I use the button's .setEnabled(false) method, the radio button is greyed out.
I don't want the Radio Button to grey out. Is there a way to override this?
Well You Could Do Something Like:
boolean rButtonEnabled = false;
JRadioButton rButton = new JRadioButton();
rButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
rdbtnNewRadioButton.setSelected(rButtonEnabled);
}
});
It's not the prettyist solution, but I hope it helps.
To store the new value perhaps you can create a new class extending JRadioButton.
While this does not use the .setEnabled(), it is effectively the same
Basically I'm making a music player in Java using Eclipse, and I have a JButton on the main GUI called "add song" - the user clicks this and another JFrame appears, allowing the user to click "browse" and select an mp3 file from the computer. I then store the data as a musicFile object I created, and I want to send this information back to the main function. My code for the "add song" action listener is the following:
private ActionListener song(final JButton button)
{
return new ActionListener(){
public void actionPerformed(ActionEvent event)
{
addSongGUI addSong = new addSongGUI(); //the JFrame that opens
//once the user presses the "add song" button
listOfSongs.add(addSong.musicFile); //the addSongGUI has a musicFile variable that I want to read and get information from
String songName = addSong.musicFile.getSongName();
//... and do more stuff
}
};
}
When this runs, "String songName = addSong.musicFile.getSongName();" gives me a null pointer exception, because it tries to read the musicFile from the addSongGUI right away, before the user can pick a song to set the musicFile. So, how can I wait until the user picks a song, closes the window, and then have this line of code read (what can I do to get rid of this null pointer exception)? Thanks.
As noted, the correct and easy solution is not to display a JFrame when you want a modal dialog -- use a modal JDialog instead:
private ActionListener song(final JButton button) {
return new ActionListener(){
public void actionPerformed(ActionEvent event) {
// AddSongDialog is a modal JDialog
AddSongDialog addSong = new AddSongDialog(mainJFrame);
addSong.setVisible(true); // show it -- this pauses flow of code here
String songName = addSong.musicFile.getSongName();
//... and do more stuff
}
};
}
Again, addSongDialog is a modal JDialog, which is why you would need to pass in the application's main JFrame into it, since the JFrame (or parent JDialog) will be needed when calling the JDailog's super constructor in your constructor.
An alternative and far weaker solution is to use a JFrame and add a WindowListener to it, but why do that when the JDialog solution works so easily and simply?
I have the following situatation:
I have a Java Swing application.
In the class that implement my GUI I have a button named Log Out tath is binding to an event listener that handle the click event, something like it:
JButton logOutButton = new JButton("LogOut");
header.add(logOutButton);
Then in the same class that implement my GUI I have declared the ActionListener that handle this event using an inner class:
logOutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("logOutButton clicked !!!");
System.exit(0);
}
});
In this moment when I click the logOutButton button the program end. I would that instead exit it is restarted by running a specific class called LoginForm (the class that implement the login form GUI)
What can I do to do this thing?
Tnx
Andrea
You don't really need to close/open window junky approach at all. Just use Card Layout:
set Frame's content pane's layout to card layout.
getContentPane().setLayout(new CardLayout());
Put your different Form's content code inside different panel and
add them to the content pane with their corresponding name, for example:
getContetnPane().add(logInFormPanel, "logIn Form");
Now you can simulate the card to appear whenever necessary by calling CardLayout.show(Container parent, String name). For example:
logOutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("logOutButton clicked !!!");
CardLayout cl = (CardLayout)(getContentPane().getLayout());
cl.show(getContentPane(), "logIn Form");
}
});
Check out a CardLayout demo from my another answer.