Cant Delete a Value From HashMap Which is Selected Randomly - java

I prepared a project that is inspired from Trivia Crack.
SporHmap is a HashMap which stores 3 values(questions). In the actionListener method the program gets a random key from the Hashmap and prints questions and the answers to the JLabels and JButtons of the QuestionClass.
The problem here is, I dont want the questions to be repeated. If a question was shown, it should not be showed again. I used tl.SporHmap.remove(randomValue); after a value was chosen but it didnt change anything.
TriviaLinked tl = new TriviaLinked();
tl.SporHmap.put("Basketbolda 3 adımdan fazla atılan adıma ne denir?","Steps");
tl.SporHmap.put("Hindistan'ın ulusal sporu nedir?","Kriket");
tl.SporHmap.put("Süper Lig'de hakeme kırmızı kart gösteren futbolcu kimdir?","Salih Dursun");
Spor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
QuestionClass q = new QuestionClass();
q.getQFrame();
Object[] values = tl.SporHmap.values().toArray();
String randomValue = (String)values[r.nextInt(values.length)];
if(tl.SporHmap.get("Hindistan'ın ulusal sporu nedir?").equals(randomValue)){
q.label.setText("Hindistan'ın ulusal sporu nedir?");
q.answer1.setText("Kriket");
q.answer2.setText("Beyzbol");
q.answer3.setText("Hokey");
q.answer4.setText("Futbol");
tl.SporHmap.remove(randomValue);
q.answer1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "True Answer");
score.setText("Score: "+scr++);
q.getQFrame().dispose();
Spor.doClick();
}
});
q.answer3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Wrong Answer");
q.getQFrame().dispose();
Spor.doClick();
}
});
q.answer2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Wrong Answer");
q.getQFrame().dispose();
Spor.doClick();
}
});
q.answer4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Wrong Answer");
q.getQFrame().dispose();
Spor.doClick();
}
});
}
else if(tl.SporHmap.get("Basketbolda 3 adımdan fazla atılan adıma ne denir?").equals(randomValue)){
q.label.setText("Basketbolda 3 adımdan fazla atılan adıma ne denir?");
q.answer1.setText("Serbest atış");
q.answer2.setText("Dışarı çıkış");
q.answer3.setText("Steps");
q.answer4.setText("Faul");
tl.SporHmap.remove(randomValue);
q.answer3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "True Answer");
score.setText("Score: "+scr++);
q.getQFrame().dispose();
Spor.doClick();
}
});
q.answer1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Wrong Answer");
q.getQFrame().dispose();
Spor.doClick();
}
});
q.answer2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Wrong Answer");
q.getQFrame().dispose();
Spor.doClick();
}
});
q.answer4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Wrong Answer");
q.getQFrame().dispose();
Spor.doClick();
}
});
}
else if(tl.SporHmap.get("Süper Lig'de hakeme kırmızı kart gösteren futbolcu kimdir?").equals(randomValue)){
q.label.setText("Süper Lig'de hakeme kırmızı kart gösteren futbolcu kimdir?");
q.answer1.setText("Erkan Zengin");
q.answer2.setText("Özer Hurmacı");
q.answer3.setText("Salih Dursun");
q.answer4.setText("Aykut Demir");
tl.SporHmap.remove(randomValue);
q.answer3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "True Answer");
score.setText("Score: "+scr++);
q.getQFrame().dispose();
Spor.doClick();
}
});
q.answer1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Wrong Answer");
q.getQFrame().dispose();
Spor.doClick();
}
});
q.answer2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Wrong Answer");
q.getQFrame().dispose();
Spor.doClick();
}
});
q.answer4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Wrong Answer");
q.getQFrame().dispose();
Spor.doClick();
}
});
}
}
});
Here is my QuestionClass class:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class QuestionClass {
public JLabel label,label1;
public JFrame questionFrame;
public JButton answer1,answer2,answer3,answer4;
public QuestionClass() {
questionFrame = new JFrame();
questionFrame.setDefaultCloseOperation(questionFrame.HIDE_ON_CLOSE);
questionFrame.setLayout(new GridLayout(3,2));
questionFrame.setSize(700, 350);
questionFrame.setVisible(true);
questionFrame.setLocationRelativeTo(null);
label = new JLabel("");
questionFrame.add(label);
label1 = new JLabel("");
questionFrame.add(label1);
answer1 = new JButton("");
questionFrame.add(answer1);
answer2 = new JButton("");
questionFrame.add(answer2);
answer3 = new JButton("");
questionFrame.add(answer3);
answer4 = new JButton("");
questionFrame.add(answer4);
}
public JFrame getQFrame() {
return questionFrame;
}
}

