Move from bottom animation JDialog - java

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();
}
}

Related

Jcombobox not displayed correctly

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);
}
}

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();
}
}

How to Change the Clockface of an Analog Clock Using BufferedImage in Java

Am trying to modify a java code that implements Analog Clock using BufferedImage. I want the face of the clock to be changed dynamically when a user clicks on a button that scrolls through an array preloaded with the locations of images. So far my attempts have failed. I have two classes; The first Class creates and displays the Analog, and the second class attempts to change the face of the Analog clock using a mutator (setAnalogClockFace()) and an accessor (getAnalogClockFace()). The following is the code for the first Class as found on here, with minor modifications:
package panels;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.util.*;
public class Clock extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
private int hours = 0;
private int minutes = 0;
private int seconds = 0;
private int millis = 0;
private static final int spacing = 10;
private static final float threePi = (float)(3.0 * Math.PI);
private static final float radPerSecMin = (float)(Math.PI/30.0);
private int size; //height and width of clockface
private int centerX;//X coord of middle of clock
private int centerY;//Y coord of middle of clock
private BufferedImage clockImage;
private BufferedImage imageToUse;
private javax.swing.Timer t;
public Clock(){
this.setPreferredSize(new Dimension(203,203));
this.setBackground(getBackground());
this.setForeground(Color.darkGray);
t = new javax.swing.Timer(1000, new ActionListener(){
public void actionPerformed(ActionEvent ae){
update();
}
});
}
public void update(){
this.repaint();
}
public void start(){
t.start();
}
public void stop(){
t.stop();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
int h = getHeight();
size = ((w < h) ? w : h) - 2 * spacing;
centerX = size/2 + spacing;
centerY = size/2 + spacing;
setClockFace(new AnalogClockTimer().getAnalogClockFace());
clockImage = getClockFace();
if (clockImage == null | clockImage.getWidth() != w | clockImage.getHeight() != h){
clockImage = (BufferedImage)(this.createImage(w,h));
Graphics2D gc = clockImage.createGraphics();
gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawClockFace(gc);
}
Calendar now = Calendar.getInstance();
hours = now.get(Calendar.HOUR);
minutes = now.get(Calendar.MINUTE);
seconds = now.get(Calendar.SECOND);
millis = now.get(Calendar.MILLISECOND);
g2d.drawImage(clockImage, null, 0, 0);
drawClockHands(g);
}
private void drawClockHands(Graphics g){
int secondRadius = size/2;
int minuteRadius = secondRadius * 3/4;
int hourRadius = secondRadius/2;
float fseconds = seconds + (float)millis/1000;
float secondAngle = threePi - (radPerSecMin * fseconds);
drawRadius(g, centerX, centerY, secondAngle, 0, secondRadius);
float fminutes = (float)(minutes + fseconds/60.0);
float minuteAngle = threePi - (radPerSecMin * fminutes);
drawRadius(g, centerX, centerY, minuteAngle, 0 , minuteRadius);
float fhours = (float)(hours + fminutes/60.0);
float hourAngle = threePi - (5 * radPerSecMin * fhours);
drawRadius(g, centerX, centerY, hourAngle, 0 ,hourRadius);
}
private void drawClockFace(Graphics g){
//g.setColor(Color.lightGray);
g.fillOval(spacing, spacing, size, size);
//g.setColor(new Color(168,168,168));
g.drawOval(spacing, spacing, size, size);
for(int sec = 0; sec < 60; sec++){
int tickStart;
if(sec%5 == 0){
tickStart = size/2-10;
}else{
tickStart = size/2-5;
}
drawRadius(g, centerX, centerY, radPerSecMin * sec, tickStart, size/2);
}
}
private void drawRadius(Graphics g, int x, int y, double angle,
int minRadius, int maxRadius){
float sine = (float)Math.sin(angle);
float cosine = (float)Math.cos(angle);
int dxmin = (int)(minRadius * sine);
int dymin = (int)(minRadius * cosine);
int dxmax = (int)(maxRadius * sine);
int dymax = (int)(maxRadius * cosine);
g.drawLine(x+dxmin, y+dymin, x+dxmax,y+dymax);
}
public void setClockFace(BufferedImage img){
if(img != null){
imageToUse = img;
}else{
try{
imageToUse =
ImageIO.read(getClass().getClassLoader().getResource("http://imgur.com/T8x0I29"));
}catch(IOException io){
io.printStackTrace();
}
}
}
public BufferedImage getClockFace(){
return imageToUse;
}
}
The second Class that attempts to set the Clock face is:
package panels;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import panels.Clock;
public class AnalogClockTimer extends javax.swing.JPanel implements ActionListener,
MouseListener {
private Clock clock;
/**
*
*/
private static final long serialVersionUID = 1L;
private JButton prevBtn;
private JTextField clockFaceCount;
private JButton nextBtn;
private JPanel buttonedPanel,leftPanel,rightPanel;
private BufferedImage image;
String[] clockFace;
int arrayPointer = 1;
/**
* Auto-generated main method to display this
* JPanel inside a new JFrame.
*/
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new AnalogClockTimer());
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public AnalogClockTimer() {
super();
initGUI();
}
private void initGUI() {
try {
BorderLayout thisLayout = new BorderLayout();
this.setLayout(thisLayout);
this.setPreferredSize(new java.awt.Dimension(283, 233));
this.setBackground(getBackground());
{
clock = new Clock();
add(clock,BorderLayout.CENTER);
clock.start();
clock.setSize(203, 203);
}
{
buttonedPanel = new JPanel();
FlowLayout buttonedPanelLayout = new FlowLayout();
buttonedPanel.setLayout(buttonedPanelLayout);
this.add(buttonedPanel, BorderLayout.SOUTH);
buttonedPanel.setPreferredSize(new java.awt.Dimension(283, 30));
{
prevBtn = new JButton(new ImageIcon(getClass().getClassLoader().getResource("icons/settings_left_rest.png")));
prevBtn.setPreferredSize(new java.awt.Dimension(20, 19));
prevBtn.setBackground(getBackground());
prevBtn.setBorderPainted(false);
prevBtn.setEnabled(false);
prevBtn.addMouseListener(this);
prevBtn.addActionListener(this);
buttonedPanel.add(prevBtn);
}
{
nextBtn = new JButton(new ImageIcon(getClass().getClassLoader().getResource("icons/settings_right_rest.png")));
nextBtn.setPreferredSize(new java.awt.Dimension(20, 19));
nextBtn.setBackground(getBackground());
nextBtn.setBorderPainted(false);
nextBtn.addMouseListener(this);
nextBtn.addActionListener(this);
}
{
clockFaceCount = new JTextField();
clockFaceCount.setPreferredSize(new java.awt.Dimension(50, 19));
clockFaceCount.setBackground(getBackground());
clockFaceCount.setBorder(null);
clockFaceCount.setHorizontalAlignment(SwingConstants.CENTER);
clockFaceCount.setEditable(false);
buttonedPanel.add(clockFaceCount);
buttonedPanel.add(nextBtn);
}
{
clockFace = new String[]{"http://imgur.com/079QSdJ","http://imgur.com/vQ7tZjI",
"http://imgur.com/T8x0I29"};
for(int i = 1; i <= clockFace.length; i++){
if(i == 1){
nextBtn.setEnabled(true);
prevBtn.setEnabled(false);
}
clockFaceCount.setText(arrayPointer+" of "+clockFace.length);
}
}
{
leftPanel = new JPanel();
leftPanel.setPreferredSize(new Dimension(40, getHeight()));
add(leftPanel,BorderLayout.WEST);
}
{
rightPanel = new JPanel();
rightPanel.setPreferredSize(new Dimension(40,getHeight()));
add(rightPanel,BorderLayout.EAST);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void mouseClicked(MouseEvent me) {
if(me.getSource() == prevBtn)
prevBtn.setIcon(new ImageIcon(getClass().getClassLoader().getResource("icons/settings_left_pressed.png")));
else
nextBtn.setIcon(new ImageIcon(getClass().getClassLoader().getResource("icons/settings_right_pressed.png")));
}
#Override
public void mouseEntered(MouseEvent me) {
if(me.getSource()==prevBtn)
prevBtn.setIcon(new ImageIcon(getClass().getClassLoader().getResource("icons/settings_left_hover.png")));
else
nextBtn.setIcon(new ImageIcon(getClass().getClassLoader().getResource("icons/settings_right_hover.png")));
}
#Override
public void mouseExited(MouseEvent me) {
if(me.getSource() == prevBtn)
prevBtn.setIcon(new ImageIcon(getClass().getClassLoader().getResource("icons/settings_left_rest.png")));
else
nextBtn.setIcon(new ImageIcon(getClass().getClassLoader().getResource("icons/settings_right_rest.png")));
}
#Override
public void mousePressed(MouseEvent me) {
if(me.getSource() == prevBtn){
prevBtn.setIcon(new ImageIcon(getClass().getClassLoader().getResource("icons/settings_left_pressed.png")));
}else{
nextBtn.setIcon(new ImageIcon(getClass().getClassLoader().getResource("icons/settings_right_pressed.png")));
}
}
#Override
public void mouseReleased(MouseEvent me) {
if(me.getSource() == prevBtn)
prevBtn.setIcon(new ImageIcon(getClass().getClassLoader().getResource("icons/settings_left_hover.png")));
else
nextBtn.setIcon(new ImageIcon(getClass().getClassLoader().getResource("icons/settings_right_hover.png")));
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == nextBtn){
{
if(arrayPointer < clockFace.length){
++arrayPointer;
prevBtn.setEnabled(true);
if(arrayPointer == clockFace.length)
nextBtn.setEnabled(false);
}
clockFaceCount.setText(arrayPointer + " of " + clockFace.length);
setAnalogClockFace(arrayPointer);
}
}else if(ae.getSource() == prevBtn){
{
if(arrayPointer > 1){
--arrayPointer;
nextBtn.setEnabled(true);
if(arrayPointer == 1){
clockFaceCount.setText(arrayPointer+" of "+clockFace.length);
prevBtn.setEnabled(false);
}
}
clockFaceCount.setText(arrayPointer + " of "+clockFace.length);
setAnalogClockFace(arrayPointer);
}
}
}
private void setAnalogClockFace(int pointerPosition) {
try{
image = ImageIO.read(getClass().getClassLoader().getResource(clockFace[pointerPosition]));
}catch(IOException io){
io.printStackTrace();
}
}
public BufferedImage getAnalogClockFace(){
return image;
}
}
I've been working on this for days, can someone please help me understand what am not doing right? Any help would be greatly appreciated.
Here is an MCVE using a JLabel to achieve the same result:
package panels;
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.*;
import java.awt.BorderLayout;
#SuppressWarnings({"serial"})
public class ClockPanel extends javax.swing.JPanel implements ActionListener {
private JLabel clockImageLabel;
private JPanel buttonsPanel;
private JButton next,prev;
private JTextField displayCount;
String[] imageFaces;
int pointer = 1;
/**
* Auto-generated main method to display this
* JPanel inside a new JFrame.
*/
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new ClockPanel());
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public ClockPanel() {
super();
initGUI();
}
private void initGUI() {
try {
setPreferredSize(new Dimension(203, 237));
BorderLayout panelLayout = new BorderLayout();
setLayout(panelLayout);
{
clockImageLabel = new JLabel();
clockImageLabel.setPreferredSize(new Dimension(203,203));
clockImageLabel.setHorizontalAlignment(SwingConstants.CENTER);
clockImageLabel.setVerticalAlignment(SwingConstants.CENTER);
add(clockImageLabel,BorderLayout.NORTH);
}
{
buttonsPanel = new JPanel();
{
next = new JButton(">");
next.addActionListener(this);
}
{
prev = new JButton("<");
prev.addActionListener(this);
displayCount = new JTextField();
displayCount.setBorder(null);
displayCount.setEditable(false);
displayCount.setBackground(getBackground());
displayCount.setHorizontalAlignment(SwingConstants.CENTER);
buttonsPanel.add(prev);
buttonsPanel.add(displayCount);
displayCount.setPreferredSize(new java.awt.Dimension(45, 23));
buttonsPanel.add(next);
add(buttonsPanel,BorderLayout.SOUTH);
}
{
imageFaces = new String[]{"http://imgur.com/T8x0I29",
"http://imgur.com/079QSdJ","http://imgur.com/vQ7tZjI"
};
for(int i = 1; i < imageFaces.length; i++){
if(i == 1){
next.setEnabled(true);
prev.setEnabled(false);
}
displayCount.setText(pointer+" of "+imageFaces.length);
setLabelImage(pointer);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void setLabelImage(int pointerPosition){
clockImageLabel.setIcon(new ImageIcon(getClass().getClassLoader().getResource(imageFaces[pointerPosition])));
this.repaint();
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == next){
if(pointer < imageFaces.length){
++pointer;
prev.setEnabled(true);
if(pointer == imageFaces.length)next.setEnabled(false);
displayCount.setText(pointer+" of "+imageFaces.length);
setLabelImage(pointer);
}
}else if(ae.getSource() == prev){
if(pointer > 1){
--pointer;
next.setEnabled(true);
if(pointer == 1)prev.setEnabled(false);
displayCount.setText(pointer+" of "+imageFaces.length);
setLabelImage(pointer);
}
}
}
}
Here are 1/2 Images for the code:
HandlessAnalogClock 1
HandlessAnalogClock 2
HandlessAnalogClock 3
This MCVE will successfully flip between two of the three images, but still has problems with ArrayIndexOutOfBoundsException.
That last part is 'Batteries Not Included' (left as an exercise for the user to correct).
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.net.URL;
#SuppressWarnings({"serial"})
public class ClockPanel extends JPanel implements ActionListener {
private JLabel clockImageLabel;
private JPanel buttonsPanel;
private JButton next, prev;
private JTextField displayCount;
BufferedImage[] images;
int pointer = 1;
/**
* Auto-generated main method to display this JPanel inside a new JFrame.
*/
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new ClockPanel());
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
public ClockPanel() {
super();
initGUI();
}
private void initGUI() {
try {
setPreferredSize(new Dimension(203, 237));
BorderLayout panelLayout = new BorderLayout();
setLayout(panelLayout);
clockImageLabel = new JLabel();
clockImageLabel.setPreferredSize(new Dimension(203, 203));
clockImageLabel.setHorizontalAlignment(SwingConstants.CENTER);
clockImageLabel.setVerticalAlignment(SwingConstants.CENTER);
add(clockImageLabel, BorderLayout.NORTH);
buttonsPanel = new JPanel();
next = new JButton(">");
next.addActionListener(this);
prev = new JButton("<");
prev.addActionListener(this);
displayCount = new JTextField();
displayCount.setBorder(null);
displayCount.setEditable(false);
displayCount.setBackground(getBackground());
displayCount.setHorizontalAlignment(SwingConstants.CENTER);
buttonsPanel.add(prev);
buttonsPanel.add(displayCount);
displayCount.setPreferredSize(new java.awt.Dimension(45, 23));
buttonsPanel.add(next);
add(buttonsPanel, BorderLayout.SOUTH);
String[] imageFaces = new String[]{
"http://i.imgur.com/T8x0I29.png",
"http://i.imgur.com/079QSdJ.png",
"http://i.imgur.com/vQ7tZjI.png"
};
images = new BufferedImage[imageFaces.length];
for (int ii=0; ii<imageFaces.length; ii++) {
System.out.println("loading image: " + ii);
images[ii] = ImageIO.read(new URL(imageFaces[ii]));
System.out.println("loaded image: " + images[ii]);
}
setLabelImage(0);
} catch (Exception e) {
e.printStackTrace();
}
}
private void setLabelImage(int pointerPosition) {
System.out.println("setLabelImage: " + pointerPosition);
clockImageLabel.setIcon(new ImageIcon(images[pointerPosition]));
this.repaint();
}
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == next) {
if (pointer < images.length) {
++pointer;
prev.setEnabled(true);
if (pointer == images.length) {
next.setEnabled(false);
}
displayCount.setText(pointer + " of " + images.length);
setLabelImage(pointer);
}
} else if (ae.getSource() == prev) {
if (pointer > 1) {
--pointer;
next.setEnabled(true);
if (pointer == 1) {
prev.setEnabled(false);
}
displayCount.setText(pointer + " of " + images.length);
setLabelImage(pointer);
}
}
}
}
Expanding on #Andrew's example, consider arranging for the index of the current image to wrap-around, as shown in the example cited here.
private int pointer = 0;
...
private void initGUI() {
...
setLabelImage(pointer);
...
}
private void setLabelImage(int pointerPosition) {
System.out.println("setLabelImage: " + pointerPosition);
clockImageLabel.setIcon(new ImageIcon(images[pointerPosition]));
displayCount.setText((pointerPosition + 1) + " of " + images.length);
this.repaint();
}
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == next) {
pointer++;
if (pointer >= images.length) {
pointer = 0;
}
} else if (ae.getSource() == prev) {
pointer--;
if (pointer < 0) {
pointer = images.length - 1;
}
}
setLabelImage(pointer);
}
As an exercise, try to factor out the repeated instantiation of ImageIcon in setLabelImage() by creating a List<ImageIcon> in initGUI().

