Can someone tell me if it is possible to nest the
if(e.getActionCommand().equals("some String"){//do it}
For example. . . .
public void actionPerformed(ActionEvent e)
{
theFrame.hide();
if(e.getActionCommand().equals("Button in theFrame"))
{
newFramerz.show();
if (e.getActionCommand().equals("Button in newFramerz"))
{
//do usual stuff
}
}
}
For some reason, my code was not working when I tried to compile it. Then I suspected the line of code which I've written at the topmost part.
Can anyone tell me if it is possible? An explaination would also be great.
EDIT
Here's a sample code of my problem.
public void ATM_MainMenu()
{
//-----------------------------//
MainMenu = new JFrame("Main Menu");
JPanel TextPanel = new JPanel();
JPanel BTPanel = new JPanel();
JPanel FormPanel = new JPanel();
JLabel TextLabel = new JLabel("Choose Transaction");
JButton InquireBalBT = new JButton("Inquire Balance");
InquireBalBT.addActionListener(this);
JButton DepositBT = new JButton("Deposit");
DepositBT.addActionListener(this);
JButton WithdrawBT = new JButton("Withdraw");
WithdrawBT.addActionListener(this);
TextPanel.setBackground(Color.white);
TextPanel.add(TextLabel);
BTPanel.add(TextPanel);
BTPanel.add(InquireBalBT);
BTPanel.add(DepositBT);
BTPanel.add(WithdrawBT);
FormPanel.setLayout(new GridLayout(2,1));
FormPanel.add(TextPanel);
FormPanel.add(BTPanel);
MainMenu.setContentPane(FormPanel);
MainMenu.pack();
MainMenu.show();
MainMenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MainMenu.setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
MainMenu.hide();
if(e.getActionCommand().equals("Inquire Balance") || e.getActionCommand().equals("Withdraw") || e.getActionCommand().equals("Deposit"))
{
//----------------------------------//
PINEnter = new JFrame("PIN");
JPanel PINTextPanel = new JPanel();
JPanel PINButtonPanel = new JPanel();
JPanel PINUniterPanel = new JPanel();
JLabel PINTextLabel = new JLabel("Please Enter PIN");
JTextField PINField = new JTextField(4);
JButton SubmitBT = new JButton("Submit PIN");
SubmitBT.addActionListener(this);
PINTextPanel.setBackground(Color.white);
PINTextPanel.add(PINTextLabel);
PINTextPanel.add(PINField);
PINButtonPanel.add(SubmitBT);
PINUniterPanel.setLayout(new GridLayout(2,1));
PINUniterPanel.add(PINTextPanel);
PINUniterPanel.add(PINButtonPanel);
PINEnter.setContentPane(PINUniterPanel);
PINEnter.setSize(360,140);
PINEnter.pack();
PINEnter.show();
PINEnter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PINEnter.setResizable(false);
PINNow = PINField.getText();
if(e.getActionCommand().equals("Inquire Balance")){OPTIONS = 1;}
else if(e.getActionCommand().equals("Withdraw")){OPTIONS = 3;}
else if(e.getActionCommand().equals("Deposit")){OPTIONS = 2;}
if(e.getActionCommand().equals("Submit PIN") && PINNow.equals(RealPin))
{ // switch and then some functions which are too long}
}
}
}
This is the code I'm working on, an ATM-Simulator. The only problem is when I get to PINEnter and then I would press the SubmitBT, It would not go to the other frames. PINEnter had a JTextField PINField and I should convert the content into a String PIN. In order to go to the other frames, PIN should be equal to String RealPin which is "1234". So if the Submit PIN button and PIN is equal to RealPin then it should be going on already with the other functions. I expected that when SubmitBT is pressed, with the PIN the same as RealPIN I should be going to the if statements but then, It didn't.
While syntactically you can do it - and it will compile, I don't think it will do what you're looking for. Let's look at your code:
if(e.getActionCommand().equals("Button in theFrame"))
{
newFramerz.show();
// If you got in here, then the value of e.getActionCommand() is "Button in theFrame"
if (e.getActionCommand().equals("Button in newFramerz"))
{
//The execution will never get here, because
//the value of e.getActionCommand() is "Button in theFrame"
//and hence will never be equal to "Button in newFramerz"
}
}
A more appropriate way of dealing with it would be:
String action = e.getActionCommand();
if(action.equals("Button in theFrame"))
{
newFramerz.show();
//whatever else
}
else if(action.equals("Button is newFramerz"))
{
//do something else
}
Related
I made a calculator and to increase its functionality and simplicity i made three frames which support simple , scientific and conversion calculator
calculator works perfect till i use it once but when i change my calculator type from simple to scientific and scientific to conversion and then again to simple calculator , program doesn't do anything at all , jbutton doesn't perform any action even actionPerformed is getting called i checked that by putting println statement in method actionPerformed.
i instantiate my three frames in constructor and i'd made three methods each for calculator type to instantiating and adding buttons and other stuff to JPanels and adding panels to JFrame
//Constructor
public Calculator()
{
//instantiating buttons
buttons = new JButton[15];
optionButtons = new JButton[5];
scientificOptionButtons = new JButton[20];
constantButtons = new JButton[5];
//instantiating calculatorFrames
simpleCalculatorFrame = new JFrame("Calculator");
scientificCalculatorFrame = new JFrame("Scientific Calculator");
convertCalculatorFrame = new JFrame("Conversion Calculator");
} // end of the constructor
when i choose calculator type from my JMenuItems i dispose the active frame and call other calculatortype methods for creating and adding stuff to panels and setting up frame like
//if statements inside method actionPerformed to check which type of calculator should run
if(event.getSource() == scientificMenuItem)
{
if(simpleCalculatorFrame.isActive())
{
simpleCalculatorFrame.dispose();
scientificCalculatorBuilder();
}
else if(convertCalculatorFrame.isActive())
{
convertCalculatorFrame.dispose();
scientificCalculatorBuilder();
}
}
else if(event.getSource() == simpleMenuItem)
{
if(scientificCalculatorFrame.isActive())
{
scientificCalculatorFrame.dispose();
simpleCalculatorBuilder();
}
else if(convertCalculatorFrame.isActive())
{
convertCalculatorFrame.dispose();
simpleCalculatorBuilder();
}
}
else if(event.getSource() == convertMenuItem)
{
if(simpleCalculatorFrame.isActive())
{
simpleCalculatorFrame.dispose();
convertCalculatorBuilder();
}
else if(scientificCalculatorFrame.isActive())
{
scientificCalculatorFrame.dispose();
convertCalculatorBuilder();
}
}
else if(event.getSource() == exitMenuItem)
{
System.exit(0);
}
everything looks fine just not getting where the problem is
here's code of my methods which instantiates the components
public void simpleCalculatorBuilder()
{
//instantiating menuBar , fileMenu and menuItems and adding functionality
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
scientificMenuItem = new JMenuItem("Scientific Calculator");
convertMenuItem = new JMenuItem("Conversion Calculator");
convertMenuItem.addActionListener(handler);
scientificMenuItem.addActionListener(handler);
exitMenuItem = new JMenuItem("Exit");
exitMenuItem.addActionListener(handler);
menuBar.add(fileMenu);
fileMenu.add(scientificMenuItem);
fileMenu.add(convertMenuItem);
fileMenu.add(exitMenuItem);
//instantiating and adding textField appearing at the top of calculator to show ongoing processes and results
myField = new JTextField();
myField.setPreferredSize(new Dimension(this.getWidth() , 40));
myField.setEditable(false);
simpleCalculatorFrame.add(myField , BorderLayout.NORTH);
//instantiating panels to hold buttons
buttonsPanel = new JPanel(new GridLayout(5 , 3 , 3 , 6));
optionButtonsPanel = new JPanel(new GridLayout(5, 1 , 3 , 3));
//loop to add buttons to panel , adding eventListeners to buttons , setting background color of buttons
for(int i = 0 ; i<buttons.length ; i++)
{
buttons[i] = new JButton(buttonTitles[i]);
buttons[i].setBackground(Color.BLACK);
buttons[i].setForeground(Color.WHITE);
buttons[i].addActionListener(handler);
buttons[i].addMouseListener(handler);
buttonsPanel.add(buttons[i]);
if(i<5)
{
optionButtons[i] = new JButton(optionButtonTitles[i]);
optionButtons[i].setBackground(Color.BLACK);
optionButtons[i].setForeground(Color.WHITE);
optionButtons[i].addActionListener(handler);
optionButtons[i].addMouseListener(handler);
optionButtonsPanel.add(optionButtons[i]);
}
}
//setting background color of panels
buttonsPanel.setBackground(Color.DARK_GRAY);
optionButtonsPanel.setBackground(Color.DARK_GRAY);
//adding items and panels to the frame and setting the simpleCalculatorFrame
simpleCalculatorFrame.setJMenuBar(menuBar);
simpleCalculatorFrame.add(buttonsPanel , BorderLayout.CENTER);
simpleCalculatorFrame.add(optionButtonsPanel , BorderLayout.EAST);
simpleCalculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
simpleCalculatorFrame.setSize(240 , 270);
simpleCalculatorFrame.setLocationRelativeTo(null);
simpleCalculatorFrame.setVisible(true);
simpleCalculatorFrame.setResizable(false);
} // end of simple calculator builder
public void scientificCalculatorBuilder()
{
//instantiating menuBar , fileMenu and menuItems and adding functionality
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
simpleMenuItem = new JMenuItem("Simple Calculator");
simpleMenuItem.addActionListener(handler);
convertMenuItem = new JMenuItem("Conversion Calculator");
convertMenuItem.addActionListener(handler);
exitMenuItem = new JMenuItem("Exit");
exitMenuItem.addActionListener(handler);
menuBar.add(fileMenu);
fileMenu.add(simpleMenuItem);
fileMenu.add(convertMenuItem);
fileMenu.add(exitMenuItem);
//instantiating and adding textField appearing at the top of calculator to show ongoing processes and results
myField = new JTextField();
myField.setPreferredSize(new Dimension(this.getWidth() , 40));
myField.setEditable(false);
scientificCalculatorFrame.add(myField , BorderLayout.NORTH);
//instantiating panels to hold buttons
buttonsPanel = new JPanel(new GridLayout(5 , 3 , 3 , 6));
optionButtonsPanel = new JPanel(new GridLayout(5, 1 , 3 , 3));
scientificOptionButtonsPanel = new JPanel(new GridLayout(5 , 4 , 3 , 3));
constantButtonsPanel = new JPanel(new GridLayout(5, 1 , 3 , 3));
scientificPanelManager = new JPanel(new GridLayout(1 , 2));
//loop to add buttons to panel , adding eventListeners to buttons , setting background color of buttons
for(int i = 0 ; i<scientificOptionButtons.length ; i++)
{
if(i<5)
{
optionButtons[i] = new JButton(optionButtonTitles[i]);
optionButtons[i].setBackground(Color.BLACK);
optionButtons[i].setForeground(Color.WHITE);
optionButtons[i].addActionListener(handler);
optionButtons[i].addMouseListener(handler);
optionButtonsPanel.add(optionButtons[i]);
constantButtons[i] = new JButton(constantButtonTitles[i]);
constantButtons[i].setBackground(Color.BLACK);
constantButtons[i].setForeground(Color.WHITE);
constantButtons[i].addActionListener(handler);
constantButtons[i].addMouseListener(handler);
constantButtonsPanel.add(constantButtons[i]);
}
if(i<15)
{
buttons[i] = new JButton(buttonTitles[i]);
buttons[i].setBackground(Color.BLACK);
buttons[i].setForeground(Color.WHITE);
buttons[i].addActionListener(handler);
buttons[i].addMouseListener(handler);
buttonsPanel.add(buttons[i]);
}
scientificOptionButtons[i] = new JButton(scientificOptionButtonTitles[i]);
scientificOptionButtons[i].setBackground(Color.BLACK);
scientificOptionButtons[i].setForeground(Color.WHITE);
scientificOptionButtons[i].addActionListener(handler);
scientificOptionButtons[i].addMouseListener(handler);
scientificOptionButtonsPanel.add(scientificOptionButtons[i]);
}// end of for loop
//setting background color of panels
buttonsPanel.setBackground(Color.DARK_GRAY);
optionButtonsPanel.setBackground(Color.DARK_GRAY);
scientificOptionButtonsPanel.setBackground(Color.DARK_GRAY);
constantButtonsPanel.setBackground(Color.DARK_GRAY);
scientificPanelManager.add(scientificOptionButtonsPanel);
scientificPanelManager.add(buttonsPanel);
scientificCalculatorFrame.setJMenuBar(menuBar);
scientificCalculatorFrame.add(constantButtonsPanel , BorderLayout.WEST);
scientificCalculatorFrame.add(optionButtonsPanel , BorderLayout.EAST);
scientificCalculatorFrame.add(scientificPanelManager , BorderLayout.CENTER);
scientificCalculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
scientificCalculatorFrame.setSize(580 , 300);
scientificCalculatorFrame.setLocationRelativeTo(null);
scientificCalculatorFrame.setVisible(true);
scientificCalculatorFrame.setResizable(false);
} // end of scientificCalculatorBuilder
//method which starts convertCalculatorFrame and initializes frame needs
public void convertCalculatorBuilder()
{
convertCalculatorTopPanel = new JPanel(new GridLayout(2 , 1 , 0 , 4));
convertCalculatorCenterPanel = new JPanel(new GridLayout(2 , 2 , 5 , 3));
convertCalculatorEastPanel = new JPanel(new GridLayout(2 , 1 ,1 , 3));
convertCalculatorSouthPanel = new JPanel(new GridLayout(1 , 2 , 5 , 2));
//instantiating menuBar , fileMenu and menuItems and adding functionality
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
simpleMenuItem = new JMenuItem("Simple Calculator");
simpleMenuItem.addActionListener(handler);
scientificMenuItem = new JMenuItem("Scientific Calculator");
scientificMenuItem.addActionListener(handler);
exitMenuItem = new JMenuItem("Exit");
exitMenuItem.addActionListener(handler);
menuBar.add(fileMenu);
fileMenu.add(simpleMenuItem);
fileMenu.add(scientificMenuItem);
fileMenu.add(exitMenuItem);
typeConvertCalculatorComboBox = new JComboBox<String>();
typeConvertCalculatorComboBox.setBackground(Color.BLACK);
typeConvertCalculatorComboBox.setForeground(Color.WHITE);
typeConvertCalculatorComboBox.setMaximumRowCount(3);
typeConvertCalculatorComboBox.addItem("Choose type of conversion");
typeConvertCalculatorComboBox.addItem("Distance Conversion");
typeConvertCalculatorComboBox.addItem("Memory Conversion");
typeConvertCalculatorComboBox.addItem("Temperature Conversion");
typeConvertCalculatorComboBox.addItem("Mass Conversion");
typeConvertCalculatorComboBox.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(typeConvertCalculatorComboBox.getSelectedItem() == "Distance Conversion")
{
fromConvertCalculatorComboBox.setEnabled(true);
toConvertCalculatorComboBox.setEnabled(true);
fromConvertCalculatorComboBox.removeAllItems();
fromConvertCalculatorComboBox.setMaximumRowCount(3);
fromConvertCalculatorComboBox.addItem("Centimeter(s)");
fromConvertCalculatorComboBox.addItem("Meter(s)");
fromConvertCalculatorComboBox.addItem("Kilometer(s)");
fromConvertCalculatorComboBox.addItem("Mile(s)");
toConvertCalculatorComboBox.removeAllItems();
toConvertCalculatorComboBox.setMaximumRowCount(2);
toConvertCalculatorComboBox.addItem("Centimeter(s)");
toConvertCalculatorComboBox.addItem("Meter(s)");
toConvertCalculatorComboBox.addItem("Kilometer(s)");
toConvertCalculatorComboBox.addItem("Mile(s)");
}
else if(typeConvertCalculatorComboBox.getSelectedItem() == "Memory Conversion")
{
fromConvertCalculatorComboBox.setEnabled(true);
toConvertCalculatorComboBox.setEnabled(true);
fromConvertCalculatorComboBox.removeAllItems();
fromConvertCalculatorComboBox.setMaximumRowCount(3);
fromConvertCalculatorComboBox.addItem("Kilobyte(s)");
fromConvertCalculatorComboBox.addItem("Megabyte(s)");
fromConvertCalculatorComboBox.addItem("Gigabyte(s)");
fromConvertCalculatorComboBox.addItem("Terabyte(s)");
toConvertCalculatorComboBox.removeAllItems();
toConvertCalculatorComboBox.setMaximumRowCount(2);
toConvertCalculatorComboBox.addItem("Kilobyte(s)");
toConvertCalculatorComboBox.addItem("Megabyte(s)");
toConvertCalculatorComboBox.addItem("Gigabyte(s)");
toConvertCalculatorComboBox.addItem("Terabyte(s)");
}
else if(typeConvertCalculatorComboBox.getSelectedItem() == "Temperature Conversion")
{
fromConvertCalculatorComboBox.setEnabled(true);
toConvertCalculatorComboBox.setEnabled(true);
fromConvertCalculatorComboBox.removeAllItems();
fromConvertCalculatorComboBox.addItem("Centigrade");
fromConvertCalculatorComboBox.addItem("Fahrenheit");
fromConvertCalculatorComboBox.addItem("Kelvin");
toConvertCalculatorComboBox.removeAllItems();
toConvertCalculatorComboBox.setMaximumRowCount(2);
toConvertCalculatorComboBox.addItem("Centigrade");
toConvertCalculatorComboBox.addItem("Fahrenheit");
toConvertCalculatorComboBox.addItem("Kelvin");
}
else if(typeConvertCalculatorComboBox.getSelectedItem() == "Mass Conversion")
{
fromConvertCalculatorComboBox.setEnabled(true);
toConvertCalculatorComboBox.setEnabled(true);
fromConvertCalculatorComboBox.removeAllItems();
fromConvertCalculatorComboBox.setMaximumRowCount(3);
fromConvertCalculatorComboBox.addItem("Milligram(s)");
fromConvertCalculatorComboBox.addItem("Pound(s) (lbs)");
fromConvertCalculatorComboBox.addItem("Kilogram(s)");
toConvertCalculatorComboBox.removeAllItems();
toConvertCalculatorComboBox.setMaximumRowCount(2);
toConvertCalculatorComboBox.addItem("Milligram(s)");
toConvertCalculatorComboBox.addItem("Pound(s) (lbs)");
toConvertCalculatorComboBox.addItem("Kilogram(s)");
}
}
}
);
fromConvertCalculatorComboBox = new JComboBox<String>();
fromConvertCalculatorComboBox.setMaximumRowCount(3);
fromConvertCalculatorComboBox.setBackground(Color.BLACK);
fromConvertCalculatorComboBox.setForeground(Color.WHITE);
fromConvertCalculatorComboBox.setEnabled(false);
toConvertCalculatorComboBox = new JComboBox<String>();
toConvertCalculatorComboBox.setMaximumRowCount(2);
toConvertCalculatorComboBox.setBackground(Color.BLACK);
toConvertCalculatorComboBox.setForeground(Color.WHITE);
toConvertCalculatorComboBox.setEnabled(false);
topConvertCalculatorLabel = new JLabel("What type of conversion you want ?");
topConvertCalculatorLabel.setForeground(Color.WHITE);
fromConvertCalculatorLabel = new JLabel("From");
fromConvertCalculatorLabel.setForeground(Color.WHITE);
toConvertCalculatorLabel = new JLabel("To");
toConvertCalculatorLabel.setForeground(Color.WHITE);
fromConvertCalculatorField = new JTextField();
fromConvertCalculatorField.setPreferredSize(new Dimension(120 , 2));
fromConvertCalculatorField.addActionListener(convertHandler);
ansConvertCalculatorField = new JTextField();
ansConvertCalculatorField.setEditable(false);
convertButton = new JButton("Convert");
convertButton.setBackground(Color.BLACK);
convertButton.setForeground(Color.WHITE);
convertButton.addMouseListener(handler);
convertButton.addActionListener(convertHandler);
convertCalculatorFrame.setJMenuBar(menuBar);
//adding components to panel and adding panels to frame
{
convertCalculatorTopPanel.add(topConvertCalculatorLabel);
convertCalculatorTopPanel.add(typeConvertCalculatorComboBox);
convertCalculatorTopPanel.setBackground(Color.DARK_GRAY);
convertCalculatorFrame.add(convertCalculatorTopPanel , BorderLayout.NORTH);
convertCalculatorCenterPanel.add(fromConvertCalculatorLabel);
convertCalculatorCenterPanel.add(fromConvertCalculatorComboBox);
convertCalculatorCenterPanel.add(toConvertCalculatorLabel);
convertCalculatorCenterPanel.add(toConvertCalculatorComboBox);
convertCalculatorCenterPanel.setBackground(Color.DARK_GRAY);
convertCalculatorFrame.add(convertCalculatorCenterPanel , BorderLayout.CENTER);
convertCalculatorEastPanel.add(fromConvertCalculatorField);
convertCalculatorEastPanel.setBackground(Color.DARK_GRAY);
convertCalculatorFrame.add(convertCalculatorEastPanel , BorderLayout.EAST);
convertCalculatorSouthPanel.add(convertButton);
convertCalculatorSouthPanel.add(ansConvertCalculatorField);
convertCalculatorSouthPanel.setBackground(Color.DARK_GRAY);
convertCalculatorFrame.add(convertCalculatorSouthPanel , BorderLayout.SOUTH);
convertCalculatorFrame.getContentPane().validate();
convertCalculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
convertCalculatorFrame.setSize(390 , 200);
convertCalculatorFrame.setLocationRelativeTo(null);
convertCalculatorFrame.setVisible(true);
convertCalculatorFrame.setResizable(false);
}
}//end of convertCalculatorBuilder
i dont have much experience in programming hope you people won't mind helping
here's an MCVE
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test {
public static void main(String[] args) {
Practice application = new Practice();
application.forFrame1();
}
}
class Practice extends JPanel
{
Handler handler = new Handler();
private JButton[] buttons;
private JButton[] moreButtons;
private JMenuBar menuBar;
private JMenu myMenu;
private JMenuItem firstItem;
private JMenuItem secondItem;
private JFrame frame1;
private JFrame frame2;
private JPanel panel1;
private JPanel panel2;
public Practice()
{
buttons = new JButton[3];
moreButtons = new JButton[5];
frame1 = new JFrame();
frame2 = new JFrame();
}
public void forFrame1()
{
menuBar = new JMenuBar();
myMenu = new JMenu("menu");
secondItem = new JMenuItem("goto 2nd frame");
secondItem.addActionListener(handler);
menuBar.add(myMenu);
myMenu.add(secondItem);
frame1.setJMenuBar(menuBar);
panel1 = new JPanel(new GridLayout(3 , 1));
for(int i = 0 ; i<buttons.length ; i++)
{
buttons[i] = new JButton(""+ i);
buttons[i].addActionListener(handler);
panel1.add(buttons[i]);
}
frame1.add(panel1);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setSize(200 , 200);
frame1.setVisible(true);
}
public void forFrame2()
{
menuBar = new JMenuBar();
myMenu = new JMenu("menu");
firstItem = new JMenuItem("goto 1st frame");
firstItem.addActionListener(handler);
menuBar.add(myMenu);
myMenu.add(firstItem);
frame2.setJMenuBar(menuBar);
panel2 = new JPanel(new GridLayout(1 , 5));
for(int i = 0 ; i<moreButtons.length ; i++)
{
moreButtons[i] = new JButton(""+ i);
moreButtons[i].addActionListener(handler);
panel2.add(moreButtons[i]);
}
frame2.add(panel2);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setSize(200 , 200);
frame2.setVisible(true);
}
private class Handler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == firstItem)
{
frame2.dispose();
forFrame1();
}
else if(event.getSource() == secondItem)
{
frame1.dispose();
forFrame2();
}
for(int i = 0 ; i< moreButtons.length ; i++)
{
if(i<buttons.length)
{
if(event.getSource() == buttons[i])
JOptionPane.showMessageDialog(null, "frame1 component working");
}
if(event.getSource() == moreButtons[i])
JOptionPane.showMessageDialog(null, "frame2 components working");
}
}
}
}
try using component after changing frame by choosing menuItem
I'm not going to go through all that code without an mcve, but your symptoms tell me the overall problem and the solution: you're re-building an already created JFrame, re-stuffing it with components, without removing old components, without unhooking old listeners, and the components then don't work. This suggests that something in the process of re-building an already built GUI is mucking up your functionality, and if so, the solution is to simply not do this. If you absolutely need to swap JFrames (a very annoying GUI design from a user's perspective by the way), then only create your GUI objects once, but display them multiple times if needed. In other words, call your builder methods just once, perhaps in the constructor, and in your button's ActionListener, don't call the builder methods but rather only the .setVisible(true) and .setVisible(false)
The bug that is causing your error is that you're adding components to an already filled JFrame and are not packing it, and so the old buttons are shown and are pressed, but their references don't match that of the new buttons. To see this for yourself, add one line to each of the forFrame1() and forFrame2() methods:
frame1.getContentPane().removeAll(); // ****** add this *****
frame1.add(panel1);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setSize(200, 200);
frame1.setVisible(true);
By removing all the old components, you all the new ones to be displayed and to function, and your code will work.
Having said this, I still feel that your design is off in several ways:
Myself, I'd swap JPanels to achieve the desired GUI change, but I wouldn't use a CardLayout since I'd want the container that holds the swapping JPanels to change sizes when the JPanel held has a different preferredSize. This means removing all components, adding new components, and re-packing the GUI.
If you must swap windows, then simply swap visibility, and don't re-create your windows as you're doing.
Other unrelated issues
Let the layout managers and components size themselves by not setting any sizes and by packing the GUI after creation.
I think you should use JFrame.setVisible(false) instead of JFrame.dispose()
I have an application that uses JDialog popups. I'm using 1.6 (compatibility requirement for the customer.) The ENTER key dismisses the dialog, taking previous results. The problem is that the user can type-ahead on hitting the ENTER key (or any other text for that matter).
Here's a snippet:
private void promptForCredentials(final GenericSwitch sw) {
final JDialog jd = new JDialog();
jd.setModal(true);
jd.getContentPane().setLayout(new FlowLayout());
final JLabel l_user = new JLabel("Username: ");
final JLabel l_pass = new JLabel("Password: ");
final JTextField tf_user = new JTextField(25);
final JTextField tf_pass = new JPasswordField(25);
JButton b_ok = new JButton("OK");
JButton b_same = new JButton("Same as previous");
JButton b_cancel = new JButton("Cancel");
final JLabel l_authfail = new JLabel("Authentication failed, try again.");
ActionListener okSameListener = new ActionListener() {
public void actionPerformed(ActionEvent ev) {
// if (((JButton) ev.getSource()).isVisible()) {
// return; // always returns for 'OK' button!
// }
String name = ((JButton) ev.getSource()).getText();
if (name.equals("OK")) {
// If user hits OK, save user/pw, unless they're both empty
// (treat that as "use last")
if (! tf_user.getText().isEmpty()
&& ! tf_pass.getText().isEmpty()) {
mLastUsername = tf_user.getText();
mLastPassword = tf_pass.getText();
}
}
jd.dispose();
sw.setUsername(mLastUsername, true);
sw.setPassword(mLastPassword, true);
if (!sw.checkLogin()) {
// auth failed so don't save for next time
mLastUsername = "";
mLastPassword = "";
}
display(sw.mIndex);
poll();
}
};
b_ok.addActionListener(okSameListener);
b_same.addActionListener(okSameListener);
b_cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
System.out.print("Poll cancelled\n");
abort();
jd.dispose();
}
});
Box box0 = Box.createHorizontalBox();
Box box1 = Box.createHorizontalBox();
Box box2 = Box.createHorizontalBox();
Box box3 = Box.createHorizontalBox();
box0.add(l_authfail);
box1.add(l_user);
box1.add(tf_user);
box2.add(l_pass);
box2.add(tf_pass);
box3.add(b_ok);
box3.add(Box.createHorizontalStrut(10));
if (!mLastUsername.isEmpty() && !mLastPassword.isEmpty()) {
box3.add(b_same);
box3.add(Box.createHorizontalStrut(10));
}
box3.add(b_cancel);
if (sw.authFailed()) {
jd.add(box0);
}
jd.add(box1);
jd.add(box2);
jd.add(box3);
SwingUtilities.getRootPane(b_ok).setDefaultButton(b_ok);
jd.setTitle("Login for " + sw.mShortname);
jd.setPreferredSize(new Dimension(400, 150));
jd.setSize(new Dimension(400, 150));
jd.setLocationRelativeTo(getContentPane());
jd.setVisible(true);
}
Since this app polls a number of external resources, most of which usually have the same username/pw, it's nice to just hit "enter" to cycle through the lot, the first time. All good. (And yeah, I know I should have "use same for subsequent" checkbox. Maybe later.)
However, I noticed to my surprise that I can type ahead. Frankly, I like this, but I don't think it's really appropriate for general users. How can I disable it?
Would it work to consume all actions prior to setting the JDialog visible? I tried checking if the button is visible, but while the Cancel button is, the OK button isn't! (commented out above)
Thanks
I want to change my JLabel when I click a JButton. It sounds simple but can't really find a good piece of code.
Here is part of my code:
final JButton continueGame = new JButton();
continueGame.setPreferredSize(new Dimension(1000, 30));
continueGame.setLocation(95, 45);
continueGame.setText("<html>Continue</html>");
continueGame.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ev) {
panel.remove(continueGame);
SwingUtilities.updateComponentTreeUI(frameKontrastGame);
if(RandomNrJeden <= 50)
{
JOptionPane.showMessageDialog(frameKontrastGame, "Eggs are not supposed to be green.");
frameKontrastGame.setVisible(false);
JFrame frameScenario2 = new JFrame();
frameScenario2.setTitle("Scenario2");
frameScenario2.setSize(1000,700);
frameScenario2.setLocationRelativeTo(null);
frameScenario2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panelScenario = new JPanel ();
panel.setLayout(new GridLayout(2, 1));
final JLabel tekst = new JLabel ();
tekst.setText("<html>Część dialogu numer 1</html>");
//JTextField dialog = new JTextField(20);
//dialog.setText("<html>Eggs are not supposed to be green.</html>");
JButton OdpPierwsza = new JButton ();
OdpPierwsza.setText("<html>Opowiedź pierwsza</html>");
OdpPierwsza.addActionListener (new ActionListener(){
#Override
public void actionPerformed(ActionEvent ev) {
tekst.setText("<html>HERE I NEED A TEXT FROM FILE dialog.txt</html>");
}
});
//panelScenario.add(dialog);
panelScenario.add(tekst);
panelScenario.add(OdpPierwsza);
frameScenario2.getContentPane().add(panelScenario);
frameScenario2.setVisible(true);
}
(If the brackets are wrong that's because its not the whole code.)
So:
Where is the "HERE I NEED A TEXT FROM FILE dialog.txt" I need some kind of reader. The best one will be the one which reads text line by line. I just cant find how to write it.
I need to add the JLabel to the JPanel.
You can read your file into just one string using
BufferedReader br = new BufferedReader(new FileReader("your_file.txt"));
String line = br.readLine();
ArrayList<String> listOfStrings = new ArrayList<>();
listOfString.add(line);
while(line != null)
{
line = br.readLine();
listOfString.add(line);
}
And now do a for-loop to iterate over the JList and add text to the JLabel. Better is a JTextArea.
I am designing a software with multiple components - each with its own actionlistener.
For an example, I have a JPanel with a cardlayout that holds 10 cards - each its own JPanel and purpose.
On one side, there are multiple buttons, I.E. Login, Logout, Settings, etc.
When I click Login, it will switch to the card using the Login() method to the Login JPanel object where I want it to wait for a button to click I.E. Login, New User, or Cancel before continuing the Login() method and setting the current user.
Is there a method to pause the program until one of the buttons are clicked to retrieve the data from it? (Kind of like how JOptionPane.showInputMessage(null,"INPUT STRING") waits for you)
My Code is below:
FRAME:
/**
* Frame design
*/
public class Frame extends JFrame{
JPanel LeftSide, UpperRightSide;
EmployeeAdder employAdd;
ArrayList<ServiceView> serviceViewers;
ChartViewer viewChart;
PayByView viewPayBy;
SettingsViewer viewSettings;
LoginViewer viewLogin;
CategoryView viewCategory;
ServiceAdder serviceAdd;
Directory directory;
Employee currentEmployee;
ChargeViewer viewCharge;
JButton Login, Logout, Settings;
CardLayout LeftCard,RightCard;
String currentCard,currentRightCard;
ButtonListen listen;
public static String CARDCAT = "Category View";
public static String CARDPAY = "Pay By";
public static String CARDCHART = "Chart View";
public static String CARDLOGIN = "Log-in View";
public static String CARDSERVICEADD = "Service Adder";
Frame(){
listen = new ButtonListen();
//-------Current Card--------------------
currentCard = CARDCAT;
currentRightCard = "CHARGE";
//-----First Find Directory Folder-------
startDirectory();
//-----User Interface--------------------
//-------Left Side-----------------------
LeftSide = new JPanel();
LeftCard = new CardLayout();
LeftSide.setLayout(LeftCard);
viewPayBy = new PayByView();
viewLogin = new LoginViewer();
viewChart = new ChartViewer();
viewCategory = new CategoryView();
employAdd = new EmployeeAdder();
serviceAdd = new ServiceAdder();
LeftSide.add(viewCategory,"CAT");
LeftSide.add(viewChart, "CHA");
LeftSide.add(viewLogin,"LOG");
LeftSide.add(viewPayBy,"PAY");
LeftSide.add(employAdd,"EMA");
LeftSide.add(serviceAdd,"SEA");
LeftCard.show(LeftSide, "CAT");
viewCategory.setEnabled(false);
LeftSide.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK),currentCard));
serviceViewers = new ArrayList<ServiceView>();
//--------Right Side---------------------
JPanel RightSide = new JPanel();
RightSide.setLayout(new BorderLayout());
UpperRightSide = new JPanel();
RightCard = new CardLayout();
UpperRightSide.setLayout(RightCard);
viewSettings = new SettingsViewer();
viewCharge = new ChargeViewer();
viewCharge.setEnabled(false);
UpperRightSide.add(viewCharge,"CHARGE");
UpperRightSide.add(viewSettings,"SETTINGS");
UpperRightSide.setPreferredSize(new Dimension(350,500));
RightSide.add(UpperRightSide,BorderLayout.NORTH);
//--------Buttons at the bottom Panel---
JPanel Buttons = new JPanel();
Buttons.setLayout(new GridLayout(3,1));
Login = new JButton("LOG-IN");
Login.addActionListener(listen);
Logout = new JButton("LOG OUT");
Logout.addActionListener(listen);
Settings = new JButton("Settings");
Settings.addActionListener(listen);
Buttons.add(Login);
Buttons.add(Logout);
Buttons.add(Settings);
Buttons.setPreferredSize(new Dimension(350,150));
RightSide.add(Buttons,BorderLayout.SOUTH);
RightSide.setSize(new Dimension(400,200));
//------Other Stuff--------------------------
//-----add Panels----------------------------
setLayout(new BorderLayout());
add(LeftSide,BorderLayout.WEST);
add(RightSide,BorderLayout.EAST);
}
private void Login(){
LeftCard.show(LeftSide, "LOG");
//----I WANT IT TO WAIT HERE FOR AN ACTION-------
int clicked = viewLogin.getClicked();
if (clicked==LoginViewer.NEWUSER){
NewUser();
}else if (clicked==LoginViewer.LOGIN){
if (viewLogin.checkPassword()){
currentEmployee = directory.getEmployee(viewLogin.getSelectedName());
viewCategory.setEnabled(true);
viewCharge.setEnabled(true);
viewCharge.refreshName(currentEmployee.getName());
LeftCard.show(LeftSide, "CAT");
}
}else if (clicked==LoginViewer.CANCEL){
LeftCard.show(LeftSide, "CAT");
}
}
public class ButtonListen implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if (!viewLogin.isWaiting()){
if (e.getSource()==Login){
if (currentCard.equals(CARDLOGIN)){
LeftCard.show(LeftSide,"CAT");
currentCard = CARDCAT;
}else{
Login();
currentCard = CARDLOGIN;
}
}else{
//Don't change the screen
}
}
}
}
}
My Code for LoginViewer:
public class LoginViewer extends JPanel{
JComboBox User;
JPasswordField passField;
JButton NewUser, Login, Cancel;
Hashtable<String,String> namespass; //names and password
private int clicked = -1;
ButtonListen listen;
public static int NEWUSER = 1;
public static int LOGIN = 0;
public static int CANCEL = 2;
boolean waiting;
LoginViewer(){
waiting = false;
//---------------------------------------
setPreferredSize(new Dimension(100,100));
listen = new ButtonListen();
namespass = new Hashtable<String,String>();
//----------Panel Design-------------------
JPanel Center = new JPanel();
Center.setLayout(new GridLayout(3,3));
User = new JComboBox();
passField = new JPasswordField();
NewUser = new JButton("New User");
NewUser.addActionListener(listen);
Login = new JButton("Login");
Login.addActionListener(listen);
Cancel = new JButton("Cancel");
Cancel.addActionListener(listen);
Center.add(new JLabel("Choose User"));
Center.add(User);
Center.add(new JLabel(""));
Center.add(new JLabel("Type Password"));
Center.add(passField);
Center.add(new JLabel(""));
Center.add(Login);
Center.add(NewUser);
Center.add(Cancel);
Center.setPreferredSize(new Dimension(300,300));
Center.setMaximumSize(new Dimension(100,100));
Center.setAlignmentX(CENTER_ALIGNMENT);
setAlignmentX(CENTER_ALIGNMENT);
setLayout(new BoxLayout(this,BoxLayout.X_AXIS));
add(Box.createHorizontalGlue());
add(Center);
add(Box.createHorizontalGlue());
}
public void uploadUserNames(Hashtable<String,String> names){
namespass.clear();
namespass.putAll(names);
User.removeAllItems();
Enumeration<String> name = names.keys();
while (name.hasMoreElements()){
User.addItem(name.nextElement());
}
}
public boolean checkPassword(){
boolean value = false;
String key = User.getSelectedItem().toString();
if (passField.getPassword().length==4){
if (namespass.get(key).equals(String.valueOf(passField.getPassword()))){
value = true;
}
}
return value;
}
public String getSelectedName(){
return User.getSelectedItem().toString();
}
public boolean isWaiting(){
return waiting;
}
public int getClicked(){
waiting = true;
return clicked;
}
public class ButtonListen implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
waiting = false;
if (e.getSource()==NewUser){
clicked = 1;
}else if (e.getSource()==Login){
clicked = 0;
}else if (e.getSource()==Cancel){
clicked = 2;
}
}
}
}
Or is it easier to just use an actionlistener to listen to ALL of the objects' buttons?
There are a LOT of buttons...
NOTE: Some of the methods are incomplete or test methods until I know how to make it work...
You don't want to use linear console-type code in a Swing GUI. Instead, with event-driven GUI programs you will want to have user interactions change a program's state, and then have the behavior of the program depend on the state. For instance, rather than have the login method pause, have it do some housekeeping -- change the state of the program to be ready to accept a login attempt -- and then where you plan to "wait", exit the login method. Then have the rest of the code for logging in reside in the login button's ActionListener.
As an aside, you've posted a lot of code, 95% of it unrelated to your problem and thus only serving as a distraction to us and preventing us from reading the code and understanding the specifics of your problem. In the future, consider creating and posting an sscce, where you condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem for us.
the way the Swing framework works is that you already "wait" for everything to happen, and it only happens once the users triggers the action corresponding to your listener.
So yes, basically you only have to wait for buttons to be clicked.
HOWEVER:
Designing responsive GUIs means that you won't let your user wait 10 seconds on a frozen interface until you do yout 10000 calculations and 10 million SELECT statements. Thus in case your action listeners (or whatever specific listeners you've got) have to perform heavy duty calculations, do them on a separate Thread, and inform the user if a task is done one way or another.
I'm writing a Text Analysis Program for college that requires you to add a word to a dictionary as well as other actions. I'm having a problem with this section of the code as I need an error message to come up if the user hits ok while the JTextField is empty. I can get it going but have created an infinite loop somehow with the error message. Please help, I've looked all over the internet but can't find an answer for such a simple bug. Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.lang.Character;
public class TAPtest implements ActionListener
{
private JFrame tap = new JFrame("Text Analysis");
private JMenuBar tapMenu = new JMenuBar();
private JMenu dictionary = new JMenu("Dictionary");
private JMenuItem addWord = new JMenuItem("Add Word");
private JFrame frameAdd = new JFrame("Add Word");
private JLabel add = new JLabel("Enter word to add:");
private JButton okNewWord = new JButton("Ok");
private JButton cancelNewWord = new JButton("Cancel");
private JTextField inputNewWord = new JTextField(28);
private JPanel westAdd = new JPanel();
private JPanel eastAdd = new JPanel();
private JPanel southAdd = new JPanel();
private Vector <String> dictionaryVector = new Vector<String>();
public TAPtest() //Constructor. Contains TAP GUI.
{
tap.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tap.setSize(350, 100);
tap.setLocation(700, 500);
tap.setResizable(false);
tap.setJMenuBar(tapMenu);
tapMenu.add(dictionary);
dictionary.add(addWord);
addWord.addActionListener(this);
tap.setVisible(true);
}
public void actionPerformed(ActionEvent event) //All actions performed.
{
if (event.getActionCommand() == "Add Word") addNewDicWordGUI();
if (event.getSource() == okNewWord) addNewDicWord();
if (event.getSource() == cancelNewWord) frameAdd.dispose();
}
public void addNewDicWordGUI()
{
frameAdd.setSize(350, 150);
frameAdd.setLocation(700, 500);
frameAdd.setResizable(false);
okNewWord.setSize(5,20);
cancelNewWord.setSize(5,20);
westAdd.add(add);
eastAdd.setLayout(new GridLayout(2,1));
eastAdd.add(okNewWord);
eastAdd.add(cancelNewWord);
southAdd.add(inputNewWord);
frameAdd.add(westAdd, BorderLayout.WEST);
frameAdd.add(eastAdd, BorderLayout.EAST);
frameAdd.add(southAdd, BorderLayout.SOUTH);
okNewWord.addActionListener(this);
cancelNewWord.addActionListener(this);
inputNewWord.addActionListener(this);
frameAdd.setVisible(true);
}
public void addNewDicWord()
{
String inputNew = inputNewWord.getText(); //Get JTextField value.
inputNew = inputNew.toLowerCase();
frameAdd.dispose();
if (inputNew.equals(""))
JOptionPane.showMessageDialog(null, "You must enter a word", "Notice", 1);
else {
boolean addItemFound = dictionaryVector.contains(inputNew); //True if contains.
if(addItemFound) //If true.
JOptionPane.showMessageDialog(null, inputNew + " already exists in the dictionary.", "Word Already Exists", 1);
else { //If not true.
dictionaryVector.addElement(inputNew); //Add the word to the dictionary Vector.
Collections.sort(dictionaryVector); //Sort the vector in ascending order.
JOptionPane.showMessageDialog(null, inputNew + " was added to the dictionary.", "Word Added", 1);
}
inputNewWord.setText(null);
}
}
public static void main(String [] args)
{
TAPtest program = new TAPtest();
}
}
private Vector <String> dictionaryVector = new Vector<String>();
inputNewWord.setText(null);
JOptionPane.showMessageDialog(null, "You must enter a word", "Notice", 1);
public void actionPerformed(ActionEvent event) //All actions performed.
{
...
}
should better be
private SortedSet<String> dictionaryVector = new TreeSet<String>();
inputNewWord.setText("");
JOptionPane.showMessageDialog(null, "You must enter a word", "Notice",
JOptionPane.ERROR_MESSAGE);
public void actionPerformed(ActionEvent event) //All actions performed.
{
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
...
}
}
}
The last invokeLater might have caused the troubles. The event handling actionPerformed is done on the event thread, and showing a message should be done after
the event is handled (as any longer task for the GUI to remain responsive).
Declare frameAdd like this -
private JFrame frameAdd = null;
The addNewDicWordGUI() method should be like this -
public void addNewDicWordGUI()
{
if(frameAdd==null)
{
//Initialized only for the first time
frameAdd = new JFrame("Add Word");
frameAdd.setSize(350, 150);
frameAdd.setLocation(100, 200);
frameAdd.setResizable(false);
okNewWord.setSize(5,20);
cancelNewWord.setSize(5,20);
westAdd.add(add);
eastAdd.setLayout(new GridLayout(2,1));
eastAdd.add(okNewWord);
eastAdd.add(cancelNewWord);
southAdd.add(inputNewWord);
frameAdd.add(westAdd, BorderLayout.WEST);
frameAdd.add(eastAdd, BorderLayout.EAST);
frameAdd.add(southAdd, BorderLayout.SOUTH);
okNewWord.addActionListener(this);
cancelNewWord.addActionListener(this);
inputNewWord.addActionListener(this);
}
frameAdd.setVisible(true);
}
Make the above changes and it will work fine.