You approach is correct: after showing a question; delete it from the map.
In other words: just fill your map with enough questions to look at; select them randomly; and after asking a question, remove() the corresponding key from your map.
But it seems that you are calling
tl.SporHmap.remove(randomValue);
Only for one of your potential cases. There should not be a condition for that remove. You randomly select a question, and then you remove it!
Beyond that: your "object" model isn't too good. There is no point in having that map, but to then have if/elses for the choices! Instead: you could create a QuizzQuestion class, and a QuizzQuestion has:
The question text itself
The correct answer
The other (wrong) answers
Using that class, you can put all values that belong together into such a QuizzQuestion object.
And then you also don't need a Map; just a List<QuizzQuestion> objects will do!
Given your comment: basically, these could be possible root causes for your problem:
As said; you don't remove for all possible cases
You "re-init" your HashMap accidentally (meaning: you actually remove the value; but you re-create or re-populate the whole map afterwards again)
A conceptual error: you assume that your program should remember its last state; so that when you close the program and start afresh; it should not show questions shown in a previous run. That would be a misconception on your end.

Related

How to simulate a mouse click in a JTextField?

I've been practicing creating a simple registration form GUI and lately I've discovered about Focus Listener. I've implemented it to my program in order to further refine it and somehow I made it work. While it does indeed work how I intended it to be, my next goal is to instead of allowing users to automatically input in the JTextField, I want them to be able to manually click in and out of the Text Field as they please. The problem is I have a hard time thinking on how can implement this.
currently this is my code:
package com.main;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class RegisterScreen extends JFrame implements ActionListener, FocusListener{
JLabel lblCreateUser, lblCreatePassword, lblHeader;
JTextField txtNewUsername, txtNewPassword;
JButton btnCreateAccount, btnReturnBack;
public RegisterScreen(){
super("Create new User");
setLayout(null);
lblCreateUser = new JLabel("Please enter your Email Address");
lblCreatePassword = new JLabel("Please enter your Password");
lblHeader = new JLabel("Create new account");
txtNewUsername = new JTextField("Username");
txtNewPassword = new JTextField("Password");
btnCreateAccount = new JButton("Create account");
btnReturnBack = new JButton("Back");
lblHeader.setBounds(130, 50, 300,40);
lblCreateUser.setBounds(50,115, 300,40);
lblCreatePassword.setBounds(50, 200, 300, 40);
txtNewUsername.setBounds(50, 150, 300, 40);
txtNewPassword.setBounds(50, 230, 300, 40);
btnCreateAccount.setBounds(50, 280,125, 40);
btnReturnBack.setBounds(223, 280,125, 40);
btnReturnBack.addActionListener(this);
btnCreateAccount.addActionListener(this);
txtNewUsername.addFocusListener(this);
txtNewPassword.addFocusListener(this);
add(lblHeader);
add(lblCreateUser);
add(txtNewUsername);
add(lblCreatePassword);
add(txtNewPassword);
add(btnCreateAccount);
add(btnReturnBack);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent exit){
System.exit(0);
}
});
setSize(400,600);
setVisible(true);
setResizable(false);
}
public static void main (String []args){
RegisterScreen register = new RegisterScreen();
}
public void actionPerformed(ActionEvent e) {
File user = new File("Usernames.txt");
File pass = new File("Passwords.txt");
if (e.getSource() == btnCreateAccount) {
try (BufferedWriter addUser = new BufferedWriter(new FileWriter(user, true)); BufferedWriter addPass = new BufferedWriter(new FileWriter(pass, true))) {
if(txtNewUsername.getText().isEmpty() && txtNewPassword.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "Username or Password must not be blank", "Error", 0);
}
else{
addUser.write(txtNewUsername.getText());
addUser.newLine();
addPass.write(txtNewPassword.getText());
addPass.newLine();
JOptionPane.showMessageDialog(null, "Account Successfully Created", "Success", JOptionPane.INFORMATION_MESSAGE);
}
}
catch (IOException exp) {
JOptionPane.showMessageDialog(this, "Account creation failed", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else if(e.getSource() == btnReturnBack){
LoginScreen login = new LoginScreen();
dispose();
}
}
public void focusGained(FocusEvent e) {
if (e.getSource() == txtNewUsername){
txtNewUsername.setText("");
}
if (e.getSource() == txtNewPassword){
txtNewPassword.setText("");
}
}
public void focusLost(FocusEvent e) {
if (e.getSource() == txtNewUsername){
txtNewUsername.setText("Username");
}
if (e.getSource() == txtNewPassword){
txtNewPassword.setText("Password");
}
}
}
I am still a beginner at programming and sorry if you find my code a bit too long but any help is much appreciated!
Some people (including myself) call this sort of thing a Field Watermark. You need to add some conditions within your if statements contained in both the focusGained and focusLost events, for example:
#Override
public void focusGained(FocusEvent e) {
if (e.getSource() == txtNewUsername && txtNewUsername.getText().equals("Username")) {
txtNewUsername.setForeground(Color.black);
txtNewUsername.setText("");
}
else if (e.getSource() == txtNewPassword && txtNewPassword.getText().equals("Password")) {
txtNewPassword.setForeground(Color.black);
txtNewPassword.setText("");
}
}
#Override
public void focusLost(FocusEvent e) {
if (e.getSource() == txtNewUsername && txtNewUsername.getText().trim().isEmpty()) {
txtNewUsername.setForeground(Color.lightGray);
txtNewUsername.setText("Username");
}
else if (e.getSource() == txtNewPassword && txtNewPassword.getText().trim().isEmpty()) {
txtNewPassword.setForeground(Color.lightGray);
txtNewPassword.setText("Password");
}
}
And during your components initialization:
txtNewUsername = new JTextField("Username");
txtNewUsername.setForeground(Color.lightGray); // ****
txtNewPassword = new JTextField("Password");
txtNewPassword.setForeground(Color.lightGray); // ****

Shortcut keys in Java (Mnemonic)

I need help with my homework. I can't seem to make this program work. I just need to put shortcut keys for the compute, reset, and exit buttons.
Compute - Ctrl C
Reset - Ctrl R
Exit - Ctrl E
If you guys need my professor's instructions, I can provide that as well.
here
Here's my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener{
JLabel fval,sval;
JTextField tf1,tf2;
JButton add,subtract,multiply,divide,compute,reset;
String s="";
JPanel jp = new JPanel();
Calculator(){
jp.setLayout(new GridLayout(5,2));
fval=new JLabel("First Value: ");
sval=new JLabel("Second Value: ");
tf1=new JTextField();
tf2=new JTextField();
add=new JButton("ADD");
subtract=new JButton("SUBTRACT");
multiply=new JButton("MULTIPLY");
divide=new JButton("DIVIDE");
compute=new JButton("COMPUTE");
reset=new JButton("RESET");
jp.add(fval);
jp.add(tf1);
jp.add(sval);
jp.add(tf2);
jp.add(add);
jp.add(subtract);
jp.add(multiply);
jp.add(divide);
jp.add(compute);
jp.add(reset);
add.addActionListener(this);
subtract.addActionListener(this);
multiply.addActionListener(this);
divide.addActionListener(this);
compute.addActionListener(this);
reset.addActionListener(this);
this.setTitle("Calculator");
this.setBounds(10,10,300,300);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
add(jp);
//ADD
Action addAction = new AbstractAction("ADD") {
#Override
public void actionPerformed(ActionEvent evt) {
s="ADD";
}
};
String key1 = "ADD";
add.setAction(addAction);
addAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_A);
add.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_DOWN_MASK), key1);
add.getActionMap().put(key1, addAction);
//SUBTRACT
Action subAction = new AbstractAction("SUBTRACT") {
#Override
public void actionPerformed(ActionEvent evt) {
s="SUBTRACT";
}
};
String key2 = "SUBTRACT";
subtract.setAction(subAction);
subAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_S);
subtract.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK), key2);
subtract.getActionMap().put(key2, subAction);
//MULTIPLY
Action mulAction = new AbstractAction("MULTIPLY") {
#Override
public void actionPerformed(ActionEvent evt) {
s="MULTIPLY";
}
};
String key3 = "MULTIPLY";
multiply.setAction(mulAction);
mulAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_M);
multiply.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_M, KeyEvent.CTRL_DOWN_MASK), key3);
multiply.getActionMap().put(key3, mulAction);
//DIVIDE
Action divAction = new AbstractAction("DIVIDE") {
#Override
public void actionPerformed(ActionEvent evt) {
s="DIVIDE";
}
};
String key4 = "DIVIDE";
divide.setAction(divAction);
divAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_D);
divide.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_D, KeyEvent.CTRL_DOWN_MASK), key4);
divide.getActionMap().put(key4, divAction);
}
public void Add(double n1,double n2){
JOptionPane.showMessageDialog(this, +(n1+n2), "Answer", JOptionPane.INFORMATION_MESSAGE);
}
public void Subtract(double n1,double n2){
JOptionPane.showMessageDialog(this, +(n1-n2), "Answer", JOptionPane.INFORMATION_MESSAGE);
}
public void Multiply(double n1,double n2){
JOptionPane.showMessageDialog(this, +(n1*n2), "Answer", JOptionPane.INFORMATION_MESSAGE);
}
public void Divide(double n1,double n2){
JOptionPane.showMessageDialog(this, +(n1/n2), "Answer", JOptionPane.INFORMATION_MESSAGE);
}
#Override
public void actionPerformed(ActionEvent e) {
String in=e.getActionCommand();
if(in.equals("COMPUTE")){
try {
double n1=Double.parseDouble(tf1.getText());
double n2=Double.parseDouble(tf2.getText());
if(s.equals("ADD"))
Add(n1,n2);
else if(s.equals("SUBTRACT"))
Subtract(n1,n2);
else if(s.equals("MULTIPLY"))
Multiply(n1,n2);
else if(s.equals("DIVIDE"))
Divide(n1,n2);
else if(in.equals("RESET")){
tf1.setText("");
tf2.setText("");
s="";
}else
{
s=in;
}
}
catch (NumberFormatException e1) {
compute.setSelected(true);
JOptionPane.showMessageDialog(this, "Math Error.", "Warning", JOptionPane.INFORMATION_MESSAGE);
}
}
};
public static void main(String[] args) {
new Calculator();
}
}
Thank you in advance!
I just need to put shortcut keys for the compute, reset, and exit buttons.
I think you are confusing a "mnemonic" with an "accelerator".
The "mnemonic" is invoked when the component is focused. You invoke the Action by using the "Alt" key plus the underlined character of the text on the button.
The "accelerator" can be invoked even when the component doesn't have focus by using the specified KeyStroke.
So instead of attempting use Key Bindings directly, you can set the "accelerator" of the Action. When you add the Action to the button the key bindings will be set automatically for you.
Read the section from the Swing tutorial on How to Use Actions for more information