how to add full image in JDialog this dialog is created by JOptionPane

my question is i want to add full background image if JDialog, this JDialog is created by JOptionPane. This image does not cover full Dialog.
If you have any solution please let me know.
public class BrowseFilePath {
public static final String DIALOG_NAME = "what-dialog";
public static final String PANE_NAME = "what-pane";
private static JDialog loginRegister;
private static String path;
private static JPanel Browse_panel = new JPanel(new BorderLayout());
private static JLabel pathLbl = new JLabel("Please Choose Folder / File");
private static JTextField regtxt_file = new JTextField(30);
private static JButton browse_btn = new JButton("Browse");
private static JButton ok_btn = new JButton("Ok");
private static JButton close_btn = new JButton("Cancel");
/*public static void main(String [] arg){
showFileDialog();
}*/
public static void showFileDialog() {
JOptionPane.setDefaultLocale(null);
JOptionPane pane = new JOptionPane(createRegInputComponent());
pane.setName(PANE_NAME);
loginRegister = pane.createDialog("ShareBLU");
/* try {
loginRegister.setContentPane(new JLabel(new ImageIcon(ImageIO.read(AlertWindow.getBgImgFilePath()))));
} catch (IOException e) {
e.printStackTrace();
}*/
loginRegister.setName(DIALOG_NAME);
loginRegister.setSize(380,150);
loginRegister.setVisible(true);
if(pane.getInputValue().equals("Ok")){
String getTxt = regtxt_file.getText();
BrowseFilePath.setPath(getTxt);
}
else if(pane.getInputValue().equals("Cancel")){
regtxt_file.setText("");
System.out.println("Pressed Cancel Button =======********=");
System.exit(0);
}
}
public static String getPath() {
return path;
}
public static void setPath(String path) {
BrowseFilePath.path = path;
}
private static JComponent createRegInputComponent() {
Browse_panel = new JBackgroundPanel();
Browse_panel.setLayout(new BorderLayout());
Box rows = Box.createVerticalBox();
Browse_panel.setBounds(0,0,380,150);
Browse_panel.add(pathLbl);
pathLbl.setForeground(Color.white);
pathLbl.setBounds(20, 20, 200, 20);
Browse_panel.add(regtxt_file);
regtxt_file.setToolTipText("Select File/Folder..");
regtxt_file.setBounds(20, 40, 220, 20);
Browse_panel.add(browse_btn);
browse_btn.setToolTipText("Browse");
browse_btn.setBounds(250, 40, 90, 20);
Browse_panel.add(ok_btn);
ok_btn.setToolTipText("Ok");
ok_btn.setBounds(40, 75, 80, 20);
Browse_panel.add(close_btn);
close_btn.setToolTipText("Cancel");
close_btn.setBounds(130, 75, 80, 20);
ActionListener chooseMe = createChoiceAction();
ok_btn.addActionListener(chooseMe);
close_btn.addActionListener(chooseMe);
browse_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int selection = JFileChooser.FILES_AND_DIRECTORIES;
fileChooser.setFileSelectionMode(selection);
fileChooser.setAcceptAllFileFilterUsed(false);
int rVal = fileChooser.showOpenDialog(null);
if (rVal == JFileChooser.APPROVE_OPTION) {
path = fileChooser.getSelectedFile().toString();
regtxt_file.setText(path);
}
}
});
rows.add(Box.createVerticalStrut(105));
Browse_panel.add(rows,BorderLayout.CENTER);
return Browse_panel;
}
public static ActionListener createChoiceAction() {
ActionListener chooseMe = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton choice = (JButton) e.getSource();
// find the pane so we can set the choice.
Container parent = choice.getParent();
while (!PANE_NAME.equals(parent.getName())) {
parent = parent.getParent();
}
JOptionPane pane = (JOptionPane) parent;
pane.setInputValue(choice.getText());
// find the dialog so we can close it.
while ((parent != null) && !DIALOG_NAME.equals(parent.getName()))
{
parent = parent.getParent();
//parent.setBounds(0, 0, 350, 150);
}
if (parent != null) {
parent.setVisible(false);
}
}
};
return chooseMe;
}
}
Don't use JOptionPane but use a full-blown JDialog. Set the content pane to a JComponent that overrides paintComponent() and returns an appropriate getPreferredSize().
Example code below:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestBackgroundImage {
private static final String BACKHGROUND_IMAGE_URL = "http://cache2.allpostersimages.com/p/LRG/27/2740/AEPND00Z/affiches/blue-fiber-optic-wires-against-black-background.jpg";
protected void initUI() throws MalformedURLException {
JDialog dialog = new JDialog((Frame) null, TestBackgroundImage.class.getSimpleName());
dialog.setModal(true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
final ImageIcon backgroundImage = new ImageIcon(new URL(BACKHGROUND_IMAGE_URL));
JPanel mainPanel = new JPanel(new BorderLayout()) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage.getImage(), 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width = Math.max(backgroundImage.getIconWidth(), size.width);
size.height = Math.max(backgroundImage.getIconHeight(), size.height);
return size;
}
};
mainPanel.add(new JButton("A button"), BorderLayout.WEST);
dialog.add(mainPanel);
dialog.setSize(400, 300);
dialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestBackgroundImage().initUI();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Don't forget to provide an appropriate parent Frame

Categories