Jcombobox not displayed correctly - java

I'm trying to put a JComboBox on a Jpanel, if i clicked shows the contents of the combobox, but it was not showed. the content appears only if I move the cursor on top of it. the Jpanel contains a Jlabel with a picture and on top of it a Jcombobox.
PanelRegionlACTEL:
package com.springJPA.vue.appACTEL;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jd.swing.custom.component.button.StandardButton;
import com.jd.swing.custom.component.jcombobox.MyComboBoxEditor;
import com.jd.swing.custom.component.jcombobox.MyComboBoxRenderer;
import com.jd.swing.util.Theme;
import com.springJPA.domain.Numero;
import com.springJPA.domain.Region;
import com.springJPA.domain.Resedence;
import com.springJPA.service.ActelsService;
import com.springJPA.service.FonctionDAO;
import com.springJPA.service.NumeroService;
import com.springJPA.service.RegionService;
import com.springJPA.service.ResedenceService;
import com.springJPA.service.VilleService;
import com.springJPA.vue.App;
public class PanelRegionlACTEL extends JPanel {
/**
*
*/
private static final long serialVersionUID = -3805099295102746248L;
public static JComboBox<String> comboBox_gouver;
public static JComboBox<String> comboBox_ACTELS;
public static JComboBox<String> comboBoxVille;
private JButton okButton;
private JButton cancelButton;
private JProgressBar progressBar;
int value = 0;
int nbp = 0;
public int selectedIndexR;
public int selectedIndexA;
public int selectedIndexV;
public JLabel labelR1;
public boolean tr=false;
FonctionDAO fonctionDAO = new FonctionDAO();
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
RegionService rgService = (RegionService) context.getBean("regionService");
ActelsService atlService = (ActelsService) context.getBean("actelService");
VilleService villeService = (VilleService) context.getBean("villeService");
NumeroService numeroService = (NumeroService) context.getBean("numeroService");
ResedenceService resedenceService = (ResedenceService) context.getBean("resedenceService");
/*public static void main(String[] args)
{
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch (Exception e) {
System.out.println("Erreur LookAndFeel"+e);
}
try{
new PanelAccueilACTEL();
}catch (Exception e) {
System.out.println("Erreur App: "+e);
e.printStackTrace();
}
}*/
/**
* Create the panel.
*/
public PanelRegionlACTEL() {
setLayout(null);
setBorder(null);
setOpaque(false);
setBounds(0, 0, 803, 534);
setBackground(new Color(0,0,0,0));
setSize(803, 534);
setVisible(true);
JButton buttonQuitter = new JButton("");
buttonQuitter.setIcon(new ImageIcon(PanelRegionlACTEL.class.getResource("/ap/s/tn/img/btn.PNG")));
buttonQuitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
buttonQuitter.setIcon(new ImageIcon(PanelLoginACTEL.class.getResource("/ap/s/tn/img/btn.PNG")));
buttonQuitter.setOpaque(true);
buttonQuitter.setSelectedIcon(new ImageIcon(App.class.getResource("/ap/s/tn/img/btn2.PNG")));
buttonQuitter.setFocusPainted(false);
buttonQuitter.setContentAreaFilled(false);
buttonQuitter.setBorderPainted(false);
buttonQuitter.setBounds(618, 420, 144, 41);
add(buttonQuitter);
JMenuReseau();
JMenuItemRegion();
JMenuDemandes();
JRadioButtonMenuItemNinstallation();
JRadioButtonMenuItemTransfaire();
JLabel lblLoginApplicationFta = new JLabel("Region application ACTEL");
lblLoginApplicationFta.setFont(new Font("Segoe Print", Font.BOLD, 16));
lblLoginApplicationFta.setForeground(new Color(255, 0, 0));
lblLoginApplicationFta.setBounds(6, 6, 229, 28);
add(lblLoginApplicationFta);
JLabel lblslectionnerUnGouvernorat = new JLabel("<html><font color='#09024D'>S\u00E9lectionner un gouvernorat</font></html>");
lblslectionnerUnGouvernorat.setFont(new Font("SansSerif", Font.PLAIN, 18));
lblslectionnerUnGouvernorat.setBounds(54, 107, 242, 25);
add(lblslectionnerUnGouvernorat);
comboBox_gouver = new JComboBox<String>();
comboBox_gouver.setModel(new DefaultComboBoxModel<String>(new String[] {"---------------------"}));
afficherLISTE_REGION();
comboBox_gouver.setBounds(323, 106, 118, 26);
comboBox_gouver.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectedIndexR = comboBox_gouver.getSelectedIndex();
selectedIndexA = comboBox_ACTELS.getSelectedIndex();
if(selectedIndexR == 0) {
comboBox_ACTELS.setModel(new DefaultComboBoxModel<String> (new String[] {"---------------------"}));
comboBoxVille.setModel(new DefaultComboBoxModel<String>(new String[] {"---------------------"}));
}
else{
afficherLISTE_ACTEL_PAR_REGION();
}
}
});
add(comboBox_gouver);
comboBox_ACTELS = new JComboBox<String>();
//comboBox_ACTELS.setRenderer(new MyComboBoxRenderer());
//comboBox_ACTELS.setEditor(new MyComboBoxEditor());
comboBox_ACTELS.setModel(new DefaultComboBoxModel<String>(new String[] {"---------------------"}));
comboBox_ACTELS.setBounds(323, 134, 118, 26);
comboBox_ACTELS.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e2) {
int indexA = comboBox_ACTELS.getSelectedIndex();
if(indexA == 0){
comboBoxVille.setModel(new DefaultComboBoxModel<String>(new String[] {"---------------------"}));
}
else{
afficherLISTE_VILLE_PAR_ACTEL();
}
}
});
JLabel lblchoixActels = new JLabel("<html><font color='#09024D'>Choix ACTELS</font></html>");
lblchoixActels.setFont(new Font("SansSerif", Font.PLAIN, 18));
lblchoixActels.setBounds(54, 139, 133, 16);
add(lblchoixActels);
add(comboBox_ACTELS);
JLabel lblville = new JLabel("<html><font color='#09024D'>Ville</font></html>");
lblville.setFont(new Font("SansSerif", Font.PLAIN, 18));
lblville.setBounds(54, 170, 42, 16);
add(lblville);
comboBoxVille = new JComboBox<String>();
comboBoxVille.setBounds(323, 165, 118, 26);
comboBoxVille.setModel(new DefaultComboBoxModel<String>(new String[] {"---------------------"}));
add(comboBoxVille);
progressBar = new JProgressBar();
progressBar.setBounds(54, 198, 154, 19);
progressBar.setVisible(false);
add(progressBar);
StandardButton button = new StandardButton("OK", Theme.GLOSSY_BLUE_THEME);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
App.cl_conteneurPaneau.show(App.conteneurPaneau, "panelAccueilACTEL");
int indexRegion = comboBox_gouver.getSelectedIndex();
int indexActel = comboBox_ACTELS.getSelectedIndex();
int indexVille = comboBoxVille.getSelectedIndex();
String region = comboBox_gouver.getSelectedItem().toString();
String ville = comboBoxVille.getSelectedItem().toString();
if((indexRegion==0)&&(indexActel==0)&&(indexVille==0)){
labelR1.setText("selectioner tout champs");
}
else if((indexActel==0)&&(indexVille==0)){
labelR1.setText("selectioner tout champs");
}
else{
action();
labelR1.setForeground(new Color(0, 128, 0));
labelR1.setText("region : "+region);
region = comboBox_gouver.getSelectedItem().toString();
ville = comboBoxVille.getSelectedItem().toString();
PanelAccueilACTEL.getLabelR().setText("<html><body><b>Region: "+region+"</b></body></html>");
PanelAccueilACTEL.getLabelV().setText("<html><body><b>*Ville: "+ville+"</b></body></html>");
remplir_code_postal();
remplir_numero();
remplir_type_voie();
}
}
});
button.setActionCommand("OK");
button.setBounds(54, 250, 80, 28);
add(button);
ImageIcon icon = new ImageIcon(getClass().getResource("/tn/pack/image/cadre-rg.png"));
Image zoom = scaleImage(icon.getImage(), 934);
Icon iconScaled = new ImageIcon(zoom);
labelR1 = new JLabel("");
labelR1.setBounds(250, 258, 133, 14);
add(labelR1);
JLabel cadre = new JLabel(iconScaled);
cadre.setIcon(new ImageIcon(PanelLoginACTEL.class.getResource("/tn/pack/image/cadre-rg.png")));
cadre.setBounds(6, 70, 486, 305);
add(cadre);
JLabel arrirePlan = new JLabel("");
arrirePlan.setIcon(new ImageIcon(PanelRegionlACTEL.class.getResource("/ap/s/tn/img/bot.png")));
arrirePlan.setBounds(0, 0, 803, 534);
add(arrirePlan);
}
public void remplir_type_voie() {
List<Resedence> listeTypeVoie = fonctionDAO.afficherLISTE_TYPE_VOIE(resedenceService);
for(Resedence resedence:listeTypeVoie) {
PanelNouvelleInstallation.comboBox_typeVoie.addItem(resedence.getType_voie());
PanelDemandeTransfertACTEL.comboBox_typeVoieA.addItem(resedence.getType_voie());
PanelDemandeTransfertACTEL.comboBox_typeVoieN.addItem(resedence.getType_voie());
}
}
public void remplir_code_postal() {
PanelNouvelleInstallation.textField_codepostal.setText(getcodePostal()+"");
PanelDemandeTransfertACTEL.textField_codepostalA.setText(getcodePostal()+"");
PanelDemandeTransfertACTEL.textField_codepostalN.setText(getcodePostal()+"");
}
protected void afficherLISTE_VILLE_PAR_ACTEL() {
try {
comboBoxVille.removeAllItems();
String nom_actel = comboBox_ACTELS.getSelectedItem().toString();
int id_actel = fonctionDAO.afficherID_ACTEL_PAR_NOM_ACTEL(atlService, nom_actel);
List<String> listeVille= fonctionDAO.afficherLISTE_VILLE_PAR_ACTEL(villeService, id_actel);
for(String lv:listeVille) {
comboBoxVille.addItem(lv);
}
} catch (Exception e1) {
System.out.println("Erreur SELECT ville");
}
}
protected void afficherLISTE_ACTEL_PAR_REGION() {
comboBox_ACTELS.setModel(new DefaultComboBoxModel<String> (new String[] {"---------------------"}));
comboBoxVille.setModel(new DefaultComboBoxModel<String>(new String[] {"---------------------"}));
List<String> listeActel= fonctionDAO.afficherLISTE_ACTEL_PAR_REGION(atlService, comboBox_gouver.getSelectedIndex()+49);
for(String la:listeActel) {
comboBox_ACTELS.addItem(la);
}
}
private void afficherLISTE_REGION() {
List<Region> listeRegion= fonctionDAO.afficherLISTE_REGION(rgService);
for(Region lr:listeRegion) {
comboBox_gouver.addItem(lr.getNom_region());
}
}
private void JRadioButtonMenuItemTransfaire() {
}
private void JRadioButtonMenuItemNinstallation() {
}
private void JMenuDemandes() {
}
private void JMenuItemRegion() {
}
private void JMenuReseau() {
}
void action() {
new Thread(new Runnable() {
public void run() {
try {
progressBar.setValue(value);
value++;
Thread.sleep(15);
}
catch (InterruptedException ex) {ex.printStackTrace();}
if (progressBar.getPercentComplete() == 1.0) {
tr=true;
}
else { tr=false;
action();}
}
}).start();
}
public int remplir_numero() {
String ville = comboBoxVille.getSelectedItem().toString();
Listnumero.listModel.removeAllElements();
PanelAffectationNumero.comboBox_choixN.removeAllItems();
PanelAffectationNumero.comboBox_choixN.setEnabled(false);
List<Numero> listeNum = fonctionDAO.afficherLISTE_NUMERO(numeroService, fonctionDAO.afficherID_VILLE_PAR_NOM_VILLE(villeService, ville));
if(listeNum!=null){
for(Numero ln:listeNum) {
Listnumero.listModel.addElement(ln.getPlage_numero()+"");
}
return 1;
}
else{
return 0;
}
}
/* public int remplir_resedence(){
PanelNouvelleInstallation.comboBoxResedence.setModel(new DefaultComboBoxModel<String>(new String[] {"-----------"}));
String nom_ville = comboBoxVille.getSelectedItem().toString();
List<Ville> listeVille = fonctionDAO.afficherRESEDENCE_PAR_NOM_VILLE(villeService, nom_ville);
if(listeVille!=null){
for(Ville lv:listeVille) {
PanelNouvelleInstallation.comboBoxResedence.addItem(lv.getResedence());
}
return 1;
}
else{
return 0;
}
}*/
/* public void remplir_voie(){
int indextvoie= PanelNouvelleInstallation.comboBoxTypeVoie.getSelectedIndex();
String type_voie = PanelNouvelleInstallation.comboBoxTypeVoie.getSelectedItem().toString();
String nom_ville = PanelRegionlACTEL.comboBoxVille.getSelectedItem().toString();
if(indextvoie == 0){
PanelNouvelleInstallation.comboBoxVoie.setModel(new DefaultComboBoxModel<String>(new String[] {"----------------"}));
}
else{
PanelNouvelleInstallation.comboBoxVoie.setModel(new DefaultComboBoxModel<String>(new String[] {"----------------"}));
List<Ville> listeVille = fonctionDAO.afficherVOIE_PAR_NOM_VILLE(villeService, nom_ville, type_voie);
if(listeVille!=null){
for(Ville lv: listeVille){
PanelNouvelleInstallation.comboBoxVoie.addItem(lv.getVoie());
}
}
}
}*/
public int getcodePostal() {
String nom_actel = comboBox_ACTELS.getSelectedItem().toString();
String nom_ville = comboBoxVille.getSelectedItem().toString();
return fonctionDAO.afficherCODEP_PAR_NOM_VILLE(villeService, fonctionDAO.afficherNUM_ACTEL_PAR_NOM_ACTEL(atlService, nom_actel)+50, nom_ville);
}
public JButton getOkButton() {
return okButton;
}
public void setOkButton(JButton okButton) {
this.okButton = okButton;
}
public JButton getCancelButton() {
return cancelButton;
}
public void setCancelButton(JButton cancelButton) {
this.cancelButton = cancelButton;
}
public static Image scaleImage(Image source, int width, int height) {
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) img.getGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(source, 0, 0, width, height, null);
g.dispose();
return img;
}
//avec une taille en pixels (=hauteur si portrait, largeur si paysage):
public static Image scaleImage(Image source, int size) {
int width = source.getWidth(null);
int height = source.getHeight(null);
double f = 0;
if (width < height) {//portrait
f = (double) height / (double) width;
width = (int) (size / f);
height = size;
} else {//paysage
f = (double) width / (double) height;
width = size;
height = (int) (size / f);
}
return scaleImage(source, width, height);
}
}

