Only one active new jframe - java

I have two forms : f_main and f_recruitment. I put a label in f_main with this code :
....
private void jLabel2MouseClicked(java.awt.event.MouseEvent evt) {
JOptionPane.showMessageDialog (null, "Recruitment Icon has been Clicked");
new F_Recruitment().setVisible(true);
}
// to display f_recruitment
Question is how can I have just one active f_recruitment open?
Update:
Thanks, what I mean is, how can I prevent user from re-click jLabel2 and another f_recruitment are open..? ( I let f_main form keep visible on purpose, while the new form f_recruitment is open)

I agree completely with glowcoder (1+), that more information would be helpful and perhaps essential to competently answering this question, but another option is to use lazy initiation -- to create an F_Recruitment variable field that's null, and instantiate it in the listener if it's null, but regardless of whether it was initially null or not, at the bottom of the listener display the field.
public class MyClass {
private F_Recruitment fRecruitment = null;
// ... more code goes here
private void jLabel2MouseClicked(java.awt.event.MouseEvent evt) {
JOptionPane.showMessageDialog (null, "Recruitment Icon has been Clicked");
if (fRecruitment == null) {
fRecruitment = new F_Recruitment();
}
fRecruitment.setVsible(true);
}

I really don't think there is enough information here to really answer your question.
You say you want just one active f_recruitment, but that implies there are more than one f_recruitment.
You could consider a toggle method:
private void toggleRecruitmentOn() {
f_main.setVisible(false);
f_recruitment.setVisible(true);
}
private void toggleMainOn() {
f_recruitment.setVisible(false);
f_main.setVisible(true);
}
I'll update this if more information gets posted about the issue at hand :)

Related

removeEvent ItemListener (removeItemListener) from within itemStateChanged doesn't work (StackOverfowError)

I have the following code, I cannot use setEnabled(false), because I need to set the background- and foregroundcolor.
public class RadioButton extends JRadioButton implements ItemListener {
public RadioButton(String text)
{
super(text);
addItemListener(this);
}
public void itemStateChanged(ItemEvent e) {
synchronized (this) {
removeItemListener(this);
if (e.getStateChange() == ItemEvent.SELECTED) {
System.out.println("item is selected true [changed]");
setSelected(false);
} else if (e.getStateChange() == ItemEvent.DESELECTED) {
System.out.println("item is selected false [changed]");
setSelected(true);
}
addItemListener(this);
}
}
}
This should be a radio button, that can't be changed. Hoever if I try testing the code, it gives me an endless loop printing
item is selected true [changed]
once...
...and then always
item is selected false [changed]
until there is a Java StackOverflowError.
How can this be? Is the disabling of the ItemListener not working?
If you can then please also show me, how to pack this into a lamda function. I got a illegal self reference-error, when trying to put this into a lamda function.
Please correct me, if the title is not correct.
As MadProgrammer pointed out, disabling the AbstractButton (aka RadioButton or Checkbox) can be archieved by setting the ButtonModel to a custom one always returning a constant value.
MainClass:
radioButtonOrCheckbox.setModel(new ButtonCustomModel(true));
ButtonCustomModel:
public class ButtonModel implements javax.swing.ButtonModel {
protected boolean state;
public ButtonModel(boolean state)
{
this.state = state;
}
#Override
public boolean isSelected() {
return state;
}
#Override
public boolean isEnabled() {
return true;
}
// other methods of ButtonModel-interface
[...]
}
I cannot use setEnabled(false), because I need to set the background- and foregroundcolor
This is probably just purely a personal thing, but I have a distinct dislike or UI's which don't conform to establish norms and user expectations.
So, when a button shouldn't be interacted with, it should be disabled. This is a convention that a user understands immediately.
I change the background-color and foreground-color for the evaluation-radiobuttons and -checkboxes.
Okay, so you want to decorate the buttons in some way, fair enough
It is clear from context that they are not meant to be checked by the user
To you perhaps, I'd probably be madly trying to click it, but I'm just that kind of user ;)
Okay, so with just a little but of paying around with the UIManager's default values, it's possible to take more control over how some elements are rendered, for example...
UIManager.put("RadioButton.disabledText", Color.BLUE);
JRadioButton rb = new JRadioButton("Test");
rb.setOpaque(true);
rb.setBackground(Color.RED);
rb.setForeground(Color.BLUE);
rb.setEnabled(false);
add(rb);
UIManager.put("CheckBox.disabledText", Color.RED);
JCheckBox cb = new JCheckBox("Test");
cb.setOpaque(true);
cb.setBackground(Color.BLUE);
cb.setForeground(Color.RED);
cb.setEnabled(false);
add(cb);
Now, this is just a quick hack.
For me, I might consider doing something different to highlight the correct answer, maybe fading or removing the other questions or use a LineBorder to highlight the correct answer or use a JLabel and nice big green tick or red cross, as some simple idea off the top of my head.