Cant use dispose(); method, Java Gui form

I have some problems with using dispose() method in my GUI project.
I' am making a GUI swing application for some kind of Elections in IntelliJ.
My problem is, by clicking a button(Confirm1, or 2 or 3) I want to open new JFrame which is checking the age of voter and closes the current JFrame where this button is located by calling dispose().
But frame.dispose(); doesn't work.
I have my JFrame declared in public static main().
Should I make reference for it in my ActionListener? I have been looking for solution, but I couldn't find any.
Here is a code:
import javax.swing.*; //another libraries
public class ElectionGUI {
private JPanel labelElection; // another texfields or etc.
private JButton Confirm1;
private JButton Confirm3;
private JButton Confirm2;
private JPanel Elections;
public VotesGUI(){
Votes votes = new Votes("...","...",0);
listX.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if(!e.getValueIsAdjusting()){
NrX.setText(listX.getSelectedValue().toString());
}
}
});
listY.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if(!e.getValueIsAdjusting()){
NrY.setText(listY.getSelectedValue().toString());
}
}
});
listZ.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if(!e.getValueIsAdjusting()){
NrZ.setText(listZ.getSelectedValue().toString());
}
}
});
Confirm1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
votes.VotesX();
votes.countVotes();
CheckAge age = new CheckAge();
age.Check(); /// referention, to my next //Jframe called psvm Check();
}
});
Confirm2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
votes.VotesY();
votes.countVotes();
CheckAge age = new CheckAge();
age.Check();
}
});
Confirm3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
votes.VotesZ();
votes.countVotes();
CheckAge age = new CheckAge();
age.Check();
}
});
}
public static void main(String[] args) {
JFrame frame = new JFrame("Elentions");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setContentPane(new ElectionGUI().labelElection);
frame.pack();
}
}