Related

Java no UI update after Thread

So, I have got this problem in my Java Swing project where I am making a bot that automatically runs through a whileloop and outputs a text that the user can define in a textfield.
Here you can see my code for adding a textline into a jlabel into my frame:
btnAddTalking = new JButton("Add");
btnAddTalking.setBounds(144, 211, 146, 23);
btnAddTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!txtTalk.getText().equals("")) {
JLabel newLabel = new JLabel(txtTalk.getText());
newLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
frame.remove(newLabel);
frame.repaint();
}
});
newLabel.setHorizontalAlignment(SwingConstants.CENTER);
newLabel.setBounds(159, yLabel, 101, 20);
frame.getContentPane().add(newLabel);
yLabel = yLabel + 20;
frame.getContentPane().setLayout(null);
frame.repaint();
Talk.addTalk(txtTalk.getText());
}
}
});
frame.getContentPane().add(btnAddTalking);
frame.getContentPane().add(lblNewLabel);
frame.getContentPane().add(lblDelayInMs);
After that I start my bot by pressing the following button:
btnStartTalking = new JButton("Start AutoTalk");
btnStartTalking.setBounds(144, 143, 146, 23);
btnStartTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int robotDelay = Integer.parseInt(timeTalk.getText());
Talk.action = "start";
robotTalk = txtTalk.getText();
if (rdbtnRed.isSelected() == true) {
robotTalk = "red:" + txtTalk.getText();
} else if (rdbtnFlash.isSelected() == true) {
robotTalk = "flash1:" + txtTalk.getText();
} else if (rdbtnGlow.isSelected() == true) {
robotTalk = "glow1:" + txtTalk.getText();
}
autoTalkStart = new Runnable() {
public void run() {
try {
btnStartTalking.setEnabled(false);
btnStopTalking.setEnabled(true);
btnAddTalking.setEnabled(false);
Talk test = new Talk(robotDelay);
} catch (AWTException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(autoTalkStart).start();
}
});
Via that button I start a thread which runs through a code that outputs the string. But after I've runned that Thread, my frame doesn't show newly-added jlabels anymore that you've added by clicking the btnAddTalking-button after you've run the Thread by clicking on the btnStartTalking-button! So, my question is: does anyone now how that's even possible (why my UI doesn't update anymore after i've run the thread)?
Greetz,
Jarnov
Here you can see my whole code for the two classes (class 1):
import java.awt.EventQueue;
import java.awt.event.InputEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import com.sun.glass.events.KeyEvent;
import com.sun.glass.ui.Robot;
import java.awt.AWTException;
import java.awt.BorderLayout;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.GroupLayout.Alignment;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.JRadioButton;
public class AutoTalker {
private static JFrame frame;
private JTextField txtTalk;
private JTextField timeTalk;
public String robotTalk;
private JButton btnStopTalking;
private JButton btnAddTalking;
private JButton btnStartTalking;
private int yLabel = 266;
private Runnable autoTalkStart;
/**
* Launch the application.
*/
public static void NewFrame() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AutoTalker window = new AutoTalker();
window.frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #return
*/
public AutoTalker() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 415);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("AutoTalker");
frame.getContentPane().setLayout(null);
JRadioButton rdbtnGlow = new JRadioButton("Glow");
rdbtnGlow.setBounds(6, 113, 64, 23);
rdbtnGlow.setActionCommand("glow");
frame.getContentPane().add(rdbtnGlow);
JRadioButton rdbtnFlash = new JRadioButton("Flash");
rdbtnFlash.setBounds(182, 113, 69, 23);
rdbtnGlow.setActionCommand("flash");
frame.getContentPane().add(rdbtnFlash);
JRadioButton rdbtnRed = new JRadioButton("Red");
rdbtnRed.setBounds(364, 113, 64, 23);
rdbtnGlow.setActionCommand("red");
frame.getContentPane().add(rdbtnRed);
final ButtonGroup rdbtnPressed = new ButtonGroup();
rdbtnPressed.add(rdbtnRed);
rdbtnPressed.add(rdbtnFlash);
rdbtnPressed.add(rdbtnGlow);
txtTalk = new JTextField();
txtTalk.setBounds(130, 28, 173, 20);
txtTalk.setColumns(10);
btnStopTalking = new JButton("Stop AutoTalk");
btnStopTalking.setBounds(144, 177, 146, 23);
btnStopTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Talk.action = "stop";
btnStartTalking.setEnabled(true);
btnStopTalking.setEnabled(false);
btnAddTalking.setEnabled(true);
frame.repaint();
}
});
btnStartTalking = new JButton("Start AutoTalk");
btnStartTalking.setBounds(144, 143, 146, 23);
btnStartTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int robotDelay = Integer.parseInt(timeTalk.getText());
Talk.action = "start";
robotTalk = txtTalk.getText();
if (rdbtnRed.isSelected() == true) {
robotTalk = "red:" + txtTalk.getText();
} else if (rdbtnFlash.isSelected() == true) {
robotTalk = "flash1:" + txtTalk.getText();
} else if (rdbtnGlow.isSelected() == true) {
robotTalk = "glow1:" + txtTalk.getText();
}
autoTalkStart = new Runnable() {
public void run() {
try {
btnStartTalking.setEnabled(false);
btnStopTalking.setEnabled(true);
btnAddTalking.setEnabled(false);
Talk test = new Talk(robotDelay);
} catch (AWTException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(autoTalkStart).start();
frame.repaint();
}
});
timeTalk = new JTextField();
timeTalk.setBounds(174, 71, 86, 20);
timeTalk.setColumns(10);
JLabel lblNewLabel = new JLabel("Text:");
lblNewLabel.setBounds(24, 28, 46, 20);
JLabel lblDelayInMs = new JLabel("Delay in ms:");
lblDelayInMs.setBounds(24, 71, 101, 20);
frame.getContentPane().add(txtTalk);
frame.getContentPane().add(btnStartTalking);
frame.getContentPane().add(btnStopTalking);
frame.getContentPane().add(timeTalk);
btnAddTalking = new JButton("Add");
btnAddTalking.setBounds(144, 211, 146, 23);
btnAddTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!txtTalk.getText().equals("")) {
JLabel newLabel = new JLabel(txtTalk.getText());
newLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
frame.remove(newLabel);
frame.repaint();
}
});
newLabel.setHorizontalAlignment(SwingConstants.CENTER);
newLabel.setBounds(159, yLabel, 101, 20);
frame.getContentPane().add(newLabel);
yLabel = yLabel + 20;
frame.getContentPane().setLayout(null);
frame.repaint();
Talk.addTalk(txtTalk.getText());
}
}
});
frame.getContentPane().add(btnAddTalking);
frame.getContentPane().add(lblNewLabel);
frame.getContentPane().add(lblDelayInMs);
btnStopTalking.setEnabled(false);
}
}
class 2:
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.ArrayList;
public class Talk extends AutoTalker {
Robot robot = new Robot();
public static String action;
public static ArrayList<String> Talks = new ArrayList<String>();
public Talk(int wait) throws AWTException, InterruptedException {
robot.delay(5000);
while(action == "start") {
for(int i = 0; i < Talks.size();i++) {
String text = Talks.get(i);
type(text);
robot.delay(wait);
}
}
}
public static void addTalk(String text) {
Talks.add(text);
}
private void type(String s)
{
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
switch(c) {
case '!':
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_SHIFT);
robot.keyRelease(KeyEvent.VK_1);
break;
case ':':
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SHIFT);
break;
default:
robot.keyPress(Character.toUpperCase(c));
break;
}
robot.delay(10);
}
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.delay(10);
}
}
Use instead
invalidate();
validate();

