My problem is that I have a class that when the user types out the text displayed dispose() is called, which works the first time but if you don't close the program and open it again, dispose() is called, but doesn't do anything which breaks the program.
public class TypeMenu extends JDialog {
protected final JPanel contentPanel = new JPanel();
protected static JTextField inputTxtField;
protected static JTextField textField;
protected static JTextField introTxtField;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Easy dialog = new Easy();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
* #param introTxtField2
* #param textField2
* #param inputTxtField2
*/
public TypeMenu(JTextField inputTxtField2, JTextField introTxtField2, JTextField textField2) {
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
contentPanel.add(getInputTxtField());
contentPanel.add(getTextField());
contentPanel.add(getIntroTxtField());
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
}
}
protected JTextField getInputTxtField() {
if (inputTxtField == null) {
inputTxtField = new JTextField();
inputTxtField.setHorizontalAlignment(SwingConstants.CENTER);
inputTxtField.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent arg0) {
String strField = textField.getText();
char key = arg0.getKeyChar();
int length = strField.length();
if (Character.toLowerCase(strField.charAt(0)) == Character.toLowerCase(key)) {
inputTxtField.setText(" ");
textField.setText(strField.substring(1));
System.out.println(length);
System.out.println(strField);
if (length - 1 <= 0) {
dispose();
}
} else {
inputTxtField.setText(" ");
}
}
});
inputTxtField.setBounds(56, 177, 314, 40);
inputTxtField.setColumns(10);
}
return inputTxtField;
}
protected JTextField getIntroTxtField() {
if (introTxtField == null) {
introTxtField = new JTextField();
introTxtField.setHorizontalAlignment(SwingConstants.CENTER);
introTxtField.setFont(new Font("Tahoma", Font.BOLD, 15));
introTxtField.setText("Easy Mode");
introTxtField.setEditable(false);
introTxtField.setBounds(56, 11, 314, 29);
introTxtField.setColumns(10);
}
return introTxtField;
}
private JTextField getTextField() {
if (textField == null) {
textField = new JTextField();
textField.setHorizontalAlignment(SwingConstants.CENTER);
textField.setFont(new Font("Monospaced", Font.BOLD, 20));
textField.setBounds(10, 51, 414, 40);
}
return textField;
}
}
This is one of the child classes
public class Easy extends TypeMenu {
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Easy dialog = new Easy();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public Easy() {
super(inputTxtField, introTxtField, textField);
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
contentPanel.add(getInputTxtField());
contentPanel.add(getIntroTxtField());
getString();
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
textField.selectAll();
}
}
private void getString() {
String str = textField.getText();
if (str.equals("")) {
String generator = StringGenerator.medium();
String nStr = "" + generator;
textField.setText(nStr);
}
}
}
The code that calls this class
public class StartMenu extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField introTxt;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
StartMenu dialog = new StartMenu();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Creates the dialog and creates the buttons that take the user to each variation of the game when pressed.
*/
public StartMenu() {
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
{
introTxt = new JTextField();
introTxt.setFont(new Font("Tahoma", Font.BOLD, 12));
introTxt.setHorizontalAlignment(SwingConstants.CENTER);
introTxt.setText("Start Menu\r\n");
introTxt.setEditable(false);
introTxt.setBounds(75, 11, 276, 20);
contentPanel.add(introTxt);
introTxt.setColumns(10);
}
{
JButton btnEasyButton = new JButton("Easy Mode");
btnEasyButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
new Easy().setVisible(true);
}
});
btnEasyButton.setBounds(141, 42, 140, 23);
contentPanel.add(btnEasyButton);
}
{
JButton btnMediumButton = new JButton("Medium Mode");
btnMediumButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
new Medium().setVisible(true);
}
});
btnMediumButton.setBounds(141, 81, 140, 23);
contentPanel.add(btnMediumButton);
}
{
JButton btnHardButton = new JButton("Hard Mode");
btnHardButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
new Hard().setVisible(true);
}
});
btnHardButton.setBounds(141, 120, 140, 23);
contentPanel.add(btnHardButton);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
}
}
}
your text field is static so he will have only one instance across the application.
so in the method getIntroTxtField() you have if statement that says :
if (introTxtField == null)
in the first time this condition is true but when you create the new instance this condition is false because the instance of the static field is all ready created in the first and you are adding the key listener inside the condition
so the action listener will be added only in the first creation.
if you need to keep the static because you need in other class you need to remove the == null
protected JTextField getInputTxtField() {
inputTxtField = null;
{
inputTxtField = new JTextField();
inputTxtField.setHorizontalAlignment(SwingConstants.CENTER);
inputTxtField.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent arg0) {
String strField = textField.getText();
char key = arg0.getKeyChar();
int length = strField.length();
if (Character.toLowerCase(strField.charAt(0)) == Character.toLowerCase(key)) {
inputTxtField.setText(" ");
textField.setText(strField.substring(1));
System.out.println(length);
System.out.println(strField);
if (length - 1 <= 0) {
dispose();
}
} else {
inputTxtField.setText(" ");
}
}
});
inputTxtField.setBounds(56, 177, 314, 40);
inputTxtField.setColumns(10);
}
return inputTxtField;
}
or remove the static from you field declaration static is used in
shared instace only when you are using only one instace across the
application like sessionFactory or any thing that need to be created
only one time.
you code is a lot to read but i think your problem is that you are calling the dispose() of the wrong object. may you are calling it always for the first object and you are creating a new one, and the dispose of this new dialog will never be call,Check you code may be you are creating many object and the dispose() is not called at all. make sure that you have full control of your objects instance to know if you are diposing the wanted dialog.
Related
I have put a background image using "paint" and as I've tried to add a Jlabel it is not showing upon running. Here's my code and screenshots.
Output
public class startingPage extends JFrame {
private JPanel contentPane;
private String audioFileName = "bg-music.wav";
private String imagePath = "truck_850x300_mining_island.png";
private String logo = "explore_with_mine.png";
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
startingPage frame = new startingPage();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public startingPage() {
initComponents();
createEvents();
playAudio();
}
public void playAudio() {
// TODO Auto-generated method stub
try
{
File audioPath = new File(audioFileName);
programManager.stream = AudioSystem.getAudioInputStream(audioPath);
programManager.clip = AudioSystem.getClip();
programManager.clip.open(programManager.stream);
programManager.clip.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void createEvents() {
}
public void initComponents() {
setTitle("Explore With Mine");
setIconImage(Toolkit.getDefaultToolkit().getImage(startingPage.class.getResource("/exploreWithMine/resources/logo.png")));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setBounds(400, 200, 720, 480);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("START");
btnNewButton.setBounds(262, 299, 177, 58);
btnNewButton.setBackground(Color.LIGHT_GRAY);
btnNewButton.setForeground(new Color(165, 42, 42));
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 42));
contentPane.add(btnNewButton);
JLabel lblNewLabel = new JLabel("TESTING");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblNewLabel.setBounds(10, 10, 146, 43);
contentPane.add(lblNewLabel);
}
public void paint(Graphics g)
{
g.drawImage(new ImageIcon(imagePath).getImage(),
-70,90, null);
}
}
OUTPUT
JLABEL not Showing (Upper Left)
I have tried removing the painted background image and it worked however I also need that background image to be there.
OUTPUT
I am trying to pass the table number from the restaurant class into tableLabel which is in the Menu page class. When the code is running the tableLabel returns null. Any help would be appreciated to enable the code when running to return a number in the tableLabel.
Extract from Restaurant Class
public class Restaurant extends JFrame {
private JPanel contentPane;
private JTextField restaurant_Txt;
private JTextField num_Diners;
private JTextField num_Diners_Txt;
private JTextField table_Num_Txt;
private JTextField num_Table;
private JButton num_TableSub_Btn;
private JButton proceed_Menu_Btn;
private JButton MyDocumentListener;
MenuPage parent;
public static String tableNumber;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Restaurant frame = new Restaurant();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Restaurant() {
super("Restaurant");
parent = new MenuPage();
initGUI();
num_Table = new JTextField("NewUser", 10);
}
public void initGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 640, 310);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
table_Num_Txt = new JTextField();
table_Num_Txt.setEditable(false);
table_Num_Txt.setText("Table number ?");
table_Num_Txt.setBounds(145, 164, 112, 26);
contentPane.add(table_Num_Txt);
table_Num_Txt.setColumns(10);
num_Table = new JTextField("");
num_Table.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (e.getKeyCode() == 10) {
tableNumber = num_Table.getText();
}
}
});
num_Table.setBounds(334, 161, 83, 26);
contentPane.add(num_Table);
num_Table.setColumns(10);
}
}
Extract from Menu Page class
tableLabel = new JLabel(" : " + Restaurant.tableNumber);
tableLabel.setBounds(16, 6, 61, 16);
contentPane.add(tableLabel);
This may be a stupid question, but are you sure you are pressing enter when being inside the num_Table field inside your GUI since the variable is set when this happens. Also you should probably pass it via the constructor to MainPage, not as a static variable.
i have two jframes in my app, Addnmember.java and Frame1.java
Frame1 is the main Jframe,
i want when someone presses the Add button, the Addmember will be shown, i have done this with this code, and every thing is fine:
AddB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.dispose();
AddMember addmem = new AddMember();
addmem.setVisible(true);
}
});
But in the new Jframe, i want to come back again when Done Bt is selected, i have done this whit this code:
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//dispose();
Frame1 addmem = new Frame1();
addmem.setVisible(true);
}
});
but this doesent work! mean the Jframe Loads but there is no content in it! look:
why this happens? here is my codes:
AddMember.java:
public class AddMember extends JFrame {
private JFrame frame;
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
private JButton btnNewButton;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddMember frame = new AddMember();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public AddMember() {
setTitle("\u0627\u0641\u0632\u0648\u062F\u0646 \u0639\u0636\u0648 \u062C\u062F\u06CC\u062F");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 331);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel label = new JLabel("\u0646\u0627\u0645:");
label.setFont(new Font("Tahoma", Font.BOLD, 11));
label.setBounds(332, 60, 46, 14);
contentPane.add(label);
textField = new JTextField();
textField.setToolTipText("\u0646\u0627\u0645");
textField.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
textField.setText("");
}
});
textField.setHorizontalAlignment(SwingConstants.RIGHT);
textField.setText("\u0646\u0627\u0645");
textField.setBounds(236, 57, 86, 20);
contentPane.add(textField);
textField.setColumns(10);
JLabel label_1 = new JLabel("\u0634.\u062F\u0627\u0646\u0634\u062C\u0648\u06CC\u06CC:");
label_1.setFont(new Font("Tahoma", Font.BOLD, 11));
label_1.setBounds(328, 103, 85, 14);
contentPane.add(label_1);
textField_1 = new JTextField();
textField_1.setToolTipText("\u0634\u0645\u0627\u0631\u0647 \u062F\u0627\u0646\u0634\u062C\u0648\u06CC\u06CC");
textField_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
textField_1.setText("");
}
});
textField_1.setText("\u0634\u0645\u0627\u0631\u0647 \u062F\u0627\u0646\u0634\u062C\u0648\u06CC\u06CC");
textField_1.setHorizontalAlignment(SwingConstants.RIGHT);
textField_1.setColumns(10);
textField_1.setBounds(236, 100, 86, 20);
contentPane.add(textField_1);
JLabel label_2 = new JLabel("\u0631\u0634\u062A\u0647:");
label_2.setFont(new Font("Tahoma", Font.BOLD, 11));
label_2.setBounds(332, 145, 46, 14);
contentPane.add(label_2);
textField_2 = new JTextField();
textField_2.setToolTipText("\u0631\u0634\u062A\u0647 \u062A\u062D\u0635\u06CC\u0644\u06CC");
textField_2.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
textField_2.setText("");
}
});
textField_2.setText("\u0631\u0634\u062A\u0647 \u062A\u062D\u0635\u06CC\u0644\u06CC");
textField_2.setHorizontalAlignment(SwingConstants.RIGHT);
textField_2.setColumns(10);
textField_2.setBounds(236, 142, 86, 20);
contentPane.add(textField_2);
JLabel label_3 = new JLabel("\u0646\u0627\u0645 \u062E\u0627\u0646\u0648\u0627\u062F\u06AF\u06CC:");
label_3.setFont(new Font("Tahoma", Font.BOLD, 11));
label_3.setBounds(144, 61, 82, 14);
contentPane.add(label_3);
textField_3 = new JTextField();
textField_3.setToolTipText("\u0646\u0627\u0645 \u062E\u0627\u0646\u0648\u0627\u062F\u06AF\u06CC");
textField_3.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
textField_3.setText("");
}
});
textField_3.setText("\u0646\u0627\u0645 \u062E\u0627\u0646\u0648\u0627\u062F\u06AF\u06CC");
textField_3.setHorizontalAlignment(SwingConstants.RIGHT);
textField_3.setColumns(10);
textField_3.setBounds(48, 58, 86, 20);
contentPane.add(textField_3);
JLabel label_4 = new JLabel("\u0634. \u062A\u0645\u0627\u0633:");
label_4.setFont(new Font("Tahoma", Font.BOLD, 11));
label_4.setBounds(144, 104, 69, 14);
contentPane.add(label_4);
textField_4 = new JTextField();
textField_4.setToolTipText("\u0634\u0645\u0627\u0631\u0647 \u062A\u0645\u0627\u0633");
textField_4.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
textField_4.setText("");
}
});
textField_4.setText("\u0634\u0645\u0627\u0631\u0647 \u062A\u0645\u0627\u0633");
textField_4.setHorizontalAlignment(SwingConstants.RIGHT);
textField_4.setColumns(10);
textField_4.setBounds(48, 101, 86, 20);
contentPane.add(textField_4);
textField_5 = new JTextField();
textField_5.setToolTipText("\u0633\u0627\u0644 \u0648\u0631\u0648\u062F");
textField_5.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
textField_5.setText("");
}
});
textField_5.setText("\u0633\u0627\u0644 \u0648\u0631\u0648\u062F");
textField_5.setHorizontalAlignment(SwingConstants.RIGHT);
textField_5.setColumns(10);
textField_5.setBounds(48, 140, 86, 20);
contentPane.add(textField_5);
JLabel label_5 = new JLabel("\u0648\u0631\u0648\u062F\u06CC:");
label_5.setFont(new Font("Tahoma", Font.BOLD, 11));
label_5.setBounds(144, 143, 46, 14);
contentPane.add(label_5);
textField_6 = new JTextField();
textField_6.setToolTipText("\u0636\u0631\u0648\u0631\u06CC \u0646\u06CC\u0633\u062A");
textField_6.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
textField_6.setText("");
}
});
textField_6.setHorizontalAlignment(SwingConstants.RIGHT);
textField_6.setText("\u0636\u0631\u0648\u0631\u06CC \u0646\u06CC\u0633\u062A");
textField_6.setColumns(10);
textField_6.setBounds(131, 187, 86, 20);
contentPane.add(textField_6);
JLabel label_6 = new JLabel("\u0627\u06CC\u0645\u06CC\u0644:");
label_6.setFont(new Font("Tahoma", Font.BOLD, 11));
label_6.setBounds(227, 190, 46, 14);
contentPane.add(label_6);
btnNewButton = new JButton("Done");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//dispose();
Frame1 addmem = new Frame1();
addmem.setVisible(true);
}
});
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 11));
btnNewButton.setBounds(171, 227, 89, 23);
contentPane.add(btnNewButton);
}
private static void addPopup(Component component, final JPopupMenu popup) {
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
private void showMenu(MouseEvent e) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}
And Frame1.java:
public class Frame1 extends JFrame {
Connection connection = null;
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame1 window = new Frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
private JTable table;
public Frame1() {
JOptionPane.showMessageDialog(null, "sazande :|");
this.initialize();
connection = DataBConect.dbConnect();
try {
String query = "select * from Users";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
JOptionPane.showMessageDialog(null, "intialize :|");
frame.setTitle("App");
frame.setBounds(100, 100, 725, 465);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton AddB = new JButton("Add");
AddB.setBackground(Color.WHITE);
AddB.setFont(new Font("Tahoma", Font.BOLD, 11));
AddB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.dispose();
AddMember addmem = new AddMember();
addmem.setVisible(true);
}
});
AddB.setBounds(302, 392, 135, 23);
frame.getContentPane().add(AddB);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(22, 26, 658, 359);
frame.getContentPane().add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
}
}
thanks.
As to why your second Frame1 shows no data, I'm not 100% sure, but perhaps it has something to do with your failure to close your database connection. Regardless, it seems wasteful and even potentially dangerous to want to gather the database data twice when you've already obtained it once, and to create your Frame1 GUI twice when you've already created it once.
You should re-design your GUI. The main JFrame GUI should remain visible, and the Frame1 window should be a modal JDialog. As a modal dialog, it will prevent users from being able to interact with the parent JFrame until the dialog is no longer visible.
Note that to get started requires only a few changes:
in Frame1.java
AddB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// frame.dispose();
AddMember addmem = new AddMember(Frame1.this); // !!
addmem.setVisible(true);
}
});
in AddMember.java
class AddMember extends JDialog {
public AddMember(JFrame frame) {
super(frame, "", ModalityType.APPLICATION_MODAL);
setTitle("\u0627\u0641\u0632\u0648\u062F\u0646 \u0639\u0636\u0648 \u062C\u062F\u06CC\u062F");
// !! setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// dispose();
dispose(); // !!
// !! Frame1 addmem = new Frame1();
// addmem.setVisible(true);
}
});
Also, you'll want to avoid null layouts and setBounds(...) as this will lead to very rigid, hard to debug and improve programs.
I am creating a login window for a program. I am having trouble getting my program to search through my arraylist and return a username and then search again for a password.
public class Login extends JFrame {
public String firstName, lastName, account, birthYear, password;
Login(String fn, String ln, String acc, String by, String pw){
firstName = fn;
lastName = ln;
account = acc;
birthYear = by;
password = pw;
}
Login current;
ArrayList<Login> list= new ArrayList<Login>();
int count;
private JPanel contentPane;
private JPasswordField passwordField;
private final Action action = new SwingAction();
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login frame = new Login();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Login() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel label = new JLabel("");
label.setBounds(217, 5, 212, 126);
contentPane.add(label);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
for (int i = 0; i<list.size(); i++){
if (Arrays.equals(list.get(i).password.toCharArray(), textField.getText().toCharArray())){
System.out.println("found the account");
if (Arrays.equals(list.get(i).password.toCharArray(), passwordField.getPassword())){
current = list.get(i);
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
overview frame = new overview();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
else{
JOptionPane.showMessageDialog(null, "Password does not match our records", "Error", JOptionPane.INFORMATION_MESSAGE);
}
}
else{
JOptionPane.showMessageDialog(null, "Account number not found", "Error", JOptionPane.INFORMATION_MESSAGE);
}
}
}
});
btnLogin.setAction(action);
btnLogin.setBounds(108, 186, 89, 23);
contentPane.add(btnLogin);
JButton btnRegister = new JButton("Register");
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Register frame = new Register();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
btnRegister.setBounds(217, 186, 89, 23);
contentPane.add(btnRegister);
passwordField = new JPasswordField();
passwordField.setBounds(172, 148, 142, 20);
contentPane.add(passwordField);
JPanel panel = new JPanel();
panel.setBackground(Color.BLUE);
panel.setBounds(39, 32, 335, 51);
contentPane.add(panel);
JLabel lblLogin = new JLabel("Login");
lblLogin.setFont(new Font("Verdana", Font.BOLD, 15));
panel.add(lblLogin);
lblLogin.setForeground(SystemColor.window);
lblLogin.setBackground(Color.BLUE);
JLabel lblAccountNumber = new JLabel("Account Number:");
lblAccountNumber.setBounds(49, 101, 113, 14);
contentPane.add(lblAccountNumber);
JLabel lblPassword = new JLabel("Password:\r\n");
lblPassword.setBounds(49, 151, 113, 14);
contentPane.add(lblPassword);
textField = new JTextField();
textField.setBounds(172, 98, 142, 20);
contentPane.add(textField);
textField.setColumns(10);
}
public void printLogin(Login l) {
System.out.println(l.firstName);
System.out.println(l.lastName);
System.out.println(l.account);
System.out.println(l.birthYear);
System.out.println(l.password);
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "Login");
putValue(SHORT_DESCRIPTION, "Login to your account");
}
public void actionPerformed(ActionEvent e) {
}
}
}
The code is supposed to run the program when the "Login" button is pressed but it currently isn't working.
Below line has a problem :
if (list.get(i).password.equals(passwordField.getPassword())){
JPasswordField#getPassword() return char[] where as you are comparing a String password with char[] that is wrong.
Try Arrays.equals() to compare arrays as follow:
Arrays.equals(list.get(i).password.toCharArray(), passwordField.getPassword());
I suggest you to use Map in place of ArrayList. Make username as key of Map.
Use
Map<String,Login> map = new HashMap<String,Login>();
instead of
ArrayList<Login> list= new ArrayList<Login>();
Map is more faster in search than ArrayList.
I hope that my notes can be helpful :
There is no main method to make the class runnable
The location of list.add(test); is not allowed there. It should be in constructor/method.
In my form, when i press ENTER button in my keyboard, the okAction() method should be invoke (and invoke perfectly).
My problem is in focus state, When i fill the text fields and then press the ENTER button, the okAction() didn't invoked, because the focus is on the second text field (not on the panel).
How fix this problem?
public class T3 extends JFrame implements ActionListener {
JButton cancelBtn, okBtn;
JLabel fNameLbl, lNameLbl, tempBtn;
JTextField fNameTf, lNameTf;
public T3() {
add(createForm(), BorderLayout.NORTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new T3();
}
});
}
public JPanel createForm() {
JPanel panel = new JPanel();
panel.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "Button");
panel.getActionMap().put("Button", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
okAction();
}
});
okBtn = new JButton("Ok");
okBtn.addActionListener(this);
cancelBtn = new JButton("Cancel");
tempBtn = new JLabel();
fNameLbl = new JLabel("First Name");
lNameLbl = new JLabel("Last Name");
fNameTf = new JTextField(10);
fNameTf.setName("FnTF");
lNameTf = new JTextField(10);
lNameTf.setName("LnTF");
panel.add(fNameLbl);
panel.add(fNameTf);
panel.add(lNameLbl);
panel.add(lNameTf);
panel.add(okBtn);
panel.add(cancelBtn);
panel.add(tempBtn);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 3, 2, 50, 10, 80, 60);
return panel;
}
private void okAction() {
if (fNameTf.getText().trim().length() != 0 && lNameTf.getText().trim().length() != 0) {
System.out.println("Data saved");
} else System.out.println("invalid data");
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == okBtn) {
okAction();
}
}
}
Declare a default button for your GUI's JRootPane:
public T3() {
//!! ..... etc...
setVisible(true);
getRootPane().setDefaultButton(okBtn);
}
In fact with a default button set, I don't see that you need to use key bindings.