changing the value of a text field as another is changed and the same but reversed causing an error

I am making a simple Miles-Kilometers converter that updates automatically as you type. The problem is that is that an error is thrown somewhere. I believe that this is because as i change one of the fields it handles the event and changes the other field but since that also has an event handler for when it is changed it tries to change the other field itself and they keep firing events back and forth until something somewhere explodes. Any idea how I can fix this or is there a different problem completely ?
Here's my code:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
public class Book extends JFrame{
private JTextField jtfKilometers = new JTextField(10);
private JTextField jtfMiles = new JTextField(10);
public Book(){
setLayout(new BorderLayout(10, 0));
JPanel jlblPanel = new JPanel(new GridLayout(2, 0, 50, 5));
jlblPanel.add(new JLabel("Kilometers"));
jlblPanel.add(new JLabel("Miles"));
add(jlblPanel, "West");
JPanel jtfPanel = new JPanel(new GridLayout(2, 0, 5, 5));
jtfPanel.add(jtfKilometers);
jtfPanel.add(jtfMiles);
add(jtfPanel, "Center");
jtfKilometers.getDocument().addDocumentListener(new DocumentListener(){
#Override
public void insertUpdate(DocumentEvent e) {
if(jtfKilometers.getText().equals("")){
jtfMiles.setText("");
}else{
jtfMiles.setText(Double.parseDouble(jtfKilometers.getText()) * 0.621371 + "");
}
}
#Override
public void removeUpdate(DocumentEvent e) {
insertUpdate(e);
}
#Override
public void changedUpdate(DocumentEvent e) {
insertUpdate(e);
}
});
jtfMiles.getDocument().addDocumentListener(new DocumentListener(){
#Override
public void insertUpdate(DocumentEvent e) {
if(jtfMiles.getText().equals("")){
jtfKilometers.setText("");
}else{
jtfKilometers.setText(Double.parseDouble(jtfMiles.getText()) * 1.60934 + "");
}
}
#Override
public void removeUpdate(DocumentEvent e) {
insertUpdate(e);
}
#Override
public void changedUpdate(DocumentEvent e) {
insertUpdate(e);
}
});
}
public static void main(String[] args){
Book f = new Book();
f.setDefaultCloseOperation(MyFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
You need to add additional guard on the focus of the text fields, so that you will be modifying only the other text field, not recursively both of them.
jtfKilometers.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
if (jtfKilometers.hasFocus()) { // ADD THIS LINE
if (jtfKilometers.getText().equals("")) {
jtfMiles.setText("");
} else {
jtfMiles.setText(Double.parseDouble(jtfKilometers.getText()) * 0.621371 + "");
}
}
}
and similarly
jtfMiles.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
if (jtfMiles.hasFocus()) { // ADD THIS LINE
if (jtfMiles.getText().equals("")) {
jtfKilometers.setText("");
} else {
jtfKilometers.setText(Double.parseDouble(jtfMiles.getText()) * 1.60934 + "");
}
}
}
An easy fix for this is checking if the frame has focus when the event is triggered. This will prevent the event from triggering back and forth like is happening to you now.
See the adjusted code snippet from your sample below...
public void insertUpdate(DocumentEvent e) {
if(jtfMiles.hasFocus()){//Check for focus here....repeat same check on your other "insertUpdate" method for your other frame.
if(jtfMiles.getText().equals("")){
jtfKilometers.setText("");
}else{
jtfKilometers.setText(Double.parseDouble(jtfMiles.getText()) * 1.60934 + "");
}
}
}
Hope this helps!

Java 1.7 issue, Enter key pressed work differently

I have following code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TesttxtF {
/**
* #param args
*/
public static void main(String[] args) {
TextField txt1 = new TextField();
TextField txt2 = new TextField();
DefaultFocusManager manager = new DefaultFocusManager() {
#Override
public void processKeyEvent(Component focusedComponent, KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_ENTER:
if (e.getID() == KeyEvent.KEY_PRESSED)
super.focusNextComponent(focusedComponent);
else
super.processKeyEvent(focusedComponent, e);
break;
default:
super.processKeyEvent(focusedComponent, e);
break;
}
}
};
FocusManager.setCurrentManager(manager);
JPanel panel = new JPanel();
panel.add(txt1);
panel.add(txt2);
txt1.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
System.out.println("Key keyTyped");
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("Key keyReleased");
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed");
}
});
txt1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Action performed");
}
});
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel, null);
frame.setSize(100, 100);
frame.setVisible(true);
}
}
When run with
jdk1.6.0_18 -> output as following when pressing enter key
Key Pressed
Key keyTyped
Action performed
jdk1.7.0_12 -> output as following when pressing enter key
Key Pressed
What is wrong with java 7 then ?
when i typed any number and clear the console. Then press the Enter key focus changed to next component but actionperformed never fired in java 7. How i can fix it ? i had checked with java 7 update 25 also. i got same result. Can anybody help ?

Categories