Swing delay between calls

I'm trying to make a program that load 4 images, put it in 4 labels and change the icons of each label in the frame regarding the random number in the list, like if it was blinking the images. It need to blink each image in the order that is sorted in comecaJogo() but when I press the btnComecar in the actionPerformed all imagens seems to change at the same time:
Here is my logic class:
public class Logica {
List<Integer> seqAlea = new ArrayList<Integer>();
List<Integer> seqInsere = new ArrayList<Integer>();
int placar = 0;
boolean cabouGame = false;
Random geraNumero = new Random();
int numero;
Timer timer = new Timer(1500,null);
public void comecaJogo() {
for (int i = 0; i < 4; i++) {
numero = geraNumero.nextInt(4) + 1;
seqAlea.add(numero);
}
}
public void piscaImagen(ImageIcon img1, ImageIcon img1b, JLabel lbl) {
timer.addActionListener(new ActionListener() {
int count = 0;
#Override
public void actionPerformed(ActionEvent evt) {
if(lbl.getIcon() != img1){
lbl.setIcon(img1);
} else {
lbl.setIcon(img1b);
}
count++;
if(count == 2){
((Timer)evt.getSource()).stop();
}
}
});
timer.setInitialDelay(1250);
timer.start();
}
}
In the frame:
public class Main extends JFrame implements ActionListener {
JLabel lblImg1 = new JLabel();
JButton btnImg1 = new JButton("Economize Energia");
final URL resource1 = getClass().getResource("/br/unip/IMGs/img1.jpg");
final URL resource1b = getClass().getResource("/br/unip/IMGs/img1_b.png");
ImageIcon img1 = new ImageIcon(resource1);
ImageIcon img1b = new ImageIcon(resource1b);
JButton btnImg2 = new JButton("Preserve o Meio Ambiente");
JLabel lblImg2 = new JLabel("");
final URL resource2 = getClass().getResource("/br/unip/IMGs/img2.jpg");
final URL resource2b = getClass().getResource("/br/unip/IMGs/img2_b.jpg");
ImageIcon img2 = new ImageIcon(resource2);
ImageIcon img2b = new ImageIcon(resource2b);
JButton btnImg3 = new JButton("N\u00E3o \u00E0 polui\u00E7\u00E3o!");
JLabel lblImg3 = new JLabel("");
final URL resource3 = getClass().getResource("/br/unip/IMGs/img3.jpg");
final URL resource3b = getClass().getResource("/br/unip/IMGs/img3_b.jpg");
ImageIcon img3 = new ImageIcon(resource3);
ImageIcon img3b = new ImageIcon(resource3b);
JButton btnImg4 = new JButton("Recicle!");
JLabel lblImg4 = new JLabel("");
final URL resource4 = getClass().getResource("/br/unip/IMGs/img4.jpg");
final URL resource4b = getClass().getResource("/br/unip/IMGs/img4_b.jpg");
ImageIcon img4 = new ImageIcon(resource4);
ImageIcon img4b = new ImageIcon(resource4b);
Logica jogo = new Logica();
JButton btnComecar = new JButton("Come\u00E7ar");
public static void main(String[] args) {
Main window = new Main();
window.setVisible(true);
}
public Main() {
lblImg1.setIcon(img1b);
lblImg1.setBounds(78, 48, 250, 200);
add(lblImg1);
btnImg1.setBounds(153, 259, 89, 23);
btnImg1.addActionListener(this);
add(btnImg1);
setBounds(100, 100, 800, 600);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnImg2.setBounds(456, 272, 186, 23);
btnImg2.addActionListener(this);
lblImg2.setIcon(img2b);
lblImg2.setBounds(421, 61, 250, 200);
add(btnImg2);
add(lblImg2);
btnImg3.setBounds(114, 525, 186, 23);
btnImg3.addActionListener(this);
lblImg3.setIcon(img3b);
lblImg3.setBounds(78, 314, 250, 200);
add(lblImg3);
add(btnImg3);
btnImg4.setBounds(456, 525, 186, 23);
btnImg4.addActionListener(this);
lblImg4.setIcon(img4b);
lblImg4.setBounds(421, 314, 250, 200);
add(lblImg4);
add(btnImg4);
btnComecar.setBounds(68, 14, 89, 23);
btnComecar.addActionListener(this);
add(btnComecar);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource().equals(btnImg1)) {
jogo.piscaImagen(img1, img1b, lblImg1);
} else if (e.getSource().equals(btnComecar)) {
jogo.comecaJogo();
System.out.println(jogo.seqAlea);
for (int i = 0; i < jogo.seqAlea.size(); i++) {
switch (jogo.seqAlea.get(i)) {
case 1:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img1, img1b, lblImg1);
break;
case 2:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img2, img2b, lblImg2);
break;
case 3:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img3, img3b, lblImg3);
break;
case 4:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img4, img4b, lblImg4);
break;
}
}
}
}
}
Thanks for the help!
one at time, like a memory game :)
There are multitudes of ways this might work, for example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main extends JFrame implements ActionListener {
JButton btnImg1 = new JButton();
JButton btnImg2 = new JButton();
JButton btnImg3 = new JButton();
JButton btnImg4 = new JButton();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new Main();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public Main() {
JPanel buttons = new JPanel(new GridLayout(2, 2)) {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
};
buttons.add(btnImg1);
buttons.add(btnImg2);
buttons.add(btnImg3);
buttons.add(btnImg4);
add(buttons);
JButton play = new JButton("Play");
add(play, BorderLayout.SOUTH);
play.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
List<JButton> sequence = new ArrayList<>(Arrays.asList(new JButton[]{btnImg1, btnImg2, btnImg3, btnImg4}));
Collections.shuffle(sequence);
Timer timer = new Timer(1000, new ActionListener() {
private JButton last;
#Override
public void actionPerformed(ActionEvent e) {
if (last != null) {
last.setBackground(null);
}
if (!sequence.isEmpty()) {
JButton btn = sequence.remove(0);
btn.setBackground(Color.RED);
last = btn;
} else {
((Timer)e.getSource()).stop();
}
}
});
timer.setInitialDelay(0);
timer.start();
}
}
This just places all the buttons into a List, shuffles the list and then the Timer removes the first button from the List until all the buttons have been "flashed".
Now this is just using the button's backgroundColor, so you'd need to create a class which allows you to associate the JButton with "on" and "off" images, these would then be added to the List and the Timer executed in a similar manner as above