error: local variables referenced from an inner class must be final or effectively final

I am working with swings. This is the code I used to make a frame for logout which would return a int value and using that value other operation could be performed in the previous function. But I am getting an error. How should I solve it?
public int logout()
{
int s=0;
JFrame main=new JFrame("Logout");
Dimension d=Toolkit.getDefaultToolkit().getScreenSize();
main.setSize(d.width/2,d.height/3);
main.setLayout(new FlowLayout());
JButton yes=new JButton("Yes");
main.add(yes); main.setVisible(true);
yes.addActionListener(new ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent e)
{
s=1;
main.setVisible(false);
}
});
return s;
}
What do you expect your program to do?
The code you wrote, tries to do:
Create a "logout" frame with a "yes" button.
Return from the logout() method with the value of the s variable.
When later the user presses the "yes" button, you prepared an action listener to then set the s variable to 1 - but that can't work, as you already returned from the logout() method, and the variable s no longer even exists.
So, be happy that the compiler told you about a problem.
I suppose you want to wait for the user's logout approvement. Then use JOptionPane methods (the Java tutorials will help you how to do that correctly).
And by the way: get into the habit of formatting and indenting your code properly. It wasn't fun reading your code.
Use the JOptionPane class to create a confirm dialog by using one of the showConfirmDialog() method to show a confirm dialog. Please read the Java tutorial How to Make Dialogs on how to create such dialogs. The source code should look something like this:
int choice = JOptionPane.showConfirmDialog(your_main_frame,
"Do you want to logout?",
"Logout?",
JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.YES_OPTION) {
// "Yes" clicked
} else {
// "No" clicked
}

how can one make a JComboBox dropdown when it is given focus?

I find that a useful way to draw attention to a jcombobox when one wants the user to select from it is to make it drop down at the point it gains focus usually when the previous item has been completed by the user.
How can this been done in Java?
You could do:
comboBox.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
comboBox.showPopup();
}
});
You want JComboBox#setPopupVisible
Add in a FocusListener to monitor for focus gained and you should be right.
Depending on if the combo box is editable or not, you may need to add a focus listener to the editor as well
rightclick on the combo box. go to events ---> mouse ----> mouseentered.
it will take you to :
private void jComboBox1MouseEntered(java.awt.event.MouseEvent evt) {}
inside the curly braces, type: jComboBox1.showPopup();
it should look like:
private void jComboBox1MouseEntered(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
jComboBox1.showPopup();
}

prevent java from multiple openings of the same window-JFrame

for example i create this on click
//this creates autor object with default constructor properties defined in autor class
menuAutor.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
autor Autor = new autor("Autor");
}
});
so object named Autor is created, and when i click again on the button, it pops up again the same Autor object.. how can prevent opening the same window if one is already opened?
EDIT: FINALY A SOLUTION!
After lots of thinking about this.. i made my solution...
default value for autorOpen="no" i declaired at the beginning of my class, just to let you know because its not visible in code below, the solution itself:
public void mouseClicked(MouseEvent e)
{
if(autorOpen=="no") {
autor Autor = new autor("Autor");
autorOpen = "yes";
Autor.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
autorOpen = "no";
}
});
}
else
JOptionPane.showMessageDialog(null, "Demo notice... you can't open that window again.. its opened already!","Error",JOptionPane.ERROR_MESSAGE);
}
});
Store the variable a little bit more globally, and check whether it exists before creating a new one.
You could also consider implementing Autor as a singleton class (to ensure only one is ever instantiated).
public class Autor {
private static Autor instance = null;
//Must be protected or private, get a reference to this class with getInstance().
protected Autor() {
}
/**
* Returns reference to this class - use in place of constructor
*/
public static Autor getInstance() {
if(instance == null) {
instance = new Autor();
}
return instance;
}
}
Use a boolean flag to indicate if the dialog is up or not. Set it to true if the dialog is popped up, and set it to false when you close that dialog.
If you're creating something with 'new' on each click, you'll get a new window each time. One solution is to create autor before any clicks happen, then have the event move it from hidden to visible.

