There are CheckBoxMenuItems и ButtonGroup. When I set the listener for current CheckBoxMenuItem, the condition is checked and the error is produced in this listener. I have active another CheckBoxMenuItem, and it is not necessary for me, even I will write "return".
Problem is that the method cannot throw exceptions and the class is anonymous.
Here is the code:
mUserMode.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(currentCard == 0) {
return;
}
boolean IsEmptyFields = true, isCheckedAnswers = false;
// check if all fields is fill in ...
endOfCycle: for(Component component: panelForAddingQuesions.getComponents()) {
if(component instanceof JTextField) {
JTextField question = (JTextField)component;
if(question.getText().length() == 0) {
IsEmptyFields = false;
break endOfCycle;
}
}
}
// and if there is one correct answer in every question
// check if all fields is fill in ...
for(Entry<JTextField, ArrayList<JCheckBox>> entrySets: equivalenceOfQuestionFiledsAndItsAnswers.entrySet()) {
isCheckedAnswers = false;
for(JCheckBox checkbox: entrySets.getValue()) {
if(checkbox.isSelected()) {
isCheckedAnswers = true;
}
}
}
if(IsEmptyFields) {
JOptionPane.showMessageDialog(MainActivity.this,
"Error", "Error",
JOptionPane.ERROR_MESSAGE);
}
else if(isCheckedAnswers) {
JOptionPane.showMessageDialog(MainActivity.this,
"Error","Error",
JOptionPane.ERROR_MESSAGE);
}
else {
cardLayout.last(cardPanel);
currentCard = 0;
}
// It doesn't help
//MainActivity.this.mAdminMode.setEnabled(true);
}
});
There is the method(аctionPerformed) in anonymous class. I want on a condition to cancel switching ChechBoxItem of elements i.e. to stop this operation. But as ,anyway , the method аctionPerformed is completed, there will be automatic a switching of checkboxes as it will be notified View. And I need to prevent it directly in a method actionPerformed
You should call MainActivity.this.mAdminMode.setSelected(true);, not setEnabled(true).
Related
I'm trying to break loop using AWTEventListener, but in 'if' after checking if I pressed ctrl+p it says error by the break;
try {
Robot robot = new Robot();
int z = 0;
while(true) {
robot.mouseMove(x + z, y);
z++;
AWTEventListener listener = new AWTEventListener() {
#Override
public void eventDispatched(AWTEvent event) {
try {
KeyEvent evt = (KeyEvent)event;
if(evt.getID() == KeyEvent.KEY_PRESSED && evt.getModifiers() == KeyEvent.CTRL_MASK && evt.getKeyCode() == KeyEvent.VK_P) {
break; //ERROR
}
}
catch(Exception e) {
e.printStackTrace();
}
}
};
Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.KEY_EVENT_MASK);
}
} catch (AWTException e) {
}
I don't think you understand what you're doing when creating the listeners. You're basically creating a class right in place, and that class has a method named eventDispatched(). There's no loop inside eventDispatched(), so there's no loop to break out of.
Furthermore, it's probably a mistake to assume the event is a KeyEvent. That's a side note.
Your listener probably needs to set some field that your while loop is looking at. Instead of while(true) you need to do "while(my listener hasn't set some flag to another value)".
I've been searching how to limit my jFrame to open only one each time it's clicked but no success aparently. My code is like this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
login = true;
InserirCliente tela_inserir = new InserirCliente(login);
jDesktopPane1.add(tela_inserir);
tela_inserir.setVisible(true);
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
login = false;
InserirCliente tela_inserir = new InserirCliente(login);
jDesktopPane1.add(tela_inserir);
tela_inserir.setVisible(true);
}
And there is a JInternalFrame with:
public InserirCliente(boolean login){
initComponents();
if(login){
jPanel1.setVisible(false);
}
else {
}
}
Pretty simple, just testing it all. But how could it be changed to display only the first one and not more then the first as it is beeing clicked? Are there handles so it receives if there are instances of the JInternalFrame already created?
First, make tela_inserir a public/private variable depending on your need:
private InserirCliente tela_inserir;
Now add the following method to your InserirCliente class:
public Boolean checkVisible(){
if(jPanel1 != null){
return jPanel1.isVisible();
}
return false;
}
Now just check if the inner JPanel is null (Not yet created) and not visible when your buttons are pressed:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//Only show new panel if i is not already visible:
if (tela_inserir == null && tela_inserir.checkVisible() == false){
login = true;
tela_inserir = new InserirCliente(login);
jDesktopPane1.add(tela_inserir);
tela_inserir.setVisible(true);
}
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
//Only show new panel if i is not already visible:
if (tela_inserir == null && tela_inserir.checkVisible() == false){
login = false;
InserirCliente tela_inserir = new InserirCliente(login);
jDesktopPane1.add(tela_inserir);
tela_inserir.setVisible(true);
}
}
I'm trying to learn Threads in Swing.
I have a Frame with a JProgressBar (progress), five JButtons (Start, Suspend, Resume, Cancel, Close), and a JLabel (label1).
The frame opens. Only Start is enabled. Start calls my class Progressor:
Updated Again Once and For All
Progressor progressor; //declared as class variable, initialized new in constructor and again in overridden done method
Here's the ButtonListener class:
public class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == jbStart) {
progressor.execute();
label1.setText("Progressing ...");
jbCancel.setEnabled(true);
jbResume.setEnabled(true);
jbSuspend.setEnabled(true);
jbClose.setEnabled(true);
}
if(e.getSource() == jbCancel) {
progressor.cancel(true);
label1.setText("Progress Canceled");
}
if (e.getSource() == jbSuspend) {
label1.setText(progressor.suspendProgress());
}
if (e.getSource() == jbResume) {
label1.setText(progressor.resumeProgress());
}
if (e.getSource() == jbClose) {
dispose();
}
}
}//buttonlistener
Here's the SwingWorker class:
public class Progressor extends SwingWorker<Void, Integer> {
private volatile boolean suspend = false;
private Object lock = new Object();
#Override
protected Void doInBackground() {
for (int i = 0; i <= 10; i++) {
checkForSuspend();
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
}
publish(i);
}
return null;
}
#Override
protected void process(List<Integer> list) {
int value = list.get(list.size() - 1);
progress.setValue(value);
}
public void checkForSuspend() {
synchronized (lock) {
while (suspend) {
try {
lock.wait();
} catch (InterruptedException ie){
}
}
}
}//checkForSuspend
#Override
protected void done() {
label1.setText("All Done. Press close to exit");
progressor = new Progressor();
}
public synchronized String suspendProgress() {
suspend = true;
return "Progress suspended ...";
}
public synchronized String resumeProgress() {
synchronized (lock) {
suspend = false;
lock.notify();
return "Progress resumed ...";
}
}
}//Progressor class
Everything works except the cancel doesn't doesn't actually cancel the thread (the progress bar continues).
Should I suspend it before canceling?
This How to Pause and Resume a Thread in Java from another Thread question looks very similar to yours and has some nice examples in the answers.
As for your own code and why it does not work:
You create a new progressor on every click. You should be using and controlling one, instead of creating new ones every time.
When suspending your progressor finishes work instead of suspending. As the above question states - you should be looking at the flag at some points of your computation and acting on it. Example:
while (!cancel) {
if (!suspended) {
for (int i = 1; i <= 10; i++) {
Thread.sleep(1000);
publish(i);
}
}
}
The above code will suspend when it next reaches 10 (unless you resumed it before that), and finish when you press cancel (Cancel needs to be added as an extra flag in the obvious manner).
Your thread should run inside a while loop that looks for a boolean to change value from another object, then simply change the state with setPause(true/false) when you click the button:
while(true){
if(object_everyone_can_reference.getPause()){
Thread.sleep(1000);
}
}
I have this code here, it's a button that call another jFrame to edit stuff, the stuff goes into a jTable that need user input to update. I want to make this update automatic, by puting in the same button, but nothing hapens when I call the function that update the jTable, problably because the java machine don't wait...
private void editarImovelActionPerformed(java.awt.event.ActionEvent evt) // Button {
int i = 0;
int linha = tabelaImoveis.getSelectedRow(); // tabelaImoveis = jTable
if (tabelaImoveis.isRowSelected(linha)) {
{
try {
Integer codigo = Integer.parseInt(tabelaImoveis.getValueAt(linha, 0).toString());
} catch (Exception e) {
mensagem.message("Linha sem Valor!");
i = 1;
} finally {
if (i == 0) {
Integer codigo = Integer.parseInt(tabelaImoveis.getValueAt(linha, 0).toString());
for (Imovel imovel : imovelLista) {
if (imovel.getCodigo() == codigo) { frmAlterar alterar = new frmAlterar();
alterar.setLocationRelativeTo(null);
alterar.setVisible(true);
alterar.setDefaultCloseOperation(alterar.DISPOSE_ON_CLOSE);
alterar.setarAtributos(imovel);
}
}
}
}
}
} else {
mensagem.message("Select Something!"); // Same as System.out...
}
updatejTable(); // This code here I want to execute after the frame "alterar" closes
}
The answer for this is the same as for all similar questions (and there are many): don't use another JFrame, use a modal JDialog.
if (i == 0) {
Integer codigo = Integer.parseInt(tabelaImoveis.getValueAt(linha, 0).toString());
for (Imovel imovel : imovelLista) {
if (imovel.getCodigo() == codigo) {
frmAlterar alterar = new frmAlterar(); // *** this should be a modal JDialog
alterar.setLocationRelativeTo(null);
// alterar.setVisible(true);
// alterar.setDefaultCloseOperation(alterar.DISPOSE_ON_CLOSE);
alterar.setarAtributos(imovel);
alterar.setVisible(true);
}
}
}
I am looking to be able to verify that a JTextField contains only 'numbers' and no (+ , -) before sending the content of this JTextField in a Sql query (to avoid a SqlException).
I want :
if I enter a letter, a JLabel is displayed and the color of JTextField changes in red.
label_errer.setVisible (true);
if I delete the letter, the JLabel will disappear and the color of JTextField is normal.
label_errer.setVisible (false);
the following code works if I click "enter":
textField_app = new JTextField(3);
textField_app.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTextField source = (JTextField) e.getSource();
String textFieldContent = source.getText();
Color bgColor = Color.RED;
boolean isNumeric=false;
try {
Integer.parseInt(textFieldContent);
isNumeric = true;
bgColor = Color.WHITE;
label_errA.setVisible(false);
} catch (Exception e2) {
// ---> isNumeric=false
}
source.setBackground(bgColor);
if(isNumeric==false){
label_errA.setEnabled(true);
label_errA.setVisible(true);
}
}
});
this solution works, but is there another?
textField_app = new JTextField(3);
KeyListener keyListener = new KeyListener() {
public void keyPressed(KeyEvent keyEvent) {
printIt("Pressed", keyEvent);
}
public void keyReleased(KeyEvent keyEvent) {
printIt("Released", keyEvent);
}
public void keyTyped(KeyEvent keyEvent) {
printIt("Typed", keyEvent);
}
private void printIt(String title, KeyEvent keyEvent) {
int keyCode = keyEvent.getKeyCode();
String keyText = KeyEvent.getKeyText(keyCode).toString();
if(keyCode==(getKeyBinding(keyText))){
textField_app.setBackground(new Color(220, 20, 60));
label_errA.setEnabled(true);
label_errA.setVisible(true);
}
else {
Color bgColor =Color.WHITE;
textField_app.setBackground(bgColor);
label_errA.setEnabled(false);
label_errA.setVisible(false);
}
}
};
public int getKeyBinding(String k){
if(k.equals("A")){
return KeyEvent.VK_A;
} else if(k.equals("B")){
return KeyEvent.VK_B;
} else if(k.equals("C")){
return KeyEvent.VK_C;
} else if(k.equals("D")){
return KeyEvent.VK_D;
} else if(k.equals("E")){
return KeyEvent.VK_E;
} else if(k.equals("F")){
return KeyEvent.VK_F;
} else if(k.equals("G")){
return KeyEvent.VK_G;
} else if(k.equals("H")){
return KeyEvent.VK_H;
} else if(k.equals("I")){
return KeyEvent.VK_I;
} else if(k.equals("J")){
return KeyEvent.VK_J;
} else if(k.equals("K")){
return KeyEvent.VK_K;
} else if(k.equals("L")){
return KeyEvent.VK_L;
} else if(k.equals("M")){
return KeyEvent.VK_M;
} else if(k.equals("N")){
return KeyEvent.VK_N;
} else if(k.equals("O")){
return KeyEvent.VK_O;
} else if(k.equals("P")){
return KeyEvent.VK_P;
} else if(k.equals("Q")){
return KeyEvent.VK_Q;
} else if(k.equals("R")){
return KeyEvent.VK_R;
} else if(k.equals("S")){
return KeyEvent.VK_S;
} else if(k.equals("T")){
return KeyEvent.VK_T;
} else if(k.equals("U")){
return KeyEvent.VK_U;
} else if(k.equals("V")){
return KeyEvent.VK_V;
} else if(k.equals("W")){
return KeyEvent.VK_W;
} else if(k.equals("X")){
return KeyEvent.VK_X;
} else if(k.equals("Y")){
return KeyEvent.VK_Y;
} else if(k.equals("Z")){
return KeyEvent.VK_Z;
}
else{
return 0;
}
}
You are looking for a JFormattedTextField. You have all the information here to get yourself started.
What you should probably do to detect every key press is to use a DocumentListener. But since your goal is validation, take a look at using a DocumentFilter instead. It's a little more complicated, but it's a cleaner way to do it, and you won't get any concurrent modification exceptions.
You can create a DocumentFilter, and then every key press will need to pass the filter's inspection (a rough way of putting it, but fairly accurate). If the filter deems it OK, it puts it through. You can also add any actions of your own, such as turning the field red, as you mentioned.
I think you are looking for the java.awt.event.KeyListener instead of ActionListener. Use the KeyTyped() function.
I wrote a library that I can give you a link to if you want, which gives you Textfields that can only take numbers and nothing else.
Yes, you can look at the source too, no problem.