Check if the jlabel icons are the same and compare with the components of the drawing lines

Hello I have to finish a project but I can't get further. The project is about having jlabels with icons generated dynamically on two sides (left and right) .
The icons are in different order on each side and there is a one to one icon relationship.
As an example one picture : link
Now you can draw lines from the left to the right between those pictures and after clicking on the check button it should tell you if its true or false :
Again one picture : link
My question is how can I compare the icons to know which combination is the right one and after comparing the drawings?
I already created two lists to know the component combination of the drawings.
Here is the code so far -
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
public class CatSameCoins{
public static JLabel label;
public ActionListener btn1Listener;
public ActionListener btn2Listener;
public ActionListener btn3Listener;
public ActionListener btn4Listener;
public ActionListener btn5Listener;
public ActionListener btn6Listener;
public JButton btn1;
public JButton btn2;
public JButton btn3;
public JButton btn4;
public JButton btn5;
public JButton btn6;
public JButton btnCheck;
public ArrayList<String> listto = new ArrayList<String>();
public ArrayList<String> listfrom = new ArrayList<String>();
public static boolean drawing = false;
public static List<Shape> shapes = new ArrayList<Shape> ();
public static Shape currentShape = null;
static Component fromComponent;
private JLabel lblCheck;
public void drawLine(Component from , Component to){
listfrom.add(from.getName()); //first list with component names from where the drawing start
listto.add(to.getName()); //second list with component names where the drawing ends
Point fromPoint = new Point();
Point toPoint = new Point();
fromPoint.x = from.getX()+from.getWidth()/2; //get middle
fromPoint.y = from.getY()+from.getHeight()/2; //get middle
toPoint.x = to.getX()+to.getWidth()/2;
toPoint.y = to.getY()+to.getHeight()/2;
currentShape = new Line2D.Double (fromPoint, toPoint);
shapes.add (currentShape);
label.repaint();
drawing = false;
}
public CatSameCoins(){
JFrame frame = new JFrame ();
frame.getContentPane().setLayout(null);
JButton btnremove = new JButton("remove-drawings");
btnremove.setBounds(139, 39, 216, 23);
btnremove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapes.removeAll(shapes);
listfrom.removeAll(listfrom);
drawing= false;
btn1.addActionListener(btn1Listener);
btn2.addActionListener(btn2Listener);
btn3.addActionListener(btn3Listener);
btn4.addActionListener(btn4Listener);
btn5.addActionListener(btn5Listener);
btn6.addActionListener(btn6Listener);
}
});
frame.getContentPane().add(btnremove);
btn1 = new JButton("1");
btn1.setName("btn1");
btn1.setBounds(21, 88, 45, 97);
btn1Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn1;
btn1.removeActionListener(this);
}
};
btn1.addActionListener(btn1Listener);
frame.getContentPane().add(btn1);
btn2 = new JButton("2");
btn2.setName("btn2");
btn2Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn2;
btn2.removeActionListener(this);
}
};
btn2.addActionListener(btn2Listener);
btn2.setBounds(21, 196, 45, 97);
frame.getContentPane().add(btn2);
btn3 = new JButton("3");
btn3.setName("btn3");
btn3Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn3;
btn3.removeActionListener(this);
}
};
btn3.addActionListener(btn3Listener);
btn3.setBounds(21, 307, 45, 97);
frame.getContentPane().add(btn3);
btn4 = new JButton("4");
btn4.setName("btn4");
btn4Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(drawing == true){
drawLine(fromComponent,btn4);
drawing = false;
btn4.removeActionListener(this);
}
}
};
btn4.addActionListener(btn4Listener);
btn4.setBounds(407, 88, 45, 97);
frame.getContentPane().add(btn4);
btn5 = new JButton("5");
btn5.setName("btn5");
btn5Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(drawing == true){
drawLine(fromComponent,btn5);
drawing = false;
btn5.removeActionListener(this);
}
}
};
btn5.addActionListener(btn5Listener);
btn5.setBounds(407, 202, 45, 91);
frame.getContentPane().add(btn5);
btn6 = new JButton("6");
btn6.setName("btn6");
btn6.setBounds(407, 307, 45, 91);
btn6Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(drawing == true){
drawLine(fromComponent,btn6);
drawing = false;
btn6.removeActionListener(this);
}
}
};
btn6.addActionListener(btn6Listener);
frame.getContentPane().add(btn6);
btnCheck = new JButton("check");
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int i=0;i< listfrom.size();i++){
System.out.println(listfrom.get(i)+" - "+listto.get(i));
}
lblCheck.setText("False");
//if().... lblCheck.setText("True")
//else lblCheck.setText("False")
/*if(btn6.getIcon().toString().equals(btn1.getIcon().toString())){
System.out.println("yes");
}
else{
System.out.println("neah");
}*/
}
});
btnCheck.setBounds(171, 405, 143, 46);
frame.getContentPane().add(btnCheck);
lblCheck = new JLabel("");
lblCheck.setHorizontalAlignment(SwingConstants.CENTER);
lblCheck.setBounds(84, 405, 80, 46);
frame.getContentPane().add(lblCheck);
label = new JLabel (){
protected void paintComponent ( Graphics g )
{
Graphics2D g2d = ( Graphics2D ) g;
g2d.setPaint ( Color.black);
g2d.setStroke(new BasicStroke(5));
for ( Shape shape : shapes )
{
g2d.draw ( shape );
repaint();
}
}
} ;
label.setSize(500,500);
frame.getContentPane().add (label);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize ( 500, 500 );
frame.setLocationRelativeTo ( null );
frame.setVisible ( true );
}
public static void main ( String[] args )
{
new CatSameCoins();
}
}
Would really appreciate for any help ;) .
Its done,
Solution : you can try it just change icon names for the second hashmap
I know this is not the best solution but at least i tried. I will try to improve it.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
public class Hashmap {
private JLabel label;
private ActionListener btn1Listener;
private ActionListener btn2Listener;
private ActionListener btn3Listener;
private ActionListener btn4Listener;
private ActionListener btn5Listener;
private ActionListener btn6Listener;
private JButton btn1;
private JButton btn2;
private JButton btn3;
private JButton btn4;
private JButton btn5;
private JButton btn6;
private JButton btnCheck;
private JButton btnNext;
private boolean drawing = false;
private Shape currentShape = null;
private Component fromComponent;
private JLabel lblCheck;
private List<Shape> shapes = new ArrayList<Shape>();
private HashMap<String, String> userLines = new HashMap<String, String>();
private HashMap<String, String> resultLines = new HashMap<String, String>();
private HashMap<String, String> icons = new HashMap<String, String>();
public void drawLine(Component from, Component to) {
userLines.put(from.getName(), to.getName());
Point fromPoint = new Point();
Point toPoint = new Point();
fromPoint.x = from.getX() + from.getWidth() / 2; // get middle
fromPoint.y = from.getY() + from.getHeight() / 2; // get middle
toPoint.x = to.getX() + to.getWidth() / 2;
toPoint.y = to.getY() + to.getHeight() / 2;
currentShape = new Line2D.Double(fromPoint, toPoint);
shapes.add(currentShape);
label.repaint();
drawing = false;
}
#SuppressWarnings("serial")
public Hashmap() {
loadIcons();
JFrame frame = new JFrame();
frame.getContentPane().setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
JButton btnremove = new JButton("remove-drawings");
btnremove.setBounds(139, 39, 216, 23);
btnremove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapes.removeAll(shapes);
drawing = false;
userLines.clear();
btn1.addActionListener(btn1Listener);
btn2.addActionListener(btn2Listener);
btn3.addActionListener(btn3Listener);
btn4.addActionListener(btn4Listener);
btn5.addActionListener(btn5Listener);
btn6.addActionListener(btn6Listener);
}
});
frame.getContentPane().add(btnremove);
btn1 = new JButton("1");
btn1.setName("1");
btn1Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn1;
}
};
btn1.addActionListener(btn1Listener);
btn1.setBounds(21, 88, 45, 97);
frame.getContentPane().add(btn1);
btn2 = new JButton("2");
btn2.setName("2");
btn2Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn2;
}
};
btn2.addActionListener(btn2Listener);
btn2.setBounds(21, 196, 45, 97);
frame.getContentPane().add(btn2);
btn3 = new JButton("3");
btn3.setName("3");
btn3Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn3;
}
};
btn3.addActionListener(btn3Listener);
btn3.setBounds(21, 307, 45, 97);
frame.getContentPane().add(btn3);
btn4 = new JButton("4");
btn4.setName("4");
btn4Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (drawing == true) {
drawLine(fromComponent, btn4);
drawing = false;
btn4.removeActionListener(this);
if (fromComponent.equals(btn1)) {
btn1.removeActionListener(btn1Listener);
}
if (fromComponent.equals(btn2)) {
btn2.removeActionListener(btn2Listener);
}
if (fromComponent.equals(btn3)) {
btn3.removeActionListener(btn3Listener);
}
}
}
};
btn4.addActionListener(btn4Listener);
btn4.setBounds(407, 88, 45, 97);
frame.getContentPane().add(btn4);
btn5 = new JButton("5");
btn5.setName("5");
btn5Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (drawing == true) {
drawLine(fromComponent, btn5);
drawing = false;
btn5.removeActionListener(this);
if (fromComponent.equals(btn1)) {
btn1.removeActionListener(btn1Listener);
}
if (fromComponent.equals(btn2)) {
btn2.removeActionListener(btn2Listener);
}
if (fromComponent.equals(btn3)) {
btn3.removeActionListener(btn3Listener);
}
}
}
};
btn5.addActionListener(btn5Listener);
btn5.setBounds(407, 202, 45, 91);
frame.getContentPane().add(btn5);
btn6 = new JButton("6");
btn6.setName("6");
btn6Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (drawing == true) {
drawLine(fromComponent, btn6);
drawing = false;
btn6.removeActionListener(this);
if (fromComponent.equals(btn1)) {
btn1.removeActionListener(btn1Listener);
}
if (fromComponent.equals(btn2)) {
btn2.removeActionListener(btn2Listener);
}
if (fromComponent.equals(btn3)) {
btn3.removeActionListener(btn3Listener);
}
}
}
};
btn6.addActionListener(btn6Listener);
btn6.setBounds(407, 307, 45, 91);
frame.getContentPane().add(btn6);
btnCheck = new JButton("check");
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (resultLines.equals(userLines) && !userLines.isEmpty()) {
lblCheck.setText("true");
} else {
lblCheck.setText("false");
}
}
});
btnCheck.setBounds(171, 405, 143, 46);
frame.getContentPane().add(btnCheck);
btnNext = new JButton("next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
userLines.clear();
resultLines.clear();
shapes.removeAll(shapes);
drawing = false;
changeCombination();
btn1.addActionListener(btn1Listener);
btn2.addActionListener(btn2Listener);
btn3.addActionListener(btn3Listener);
btn4.addActionListener(btn4Listener);
btn5.addActionListener(btn5Listener);
btn6.addActionListener(btn6Listener);
}
});
btnNext.setBounds(335, 435, 117, 25);
frame.getContentPane().add(btnNext);
lblCheck = new JLabel("");
lblCheck.setHorizontalAlignment(SwingConstants.CENTER);
lblCheck.setBounds(84, 405, 80, 46);
frame.getContentPane().add(lblCheck);
label = new JLabel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.black);
g2d.setStroke(new BasicStroke(3));
for (Shape shape : shapes) {
g2d.draw(shape);
repaint();
}
}
};
label.setSize(frame.getWidth(), frame.getHeight());
frame.getContentPane().add(label);
frame.setVisible(true);
}
private void loadIcons() {
icons.clear();
icons.put("money/coin2/1_Cent.png", "money/coin2/1_Cent.png");
icons.put("money/coin2/5_Cent.png", "money/coin2/5_Cent.png");
icons.put("money/coin2/10_Cent.png", "money/coin2/10_Cent.png");
icons.put("money/coin2/20_Cent.png", "money/coin2/20_Cent.png");
icons.put("money/coin2/50_Cent.png", "money/coin2/50_Cent.png");
icons.put("money/coin2/2_Euro.png", "money/coin2/2_Euro.png");
icons.put("money/coin2/1_Euro.png", "money/coin2/1_Euro.png");
}
public void changeCombination() {
Random randLeftSide = new Random();
Random randRightSide = new Random();
while (resultLines.size() < 3) {
int left = randLeftSide.nextInt(3 - 1 + 1) + 1;
int right = randRightSide.nextInt(6 - 4 + 1) + 4;
// System.out.println("leftside: "+left+"rightside: "+y);
while (resultLines.containsKey(String.valueOf(left))) {
if (resultLines.size() > 3) {
break;
} else {
left = randLeftSide.nextInt(3 - 1 + 1) + 1;
// System.out.println("leftside : "+left);
}
}
while (resultLines.containsValue(String.valueOf(right))) {
if (resultLines.size() > 3) {
break;
} else {
right = randRightSide.nextInt(6 - 4 + 1) + 4;
// System.out.println("rightside: "+right);
}
}
resultLines.put(String.valueOf(left), String.valueOf(right));
}
// System.out.println("TOTAL MAP: "+resultLines.toString());
changeImages();
}
private void changeImages() {
List<Integer> randomIcon = new ArrayList<Integer>(); //creating array list for the icon random numbers
List<Integer> randomLines = new ArrayList<Integer>(); //creating array list for the lines random numbers
for (int i = 0; i < resultLines.size(); i++) {
int randomIndexIcon = new Random().nextInt(icons.size()); //generate random number for the icons from the hashmap
while (randomIcon.contains(randomIndexIcon)) { //while the list contains the random number generate a new one to prevent printing same pictures
randomIndexIcon = new Random().nextInt(icons.size());
}
randomIcon.add(randomIndexIcon); //add to the array list of the icon random numbers the generated random number
int randomIndexResult = new Random().nextInt(resultLines.size()); //generate random number for the lines
while (randomLines.contains(randomIndexResult)) { //while for second list to prevent generating same numbers
randomIndexResult = new Random().nextInt(resultLines.size());
}
randomLines.add(randomIndexResult); //add to the array list of the lines random numbers the generated random number
Object iconValue = icons.values().toArray()[randomIndexIcon]; //this is to get the icon string
Object valueLeft = resultLines.keySet().toArray()[randomIndexResult]; //this is to get the random key value from the resultLines map (left side)
if (valueLeft.equals("1")) { //check conditions
btn1.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueLeft.equals("2")) {
btn2.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueLeft.equals("3")) {
btn3.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
Object valueRight = resultLines.values().toArray()[randomIndexResult]; //get the values from the hashmap (right side)
if (valueRight.equals("4")) { //check conditions
btn4.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueRight.equals("5")) {
btn5.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueRight.equals("6")) {
btn6.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
}
}
public static void main(String[] args) {
new Hashmap();
}
}

Display array in textboxes in a while loop

I am creating a program that will take the data from several textboxes store in an array and when a next and previous button are pressed display the next or last position in the array, currently the next button gets stuck in a while loop without displaying and I'm not sure how to fix it, I am an amateur and I need help with this.
package major;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.List;
import java.awt.Label;
import javax.swing.JScrollPane;
import javax.swing.JList;
import javax.swing.JButton;
import javax.swing.JScrollBar;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
public class gui {
private JFrame frame;
private JTextField websitetxt;
private JTextField usernametxt;
private JTextField passwordtxt;
private encryptedData[] dataArray;
private int dataArrayMaxIndex;
private int dataArrayMax;
private int dataArrayCurrentIndex;
private JButton btnadd;
private JButton btnnew;
private JButton btndelete;
private JTextField notestxt;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
gui window = new gui();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public gui() {
initialize();
dataArrayMax = 20;
dataArray = new encryptedData[dataArrayMax];
dataArrayMaxIndex = 0;
while (dataArrayMaxIndex < dataArrayMax) {
dataArray[dataArrayMaxIndex] = new encryptedData();
dataArrayMaxIndex++;
}
dataArrayMaxIndex = -1;
dataArrayCurrentIndex = -1;
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 569, 427);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
websitetxt = new JTextField();
websitetxt.setBounds(315, 56, 191, 38);
frame.getContentPane().add(websitetxt);
websitetxt.setColumns(10);
usernametxt = new JTextField();
usernametxt.setColumns(10);
usernametxt.setBounds(315, 105, 191, 38);
frame.getContentPane().add(usernametxt);
passwordtxt = new JTextField();
passwordtxt.setColumns(10);
passwordtxt.setBounds(315, 154, 191, 38);
frame.getContentPane().add(passwordtxt);
JLabel lblWebsite = new JLabel("Website:");
lblWebsite.setBounds(227, 68, 78, 14);
frame.getContentPane().add(lblWebsite);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(227, 117, 78, 14);
frame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(227, 166, 78, 14);
frame.getContentPane().add(lblPassword);
final JButton btnadd = new JButton("Add to Database");
btnadd.setEnabled(false);
btnadd.setBounds(10, 105, 191, 38);
frame.getContentPane().add(btnadd);
JLabel lblPasswordManagerHsc = new JLabel("Password manager hsc 2014");
lblPasswordManagerHsc.setBounds(191, 11, 168, 14);
frame.getContentPane().add(lblPasswordManagerHsc);
final JButton btnnew = new JButton("New Record");
btnnew.setBounds(10, 56, 191, 38);
frame.getContentPane().add(btnnew);
JButton btndelete = new JButton("Delete Record");
btndelete.setBounds(10, 154, 191, 38);
frame.getContentPane().add(btndelete);
JButton btnprev = new JButton("Prev");
btnprev.setBounds(315, 316, 89, 23);
frame.getContentPane().add(btnprev);
JButton btnnext = new JButton("Next");
btnnext.setBounds(417, 316, 89, 23);
frame.getContentPane().add(btnnext);
notestxt = new JTextField();
notestxt.setBounds(315, 203, 191, 102);
frame.getContentPane().add(notestxt);
notestxt.setColumns(10);
JLabel lblnotes = new JLabel("Notes");
lblnotes.setBounds(227, 215, 46, 14);
frame.getContentPane().add(lblnotes);
JButton btngenerate = new JButton("Generate Password");
btngenerate.setBounds(10, 203, 191, 38);
frame.getContentPane().add(btngenerate);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu File = new JMenu("File");
menuBar.add(File);
JMenuItem save = new JMenuItem("Save");
File.add(save);
JMenuItem load = new JMenuItem("Load");
File.add(load);
JMenuItem mntmHelp = new JMenuItem("About");
File.add(mntmHelp);
websitetxt.setEnabled(false);
usernametxt.setEnabled(false);
passwordtxt.setEnabled(false);
notestxt.setEnabled(false);
btnadd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnadd.setEnabled(false);
dataArrayCurrentIndex++;
dataArrayMaxIndex++;
dataArray[dataArrayCurrentIndex].username = usernametxt.getText();
dataArray[dataArrayCurrentIndex].password = passwordtxt.getText();
dataArray[dataArrayCurrentIndex].notes = notestxt.getText();
dataArray[dataArrayCurrentIndex].website = websitetxt.getText();
}
});
btnnew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnnew) {
websitetxt.setEnabled(true);
usernametxt.setEnabled(true);
passwordtxt.setEnabled(true);
notestxt.setEnabled(true);
btnadd.setEnabled(true);
websitetxt.setText("");
usernametxt.setText("");
passwordtxt.setText("");
notestxt.setText("");
}
}
});
btndelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnprev.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnnext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = 0;
while (i < dataArrayMaxIndex) {
dataArrayCurrentIndex = i;
websitetxt.setText(dataArray[i].getWebsitename());
usernametxt.setText(dataArray[i].getUsername());
passwordtxt.setText(dataArray[i].getPassword());
notestxt.setText(dataArray[i].getNotes());
}
i++;
}
});
}
}
package major;
public class encryptedData {
public String website;
public String username;
public String password;
public String notes;
public encryptedData() {
try {
website = "";
username = "";
password = "";
notes = "";
} catch (Exception e) {
}
}
public encryptedData(String w, String u, String p, String n) {
try {
website = w;
username = u;
password = p;
notes = n;
} catch (Exception e) {
}
}
//Access methods
public String getWebsitename() {
return website;
}
public void setWebsiteName(String w) {
website = w;
}
public String getUsername() {
return username;
}
public void setUsername(String u) {
username = u;
}
public String getPassword() {
return password + "";
}
public void setPassword(String p) {
password = p;
}
public String getNotes() {
return notes + "";
}
public void setNotes(String n) {
notes = n;
}
}
You are incrementing i after the while loop in actionPerformed()!
If you had formatted your code better, this would have been obvious:
btnnext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = 0;
while (i<dataArrayMaxIndex) {
dataArrayCurrentIndex = i;
websitetxt.setText(dataArray[i].getWebsitename());
usernametxt.setText(dataArray[i].getUsername());
passwordtxt.setText(dataArray[i].getPassword());
notestxt.setText(dataArray[i].getNotes());
}
i++;
}
});
And this would have been even better:
btnnext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i<dataArrayMaxIndex; i++) {
dataArrayCurrentIndex = i;
websitetxt.setText(dataArray[i].getWebsitename());
usernametxt.setText(dataArray[i].getUsername());
passwordtxt.setText(dataArray[i].getPassword());
notestxt.setText(dataArray[i].getNotes());
}
}
});