Java: How can I detect the user has finalised their save name without using an actionListener?

Basically I wan't to obtain a string from the user, I have created a class called "frames" in which I have a load of methods such as exitChoice(), infoPop(), ect... I wish to create one called getText(), and this is what I have so far:
public String getText()
{
JDialog textBox = new JDialog(frame, "Save Name", true);
JTextField inputField = new JTextField(18);
inputField.setText(save == null ? "new save" : save.saveName);
textBox.setBounds(width, height, 275, 70);
textBox.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
textBox.setLayout(new FlowLayout());
textBox.setAlwaysOnTop(true);
textBox.setResizable(false);
textBox.add(inputField);
textBox.setVisible(true);
return inputField.getText();
}
now I know this won't work, It simply gets the game stuck and I have to terminate it externally, I also understand why it doesn't work, that isn't the problem, I also know how to add a JButton, an action listener and work it from there,
Basically I am trying to create a clean simple method which obtains a String from the user which is ALL contained within the method.
Ideally I would like to write a line which reads along the lines of
//EDIT: I know the method getText() does exist, sorry if it is misleading, I will ammend it
//String saveName = new JTextField.getText();
String saveName = new JTextInputGetterBoxThing();
but as far as I have found so far this doesn't appear to exist, does anybody have any ideas? or ideally know of a one liner that I have missed?
I think what you want is the JOptionPane.showInputDialog method. Something like this?
public class GetUserInput {
public static String getUserInput() {
return JOptionPane.showInputDialog("Type Something");
}
public static void main(String[] args) {
System.out.println("User Input: " + getUserInput());
}
}
This shows a dialog with the prompt "Type Something" and a text field for entry. Whatever the user types in the text field is returned by getUserInput().
Honestly I'm not sure of having fully understood your problem. Anyway,
here's a tutorial on how to make dialogs properly in Swing.
If you use
int ret = JOptionPane.showOptionDialog(new JDialog(), ...);
Your application main frame input is blocked until the JDialog showed is closed.
If you don't want to use an ActionListener or something similare (DocumentListener, ...) you can force the user to insert a value in the JTextField, press the ok button and the when showOptionDialog return, manually retrieve the text of the JTextField with getText().
EDIT:
I try to extend my answer a little bit.
Extends a JDialog to create the desired dialog:
public class CustomDialog extends JDialog{
private JPanel panel;
private JTextField field;
public CustomDialog(){
panel = new JPanel(); //create a panel possibly with a LayoutManager
field = new JTextField();
}
public JTextField getField(){
return this.field;
}
}
Then show the dialog where you need it, and check the field text when it returns:
CustomDialog dialog = new CustomDialog();
int ret = JOptionPane.showOptionDialog(dialog, ...);
String text = dialog.getField().getText();
public String getSaveName()
{
boolean textGot = false;
String returnText = null;
while (!textGot)
{
returnText = (String) JOptionPane.showInputDialog(hub.frame, "Enter the name of your save:\n", "Save Box",
JOptionPane.PLAIN_MESSAGE, null, null, save == null ? "new save" : save.saveName);
if ((returnText != null) && (returnText.length() > 0))
{
textGot = true;
}
}
return returnText;
}
Here is the final method I am using, much cleaner than the old setup I had which involved creating a tiny frame, and adding a textfield and a button with a listener!

Categories