Move from bottom animation JDialog

I have write an animation for my JDialog, but if I do it in the listener of a JButton it works but in my constructor no . I have try with a thread and a Timer and it's not working too.
my code :
TestTheDialog.java
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionEvent;
public class TestTheDialog implements ActionListener {
JFrame mainFrame = null;
JButton myButton = null;
public TestTheDialog() {
mainFrame = new JFrame("TestTheDialog Tester");
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
myButton = new JButton("Test the dialog!");
myButton.addActionListener(this);
mainFrame.setLocationRelativeTo(null);
mainFrame.getContentPane().add(myButton);
mainFrame.pack();
mainFrame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(myButton == e.getSource()) {
System.err.println("Opening dialog.");
CustomDialogMessage myDialog = new CustomDialogMessage(mainFrame, true, "+33679149407","azertyuiopqsdfghjklmwxcvbnazertyuiopqsdfghjklmwxcvbn");
System.err.println("After opening dialog.");
if(myDialog.getAnswer()) {
System.err.println("The answer stored in CustomDialog is 'true' (i.e. user clicked yes button.)");
}
else {
System.err.println("The answer stored in CustomDialog is 'false' (i.e. user clicked no button.)");
}
}
}
public static void main(String argv[]) {
TestTheDialog tester = new TestTheDialog();
}
}
CustomDialogMessage.java :
import javax.swing.JDialog;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.util.concurrent.TimeUnit;
public class CustomDialogMessage extends JDialog implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel myPanel = null;
private JButton closeButton = null;
private JButton answerButton = null;
private JButton plusButton = null;
private boolean answer = false;
public boolean getAnswer() { return answer; }
public int dialogWidth = 300;
public int dialogHeight = 100;
String textHeader ="You got a new message from :" ;
public CustomDialogMessage(JFrame frame, boolean modal,String myNumero, String myMessage) {
super(frame, modal);
setUndecorated(true);
setBackground(new Color(82,82,82,175));
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle winSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
final int taskBarHeight = screenSize.height - winSize.height;
myPanel = new JPanel();
myPanel.setPreferredSize(new Dimension(dialogWidth, dialogHeight));
myPanel.setBackground(new Color(1,0,0,0));
myPanel.setLayout(null);
getContentPane().add(myPanel);
JLabel header = new JLabel(textHeader);
FontMetrics fm = header.getFontMetrics( header.getFont());
fm.stringWidth("You got a new message !");
header.setBounds((dialogWidth- fm.stringWidth(textHeader))/2, 0, 200, 30);
myPanel.add(header);
closeButton = new JButton("Close");
closeButton.addActionListener(this);
closeButton.setBounds(210, 75, 90, 25);
myPanel.add(closeButton);
answerButton = new JButton("Answer");
answerButton.addActionListener(this);
answerButton.setBounds(0, 75, 90, 25);
myPanel.add(answerButton);
plusButton = new JButton("Plus");
plusButton.addActionListener(this);
plusButton.setBounds(105, 75, 90, 25);
myPanel.add(plusButton);
pack();
setLocation(screenSize.width-dialogWidth,screenSize.height-dialogHeight-taskBarHeight);
setVisible(true);
}
public void animation(){
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle winSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
int taskBarHeight = screenSize.height - winSize.height;
int i = 0;
while(i<=dialogHeight){
try {
TimeUnit.MILLISECONDS.sleep(50);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
i+=5;
this.setLocation(screenSize.width-dialogWidth,screenSize.height-i-taskBarHeight);
}
}
}
finally i find a way to do it : ( i think it will help many person ;) )
MainWindow.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MainWindow extends JFrame {
private static final long serialVersionUID = 1L;
public MainWindow() throws IOException {
// name of window
this.setTitle("BlueNect");
// size of the window
this.setSize(300, 300);
// to not resize the window
this.setResizable(false);
JButton button = new JButton("Test Notif");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new PopUpMessage().makeUI("0679149407","azertyu iopqsdf ghjklmw xcvbnaze rtyu iopqsdfghjk lmwxcvbn azertyu iopqsdf ghjklmw xcvbnaze rtyu iopqsdfghjk lmwxcvbn azertyu iopqsdf ghjklmw xcvbnaze rtyu iopqsdfghjk lmwxcvbn azertyu iopqsdf ghjklmw xcvbnaze rtyu iopqsdfghjk lmwxcvbn azertyu iopqsdf ghjklmw xcvbnaze rtyu iopqsdfghjk lmwxcvbn");
//new PartialFrame().makeUI("0679149407","azertyu iopqsdf ghjklmw xcvbnaze rtyu iopqsdfghjk");
}
});
this.getContentPane().add(button);
// close safely the frame
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// put the window on the center of the display
this.setLocationRelativeTo(null);
// set the window visible
this.setVisible(true);
}
public static void main(String[] args) {
try {
new MainWindow();
} catch (IOException e) {
e.printStackTrace();
}
}
}
PopUpMessage.java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class PopUpMessage {
private int height = 0;
private Rectangle screenRect = GraphicsEnvironment
.getLocalGraphicsEnvironment().getMaximumWindowBounds();
private JPanel panel = new JPanel();
private JLabel text;
private JLabel messageSMS;
private String messageFull;
private static JTextArea textArea = new JTextArea();
final JButton plus = new JButton("Plus");
final JButton reply = new JButton("Reply");
final JButton close = new JButton("Exit");
final JButton send = new JButton("Send");
private int secondClick = 0;
private static JScrollPane scrollPaneTextArea = new JScrollPane(textArea);
private Dimension panelDimension = new Dimension(300, 100);
private JDialog dialog = new JDialog() {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public void paint(Graphics g) {
g.setClip(0, 0, getWidth(), height);
super.paint(g);
}
};
private Timer timer = new Timer(1, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
height += 5;
if (height == dialog.getHeight()) {
timer.stop();
}
dialog.setLocation(screenRect.width - dialog.getWidth(),
screenRect.height - height);
dialog.repaint();
}
});
private Timer timer2 = new Timer(1, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
height -= 5;
if (height == 0) {
timer.stop();
dialog.dispose();
}
dialog.setLocation(screenRect.width - dialog.getWidth(),
screenRect.height - height);
dialog.repaint();
}
});
public void makeUI(String number, String message) {
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setUndecorated(true);
dialog.setBackground(new Color(1, 0, 0, 0));
panel.setPreferredSize(panelDimension);
panel.setBackground(new Color(22, 83, 206, 200));
panel.setLayout(null);
dialog.setContentPane(panel);
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer2.setInitialDelay(0);
timer2.start();
}
});
close.setBounds(210, 70, 90, 25);
reply.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (secondClick == 0) {
textArea.setColumns(20);
textArea.setLineWrap(true);
textArea.setRows(5);
textArea.setWrapStyleWord(true);
scrollPaneTextArea.setBounds((panel.getWidth()-280)/2, messageSMS.getY()+messageSMS.getHeight(), 280, 90);
panel.add(scrollPaneTextArea);
height = dialog.getHeight() + scrollPaneTextArea.getHeight();
panel.setPreferredSize(new Dimension(panel.getWidth(),
panel.getHeight() + scrollPaneTextArea.getHeight()));
dialog.setLocation(dialog.getX(), dialog.getY() - scrollPaneTextArea.getHeight());
plus.setBounds(plus.getX(), plus.getY()+scrollPaneTextArea.getHeight(), plus.getWidth(), plus.getHeight());
close.setBounds(close.getX(), close.getY()+scrollPaneTextArea.getHeight(), close.getWidth(), close.getHeight());
send.setBounds(0, close.getY(), close.getWidth(), close.getHeight());
panel.remove(reply);
panel.add(send);
dialog.pack();
}
}
});
reply.setBounds(0, 70, 90, 25);
plus.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (secondClick == 0) {
FontMetrics fm = panel.getFontMetrics(messageSMS.getFont());
int sizeMessage = fm.stringWidth(messageSMS.getText());
int decallage = (sizeMessage / 90) * 15;
height = dialog.getHeight() + decallage - fm.getHeight()*3;
panel.setPreferredSize(new Dimension(panel.getWidth(),
panel.getHeight() + decallage - fm.getHeight()*3));
messageSMS.setText("<html><P ALIGN=\"JUSTIFY\">"
+ messageFull);
dialog.setLocation(dialog.getX(), dialog.getY() - decallage
+ fm.getHeight()*3);
close.setBounds(close.getX(), close.getY() + decallage - fm.getHeight()*3, close.getWidth(), close.getHeight());
send.setBounds(send.getX(), send.getY() + decallage - fm.getHeight()*3, send.getWidth(), send.getHeight());
reply.setBounds(reply.getX(), reply.getY() + decallage - fm.getHeight()*3, reply.getWidth(), reply.getHeight());
panel.remove(plus);
scrollPaneTextArea.setBounds(scrollPaneTextArea.getX(), scrollPaneTextArea.getY()+ decallage - fm.getHeight()*3, scrollPaneTextArea.getWidth(), scrollPaneTextArea.getHeight());
messageSMS.setBounds(messageSMS.getX(), messageSMS.getY(), messageSMS.getWidth(), decallage);
dialog.pack();
}
}
});
plus.setBounds(105, 70, 90, 25);
send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer2.setInitialDelay(0);
timer2.start();
}
});
messageFull = message;
text = new JLabel("New message from : " + number);
FontMetrics fm = panel.getFontMetrics(text.getFont());
messageSMS = new JLabel("<html><center>" + message + "</center></html>");
int textSize = fm.stringWidth(text.getText());
text.setBounds((panelDimension.width - textSize) / 2, 0, textSize, 25);
textSize = fm.stringWidth(messageSMS.getText());
if (textSize > 810) {
textSize = 290;
}
messageSMS.setBounds((panelDimension.width - textSize) / 2, 20,
textSize, fm.getHeight()*3);
panel.add(close);
panel.add(reply);
if (fm.stringWidth(messageSMS.getText()) > 870) {
int sizeChar = fm.stringWidth(messageSMS.getText())
/ messageSMS.getText().length();
int allowedChar = 870 / sizeChar;
String temp = message.substring(0, allowedChar - 33) + "...";
messageSMS.setText("<html><center>" + temp + "</center></html>");
panel.add(plus);
}
panel.add(messageSMS);
panel.add(text);
dialog.pack();
dialog.setVisible(true);
timer.setInitialDelay(0);
timer.start();
}
}

Categories