How to Run TimerTask behind JFrame in java - java

I have a problem with the application (GUI JFrame form Class) that I created, I am trying to run a method that contains commands to perform data scanning using java.util.TimerTask. The method I want to run through JCheckBoxMenuItem and will run if I tickcheckBoxMenuItem. The problem is that when I check 'checkBoxMenuItem`, scan method still running but I can not access JFrame (GUI) again.
import Database.KoneksiDatabase2;
import Design.ClButtonTransparan;
import Design.JPanelWithImage;
import Proses.Data.DebitDiberikan;
import Proses.Data.DebitKebutuhan;
import Proses.Data.DebitTersedia;
import Proses.Data.AutoScanNReply;
import Proses.Data.CurahHujan;
import Proses.Data.DataKirim;
import Proses.Data.DataMasuk;
import Proses.Data.Faktor_K;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.util.Timer;
public class FormPAI extends javax.swing.JFrame {
private JPanel contentPane, panel1, panelJam;
private JLabel lbtotQs, lbtotQb, lbtotQa, lbfaktorK, lbQa1, lbQa2, lbQa3;
private JLabel lbQa4, lbQa5, lbQa6, lbQa7, lbQa8, lbQa9, lbQa10, lbQa11;
private JLabel lbQa12, lbQb1, lbQb2, lbQb3, lbQb4, lbQb5, lbQb6, lbQb7;
private JLabel lbQb8, lbQb9, lbQb10, lbQb11, lbQb12, lbTotQ;
private JButton btn1, btn2, btn3, btn4, btn5, btn6;
//public Timer timer2 = null;
private JPopupMenu popUp;
private JMenuItem tulisPesan, inbox, kotakKeluar, pesanTerkirim;
ActionListener aksi, aksiTulisPesan, aksiInbox, aksikotakKeluar, aksiPesanTerkirim;
private Timer timer;
public FormPAI() throws IOException, SQLException {
initComponents();
setTitle("Pembagian Air Irigasi");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 700, 650);
BufferedImage img = ImageIO.read(new File("C:\\Users\\X201\\Documents\\NetBeansProjects\\PembagianAirIrigasi\\src\\img\\bacground3.jpg"));
contentPane = new JPanelWithImage(img);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
setLocationRelativeTo(null);
btnClose();
BufferedImage imgSkema = ImageIO.read(new File("C:\\Users\\X201\\Documents\\NetBeansProjects\\PembagianAirIrigasi\\src\\img\\baturiti3.png"));
panel1 = new JPanelWithImage(resize(imgSkema, 670, 420));
panel1.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel1.setBounds(5, 115, 680, 425);
contentPane.add(panel1);
ClockLabel dateLable = new ClockLabel("date");
ClockLabel timeLable = new ClockLabel("time");
// ClockLabel dayLable = new ClockLabel("day");
panelJam = new JPanel();
panelJam.setBounds(545, 541, 140, 55);
panelJam.setBackground(Color.black);
panelJam.add(timeLable);
panelJam.add(dateLable);
// panelJam.add(dayLable);
contentPane.add(panelJam);
jCheckBoxMenuItem1.setText("Run Gammu");
jCheckBoxMenuItem1.setSelected(false);
jCheckBoxMenuItem1.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
System.out.println("Checked? " + jCheckBoxMenuItem1.isSelected());
int state = e.getStateChange();
if (state == ItemEvent.SELECTED){
try {
scan();
} catch (SQLException ex) {
Logger.getLogger(FormPAI.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
timer.cancel();
}
}
});
}
public void scan() throws SQLException{
java.util.TimerTask task = new java.util.TimerTask() {
DebitKebutuhan dk = new DebitKebutuhan();
#Override
public void run(){
System.out.println("ajik");
DataMasuk obj = new DataMasuk();
DataKirim dkrm = new DataKirim();
CurahHujan ch = new CurahHujan();
String cek = null, processed="";
try {
Connection c = KoneksiDatabase2.getKoneksiDBSMS();
ResultSet rset = c.prepareStatement("SELECT * FROM inbox WHERE Processed='false'").executeQuery();
while (rset.next()){
cek = rset.getString("ID");
processed = rset.getString("Processed");
}
if (cek != null){
obj.ambilTeksPesan();
obj.cekFormatPesan();
if (obj.formatSMS == true && processed.equals("false")){
obj.ambilDataPesan();
obj.simpanPesan_ke_DB();
obj.sendToDataMasuk();
obj.updateDataMasuk();
ch.simpanCHKeDB();
dkrm.sendToOutbox();
obj.tandaiSudahDibalas(cek);
}
}
rset.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
timer = new Timer(true);// true to run timer as daemon thread
timer.schedule(task, 0, 5000);// Run task every 5 second
try {
Thread.sleep(60000*60); // Cancel task after 1 minute.
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
timer.cancel();
}
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = dimg.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return dimg;
}
public final void btnClose(){
ImageIcon idt = new ImageIcon("C:\\Users\\X201\\Documents\\NetBeansProjects\\PembagianAirIrigasi\\src\\img\\exit.png");
Image imgRoll = idt.getImage();
Image newImgRoll = imgRoll.getScaledInstance(65, 65, 100);
ImageIcon icon = new ImageIcon("C:\\Users\\X201\\Documents\\NetBeansProjects\\PembagianAirIrigasi\\src\\img\\shutdown.png");
Image img = icon.getImage();
Image newimg = img.getScaledInstance(65, 65, 100);
btn6 = new ClButtonTransparan("<html><center>"+"KELUAR"+"</center></html>");
btn6.setFont(new Font("Berlin Sans FB Demi", Font.PLAIN,12));
btn6.setBounds(555, 5, 105, 105); // posisi jbutton (x, y) dan ukurunnnya (lebar, tinggi)
btn6.setIcon(new ImageIcon(newimg));
btn6.setRolloverIcon(new ImageIcon (newImgRoll));
btn6.setVerticalTextPosition(SwingConstants.BOTTOM); //membuat text jbutton berada dibawah
btn6.setHorizontalTextPosition(SwingConstants.CENTER); //membuat text jbutton berada ditengah
contentPane.add(btn6);
btn6.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//JOptionPane.showConfirmDialog(rootPane, menuBar);
System.exit(0);
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jCheckBoxMenuItem1.setSelected(true);
jCheckBoxMenuItem1.setText("jCheckBoxMenuItem1");
jCheckBoxMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxMenuItem1ActionPerformed(evt);
}
});
jMenu2.add(jCheckBoxMenuItem1);
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jCheckBoxMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FormPAI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try{
FormPAI frame = new FormPAI();
frame.setVisible(true);
//frame.scan();
}catch(Exception e){
}
}
});
}
// Variables declaration - do not modify
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
// End of variables declaration
}
class ClockLabel extends JLabel implements ActionListener {
String type;
SimpleDateFormat sdf;
public ClockLabel(String type) {
this.type = type;
setForeground(Color.green);
switch (type) {
case "day" : sdf = new SimpleDateFormat("EEEE ");
setFont(new Font("Digital-7", Font.PLAIN, 14));
setHorizontalAlignment(SwingConstants.RIGHT);
break;
case "time" : sdf = new SimpleDateFormat("hh:mm a");
setFont(new Font("sans-serif", Font.PLAIN, 16));
setHorizontalAlignment(SwingConstants.CENTER);
break;
case "date" : sdf = new SimpleDateFormat("dd MMMM yyyy");
setFont(new Font("sans-serif", Font.PLAIN, 20));
setHorizontalAlignment(SwingConstants.CENTER);
break;
default : sdf = new SimpleDateFormat();
break;
}
javax.swing.Timer t = new javax.swing.Timer(1000, this);
t.start();
}
#Override
public void actionPerformed(ActionEvent ae) {
Date d = new Date();
setText(sdf.format(d));
}
}

The problem is that you are putting the UI thread to sleep, and it looks like you are sleeping for longer than you think you are... 60000 * 60 = one hour!
public void scan() throws SQLException{
java.util.TimerTask task = new java.util.TimerTask() {
// ...
};
timer = new Timer(true);// true to run timer as daemon thread
timer.schedule(task, 0, 5000);// Run task every 5 second
try {
//--------------------------------------------------
// This is putting the UI to sleep for an hour!
//--------------------------------------------------
Thread.sleep(60000*60); // Cancel task after 1 minute. <-- NOT 1 minute!
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
timer.cancel();
}
You should try to get all of that business onto a separate thread. It could be done like this:
public void scan() throws SQLException{
Runnable scanRunner = new Runnable() {
public void run() {
java.util.TimerTask task = new java.util.TimerTask() {
// ...
};
timer = new Timer(true);// true to run timer as daemon thread
timer.schedule(task, 0, 5000);// Run task every 5 second
try {
Thread.sleep(1000*60); // Cancel task after 1 minute.
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
timer.cancel();
}
};
new Thread(scanRunner).start();
}
As a side note, there are likely a lot of other issues doing it this way since you could check/uncheck the box in the UI at your leisure, and it would not stop any previous scan tasks... I'll let you manage that situation yourself, or ask a different question.

Related

How to make a JButton with Windows look have a background color and have the click input?

I just implemented the Windows look and feel in my Java application, but all the buttons lost the background color. After some research, I found out that I had to call the method "buttonName.setContentAreaFilled(false);" followed by "buttonName.setBackground(Color.blue);". That worked as expected, until I realized that the buttons lost the input click.
package f.h.projects;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
//import control.Control;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
//import negocios.Usuario;
public class FHProjects extends javax.swing.JFrame implements ActionListener {
private JLabel lCanvas, lLogo, lUsername, lPassword;
private JTextField jUsername, jPassword;
private JButton btnLogin;
private BufferedImage img = null;
//private ProjectsMenu proye;
//private Control ctrl;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new FHProjects().setVisible(true);
} catch (Exception e) {
System.out.println(e.getMessage());
System.exit(0);
}
}
});
}
public FHProjects() throws ClassNotFoundException {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (InstantiationException ex) {
Logger.getLogger(FHProjects.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(FHProjects.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(FHProjects.class.getName()).log(Level.SEVERE, null, ex);
}
//ctrl = new Control();
/**
// try {
/**
setContentPane(lCanvas = new JLabel());
add(lLogo = new JLabel());
lLogo.setBounds(250, 50, 200, 200);
img = ImageIO.read(new File("src/src/mainLogo.png"));
Image dimg1 = img.getScaledInstance(lLogo.getWidth(), lLogo.getHeight(), Image.SCALE_SMOOTH);
ImageIcon imageIcon1 = new ImageIcon(dimg1);
lLogo.setIcon(imageIcon1);
} catch (IOException e) {
System.out.println(e.getMessage());
}
*/
lCanvas.setOpaque(true);
lCanvas.setBackground(java.awt.Color.WHITE);
lCanvas.add(lUsername = new JLabel());
lCanvas.add(lPassword = new JLabel());
lCanvas.add(jUsername = new JTextField());
lCanvas.add(jPassword = new JPasswordField());
lCanvas.add(btnLogin = new JButton());
lUsername.setText("User: ");
lPassword.setText("Password: ");
btnLogin.setText("Login");
btnLogin.setFocusPainted(false);
btnLogin.setBorderPainted(false);
btnLogin.setContentAreaFilled(false);
btnLogin.setOpaque(true);
lUsername.setFont(new java.awt.Font("Tahoma", 1, 20));
lPassword.setFont(new java.awt.Font("Tahoma", 1, 20));
btnLogin.setFont(new java.awt.Font("Tahoma", 1, 15));
btnLogin.setBackground(java.awt.Color.red);
btnLogin.setForeground(java.awt.Color.black);
btnLogin.setBorderPainted(false);
lUsername.setBounds(200, 280, 100, 30);
lUsername.setHorizontalAlignment(SwingConstants.RIGHT);
lPassword.setBounds(153, 330, 147, 30);
lPassword.setHorizontalAlignment(SwingConstants.RIGHT);
jUsername.setBounds(350, 280, 200, 30);
jPassword.setBounds(350, 330, 200, 30);
btnLogin.setBounds(300, 400, 100, 30);
btnLogin.addActionListener(this);
jUsername.setText("developer");
jUsername.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
login();
}
}
});
jPassword.setText("123");
jPassword.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
login();
}
}
});
setTitle("F&H Projects");
setSize(700, 500);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
//setIconImage(Toolkit.getDefaultToolkit().getImage("src/src/mainLogo.png"));
}
public void login() {
boolean accedio = false;
/**if (ctrl.login(jUsername.getText(), jPassword.getText()) != null) {
Usuario user = ctrl.login(jUsername.getText(), jPassword.getText());
setVisible(false);
proye = new ProjectsMenu(this, true, user, ctrl);
accedio = true;
} else if (accedio == false) {
JOptionPane.showMessageDialog(this, "Username or password is incorrect!", "Error!", JOptionPane.ERROR_MESSAGE);
}
*/
System.out.println("Success!");
}
#Override
public void actionPerformed(ActionEvent e) {
JButton obj = (JButton) e.getSource();
if (obj == btnLogin) {
login();
}
}
}
The buttons work as expected, but it bugs me not to have that input click. If I document the method "buttonName.setContentAreaFilled(false);" or set the parameter to true, the input click comes back but I loose the background color.
Is there a way to have the background color and the input click at the same time in a JButton?

jLabel slideshow when a mouse enters a button

I can't get this to work:
public void ru() throws InterruptedException {
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/room.jpg")));
setVisible(true);
Thread.sleep(400);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/ROOMS.jpg")));
setVisible(true);
Thread.sleep(400);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/background.jpg")));
setVisible(true);
}
private void BtnRoomsMouseEntered(java.awt.event.MouseEvent evt) {
try {
ru();
} catch (InterruptedException ex) {
}
}
Any solutions?
I want a jLabel to show a slide show when a mouse enters a certain button and stays like that as long as the mouse is still in a button. If the mouse happens to exit the button, the jlabel will return to a null state. (no more anything.) Is that possible? Please help. I also tried using for statement but no good. I'm using netbeans by the way.
First thing you need to implement a javax.swing.Timer. Trying to call Thread.sleep() will block the Event Dispatch Thread. See How to use Swing Timers. Here is the basic construct
Timer(int delay, ActionListener listener)
where delay is the time in milliseconds you want delayed and the listener will listen for the Timer ActionEvent fired every delay milliseconds.
So you want something like this
public class MyFrame extends javax.swing.JFrame {
private Timer timer = null;
ImageIcon[] icons = new ImageIcon[3];
int index = -1;
public MyFrame() {
initComponents();
icons[0] = new ImageIcon(...);
icons[1] = new ImageIcon(...);
icons[2] = new ImageIcon(...);
timer = new Timer(2000, new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (index + 1 > 2) {
index = 0;
jLabel3.setIcon(icons[index]);
} else {
index++;
jLabel3.setIcon(icons[index]);
}
}
});
}
}
For your button, you need to use mouseEntered and mouseExited, then you can just call timer.start() or timer.stop()
private void jButton1MouseExited(MouseEvent e) {
timer.stop();
}
private void jButton1MouseEntered(MouseEvent e) {
timer.start();
}
If you don't know how to add the MouseListener just right click on the button from the design view and select Event -> Mouse -> mouseEntered. Do the same for mouseExited. You should see the above methods auto-generated for you.
UPDATE
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.WindowConstants;
public class ImageViewer extends javax.swing.JFrame {
private Timer timer = null;
ImageIcon[] icons = new ImageIcon[5];
int index = -1;
public ImageViewer() {
initComponents();
try {
icons[0] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/orange/stackoverflow-4-xxl.png"));
icons[1] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/caribbean-blue/stackoverflow-4-xxl.png"));
icons[2] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/royal-blue/stackoverflow-4-xxl.png"));
icons[3] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/moth-green/stackoverflow-4-xxl.png"));
icons[4] = new ImageIcon(new URL("http://www.iconsdb.com/icons/preview/soylent-red/stackoverflow-4-xxl.png"));
} catch (MalformedURLException ex) {
Logger.getLogger(ImageViewer.class.getName()).log(Level.SEVERE, null, ex);
}
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (index + 1 > 4) {
index = 0;
jLabel1.setIcon(icons[index]);
} else {
index++;
jLabel1.setIcon(icons[index]);
}
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new JButton();
jLabel1 = new JLabel();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent evt) {
jButton1MouseEntered(evt);
}
public void mouseExited(MouseEvent evt) {
jButton1MouseExited(evt);
}
});
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(127, 127, 127))
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 285, GroupLayout.PREFERRED_SIZE)
.addContainerGap(29, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel1, GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addGap(16, 16, 16))
);
pack();
}// </editor-fold>
private void jButton1MouseEntered(MouseEvent evt) {
timer.start();
}
private void jButton1MouseExited(MouseEvent evt) {
timer.stop();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ImageViewer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private JButton jButton1;
private JLabel jLabel1;
// End of variables declaration
}
You want to add a MouseAdapter to the JLabel and use its mouseEntered() and mouseExited() as follows:
jLabel3.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
try {
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/room.jpg")));
setVisible(true);
Thread.sleep(400);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/ROOMS.jpg")));
setVisible(true);
Thread.sleep(400);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adv/background.jpg")));
setVisible(true);
} catch(InterruptedException e) {
}
#Override
public void mouseExited(java.awt.event.MouseEvent evt) {
//whatever you mean by "null state"
}
});

What is the best layout in Java for scrolling text?

im trying to do a bar that show some messages and I got a trouble with it, check the image below to see what I have so far:
http://i.stack.imgur.com/xSMtY.png
So, in the top bar, i have a panel made by myself that contains labels, each message is a label and it will roll in the panel, the problem is when the message go out of the screen i want her to go to the end of the queue, but since im using BoxLayout in my made up JPanel i can't do it, in the white bar, i got the same layout and i get the same problem, i dont know how i can keep rooling without break the chain...
(In Java)
If anyone of you can help me i will be glad for it...
Thank you all in advance for your time :)
Edit: as requested i will post some code here:
this is my custom panel code:
package smstest;
import entidades.MensagemParaEcra;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import static java.lang.Thread.sleep;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/**
*
* #author NEMESIS
*/
public class MyPanel extends JPanel {
private JLabel label;
//private MyPanel panel;
private LinkedList<String> texto;
private LinkedList<MensagemParaEcra> msgs;
private LinkedList<JLabel> labels;
private int x = 0, tamanho;
public MyPanel() {
texto = new LinkedList<>();
msgs = new LinkedList<>();
labels = new LinkedList<>();
//config panel
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
this.setBackground(Color.black);
Dimension dim = new Dimension(1500, 30);
tamanho = 1500;
this.setPreferredSize(dim);
this.repaint();
this.addComponentListener(new ComponentListener() {
#Override
public void componentResized(ComponentEvent e) {
tamanho = MyPanel.this.getWidth();
}
#Override
public void componentMoved(ComponentEvent e) {
}
#Override
public void componentShown(ComponentEvent e) {
}
#Override
public void componentHidden(ComponentEvent e) {
}
});
// start the scrolling of the labels
start();
}
public void addMensagem(MensagemParaEcra msg) {
labels.add(new JLabel(msg.getTexto() + " -- "));
refresh();
}
public void removerMsg(int id) {
int size = msgs.size();
for (int i = 0; i < size; i++) {
if (msgs.get(i).getId() == id) {
msgs.remove(i);
}
}
refresh();
}
private void refresh() {
int size = labels.size();
labels.get(0).setLocation(0, 0);
for (int i = 0; i < size; i++) {
labels.get(i).setForeground(Color.white);
labels.get(i).setFont(new Font("Tahoma", Font.BOLD, 40));
labels.get(i).setOpaque(true);
labels.get(i).setBackground(Color.red);
MyPanel.this.add(labels.get(i));
// since im using a box layout it's useless but otherwise this
// may add my labels one after the other
if (i > 0) {
int largura = labels.get(i - 1).getWidth();
labels.get(i).setLocation(x + largura, 0);
} else {
labels.get(i).setLocation(x, 0);
}
}
}
private void start() {
final Runnable running = new Runnable() {
#Override
public void run() {
MyPanel.this.repaint();
}
};
Thread t = new Thread() {
public void run() {
while (true) {
for (JLabel lb : labels) {
// make the labels get 3 pixels to the left
lb.setLocation(lb.getLocation().x -3, 0);
}
try {
SwingUtilities.invokeAndWait(running);
sleep(30);
} catch (InterruptedException ex) {
Logger.getLogger(MyPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(MyPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
t.start();
}
}
And this is the frame that have the 2 bars for the scrolling text:
package smstest;
import entidades.DadosDaAplicacao;
import entidades.MensagemParaEcra;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import static java.lang.Thread.sleep;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
/**
*
* #author NEMESIS
*/
public final class MonitorDeMensagensFrame extends javax.swing.JFrame {
private static final MonitorDeMensagensFrame instance = new MonitorDeMensagensFrame();
private static Point point = new Point();
private int tamanho = 1500;
private JLabel label;
private JLabel label1;
/**
* Creates new form MonitorDeMensagensFrame
*/
public MonitorDeMensagensFrame() {
initComponents();
MyPanel topPanel = new MyPanel();
// its an undecorated frame so i have the listers to move it
this.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
point.x = e.getX();
point.y = e.getY();
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
Point p = getLocation();
setLocation(p.x + e.getX() - point.x, p.y + e.getY() - point.y);
}
});
// setting the size of the frame
setSize(getRes().width, 73);
setLocation(0, 0);
PanelMsg.repaint();
// create the labels for the below bar
criarPub();
// add messages to the upper bar using a method in MyPanel
// this messages now are made up for tests
topPanel.addMensagem(new MensagemParaEcra(0, "msg 1"));
topPanel.addMensagem(new MensagemParaEcra(1, "msg 2"));
topPanel.addMensagem(new MensagemParaEcra(2, "msg 3"));
topPanel.addMensagem(new MensagemParaEcra(3, "msg 4"));
topPanel.addMensagem(new MensagemParaEcra(4, "msg 5"));
topPanel.addMensagem(new MensagemParaEcra(5, "msg 6"));
topPanel.addMensagem(new MensagemParaEcra(6, "msg 7"));
// start the rolling text on the below bar
startPub();
}
private Dimension getRes() {
Toolkit toolkit = Toolkit.getDefaultToolkit();
// Get the current screen size
Dimension scrnsize = toolkit.getScreenSize();
return scrnsize;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
PanelMsg = new javax.swing.JPanel();
PanelPublicidade = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
getContentPane().setLayout(new java.awt.GridLayout(2, 0));
PanelMsg.setBackground(new java.awt.Color(255, 0, 0));
PanelMsg.setMinimumSize(new java.awt.Dimension(173, 20));
PanelMsg.setLayout(new java.awt.BorderLayout());
getContentPane().add(PanelMsg);
PanelPublicidade.setBackground(new java.awt.Color(102, 255, 102));
PanelPublicidade.setMinimumSize(new java.awt.Dimension(403, 25));
javax.swing.GroupLayout PanelPublicidadeLayout = new javax.swing.GroupLayout(PanelPublicidade);
PanelPublicidade.setLayout(PanelPublicidadeLayout);
PanelPublicidadeLayout.setHorizontalGroup(
PanelPublicidadeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 806, Short.MAX_VALUE)
);
PanelPublicidadeLayout.setVerticalGroup(
PanelPublicidadeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 26, Short.MAX_VALUE)
);
getContentPane().add(PanelPublicidade);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MonitorDeMensagensFrame().setVisible(true);
}
});
}
public static MonitorDeMensagensFrame getInstance() {
return instance;
}
public void criarPub() {
String msg = DadosDaAplicacao.getInstance().getMsgPublicidade();
PanelPublicidade.setLayout(new BoxLayout(PanelPublicidade, BoxLayout.X_AXIS));
PanelPublicidade.setBackground(Color.black);
Dimension dim = new Dimension(1500, 30);
PanelPublicidade.setPreferredSize(dim);
PanelPublicidade.repaint();
PanelPublicidade.addComponentListener(new ComponentListener() {
#Override
public void componentResized(ComponentEvent e) {
tamanho = PanelMsg.getWidth();
}
#Override
public void componentMoved(ComponentEvent e) {
}
#Override
public void componentShown(ComponentEvent e) {
}
#Override
public void componentHidden(ComponentEvent e) {
}
});
label = new JLabel("");
label1 = new JLabel("");
label.setText(msg + " ");
label1.setText(msg + " ");
label.setForeground(Color.black);
label.setFont(new Font("Tahoma", Font.PLAIN, 40));
label.setOpaque(true);
label.setBackground(Color.white);
label1.setForeground(Color.black);
label1.setFont(new Font("Tahoma", Font.PLAIN, 40));
label1.setOpaque(true);
label1.setBackground(Color.white);
PanelPublicidade.add(label);
PanelPublicidade.add(label1);
label.setLocation(PanelPublicidade.getLocation().x, PanelPublicidade.getLocation().y);
label1.setLocation(label.getWidth(), label.getLocation().y);
PanelPublicidade.repaint();
}
public void startPub() {
final int tamanho = label.getWidth();
final Runnable running = new Runnable() {
#Override
public void run() {
PanelPublicidade.repaint();
}
};
Thread t = new Thread() {
#Override
public void run() {
while (true) {
label.setLocation(label.getLocation().x - 3,0);
label1.setLocation(label1.getLocation().x - 3, 0);
// if(label.getLocation().x + tamanho == 0){
// label.setLocation(label1.getLocation().x, 0);
// }
try {
SwingUtilities.invokeAndWait(running);
sleep(28);
} catch (InterruptedException ex) {
Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
t.start();
}
// Variables declaration - do not modify
private javax.swing.JPanel PanelMsg;
private javax.swing.JPanel PanelPublicidade;
// End of variables declaration
}
There is the code...
Thank you for the help :)

Auto clicker UI goes black when started

i have made a simple auto clicker, but when i run it the screen goes black so i cant stop it etc. i dont have a clue what i have done wrong. I thought maybe i had to set focus, but i am not sure.
Code:
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.UIManager;
import javax.swing.JRadioButton;
public class AutoClicker1 extends JFrame {
private JPanel contentPane;
private JTextField textField;
public static int rate;
public static boolean go = false;
public static int time;
public static int multiplyer;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AutoClicker1 frame = new AutoClicker1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public AutoClicker1() {
setTitle("Auto Clicker");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 361, 154);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNoOfClicks = new JLabel("Interval between clicks");
lblNoOfClicks.setBounds(10, 25, 149, 14);
contentPane.add(lblNoOfClicks);
textField = new JTextField();
textField.setBounds(10, 55, 139, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton btnStopf = new JButton("Stop(F11)");
btnStopf.setBounds(203, 45, 89, 23);
contentPane.add(btnStopf);
JButton button = new JButton("Stop(F11)");
button.setBounds(203, 81, 89, 23);
contentPane.add(button);
final JRadioButton rdbtnSeconds = new JRadioButton("Seconds");
rdbtnSeconds.setBounds(6, 81, 65, 23);
contentPane.add(rdbtnSeconds);
final JRadioButton rdbtnMilliseconds = new JRadioButton("Milliseconds");
rdbtnMilliseconds.setBounds(71, 81, 109, 23);
contentPane.add(rdbtnMilliseconds);
btnStopf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
go = false;
}
});
JButton btnStart = new JButton("Start(F10)");
btnStart.setBounds(203, 11, 89, 23);
contentPane.add(btnStart);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
go = true;
if (rdbtnMilliseconds.isSelected()) {
autoClick();
} else {
if (rdbtnSeconds.isSelected()) {
multiplyer = 1000;
autoClick();
}
}
}
});
}
private void autoClick() {
requestFocus();
rate = Integer.parseInt(textField.getText());
time = (rate * multiplyer);
System.out.print(time);
try {
Robot robot = new Robot();
while (true) {
try {
Thread.sleep(rate);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
} catch (InterruptedException ex) {}
}
} catch (AWTException e) {}
}
private void keyListner(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_F10) {
System.out.print("pressed F10");
go = true;
}
if (key == KeyEvent.VK_F11) {
go = false;
}
}
private void setTheme() {
try {
UIManager
.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void checkRate() {
if (rate < 500) {
rate = 0;
}
}
}
You are blocking the Event Dispatch Thread in autoClick() with the while(true), instead of that you can use a Swing Timer.
I suggest not using keyListener for listen only 2 keys, you can use keybindings for that purpose. Also you shouldn't call directly setBounds rely in a proper LayoutManager to position in screen.
You break out of the program loop in your Main method when you enter the wile loop in your AutoClick method.
You could instead run your program in a "game loop".
In the main method what I would do is create a method called run()
public void run()
{
int FPS = 60;
float startTime = System.currentTimeInMillis();
while(started)
{
float currentTime = System.currentTimeInMillis();
float passedTime = currentTime - startTime;
startTime = System.currentTimeInMillis();
if(passedTime > (float) 1000/FPS)
{
update();
}
}
}
and then in the update method put the logic of the program. I know it is a totally different approach to how you are currently doing it but in my opinion it allows for more flexibility.
For example in your action listener you could have it invoke a "startClick()" method
where it sets a boolean value to true and initializes what you intialzie currently in the autoclick method. Then your update() method would look like this:
public void update()
{
if(boolean) //boolean value that startClick sets to true
{
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
}
This way the program isn't stuck in an infinite while-loop and you can control how often it updateswith the FPS variable.

java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver

I have java source,and when I run,it writes
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver
I thinks it is needed ODBC driver,but I can't see it.
Java source code:
import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import java.sql.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.image.*;
import java.awt.event.*;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class a extends javax.swing.JDialog {
private JLabel jLabel1;
private JLabel jLabel2;
private JLabel jLabel3;
private JLabel jLabel4;
private JTextField txtPiradi;
private JTextField txtSaxeli;
private JTextField txtGvari;
Image img;
File file = null;
String path = "";
JTextField text = new JTextField(20);
JButton browse, save;
Connection conn = null;
ResultSet rs = null;
Statement stmt = null;
/**
* Auto-generated main method to display this JDialog
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
wevrtaDamateba inst = new wevrtaDamateba(frame);
inst.setVisible(true);
}
});
}
public wevrtaDamateba(JFrame frame) {
super(frame);
initGUI();
}
private void initGUI() {
try {
{
getContentPane().setLayout(null);
this.setTitle("\u10d0\u10ee\u10d0\u10da\u10d8 \u10ec\u10d4\u10d5\u10e0\u10d8\u10e1 \u10d3\u10d0\u10db\u10d0\u10e2\u10d4\u10d1\u10d0");
{
jLabel1 = new JLabel();
getContentPane().add(jLabel1);
jLabel1.setText("\u10e1\u10d0\u10ee\u10d4\u10da\u10d8:");
jLabel1.setFont(new java.awt.Font("Sylfaen",0,12));
jLabel1.setBounds(78, 21, 60, 40);
}
{
jLabel2 = new JLabel();
getContentPane().add(jLabel2);
jLabel2.setText("\u10d2\u10d5\u10d0\u10e0\u10d8:");
jLabel2.setFont(new java.awt.Font("Sylfaen",0,12));
jLabel2.setBounds(78, 67, 60, 40);
}
{
jLabel3 = new JLabel();
getContentPane().add(jLabel3);
jLabel3.setText("\u10de\u10d8\u10e0\u10d0\u10d3\u10d8 N:");
jLabel3.setFont(new java.awt.Font("Sylfaen",0,12));
jLabel3.setBounds(78, 112, 60, 40);
}
{
jLabel4 = new JLabel();
getContentPane().add(jLabel4);
jLabel4.setText("\u10e1\u10e3\u10e0\u10d0\u10d7\u10d8:");
jLabel4.setFont(new java.awt.Font("Sylfaen",0,12));
jLabel4.setBounds(78, 152, 60, 40);
}
{
txtSaxeli = new JTextField();
getContentPane().add(txtSaxeli);
txtSaxeli.setBounds(161, 28, 180, 23);
}
{
txtGvari = new JTextField();
getContentPane().add(txtGvari);
txtGvari.setBounds(161, 74, 180, 23);
}
{
txtPiradi = new JTextField();
getContentPane().add(txtPiradi);
txtPiradi.setBounds(161, 119, 180, 23);
}
{
browse = new JButton();
getContentPane().add(browse);
browse.setText("\u10e1\u10e3\u10e0\u10d0\u10d7\u10d8\u10e1 \u10d0\u10e0\u10e9\u10d4\u10d5\u10d0");
browse.setBounds(161, 159, 180, 23);
browse.setFont(new java.awt.Font("Sylfaen",0,12));
browse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.addChoosableFileFilter(new ImageFileFilter());
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
path = file.getPath();
ImageIcon icon = new ImageIcon(path);
// label.setIcon(icon);
text.setText(path);
repaint();
}
}
});
}
{
save = new JButton();
getContentPane().add(save);
save.setText("\u10d3\u10d0\u10db\u10d0\u10e2\u10d4\u10d1\u10d0");
save.setBounds(173, 224, 123, 23);
save.setFont(new java.awt.Font("Sylfaen",0,12));
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
File f = new File(path);
String saxeli = txtSaxeli.getText();
String gvari = txtGvari.getText();
int piradi = Integer.parseInt(txtPiradi.getText());
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:Base","","");
PreparedStatement psmnt = conn
.prepareStatement("insert into user('saxeli','gvari','piradi','img') values (?,?,?,?)");
FileInputStream fis = new FileInputStream(f);
psmnt.setString(1, saxeli);
psmnt.setString(2, gvari);
psmnt.setInt(3, piradi);
psmnt.setBinaryStream(4, (InputStream) fis,
(int) (f.length()));
int s = psmnt.executeUpdate();
JOptionPane.showMessageDialog(null,
"Inserted successfully!");
} catch (Exception ex) {
System.out.print(ex);
}
}
});
}
}
this.setSize(665, 346);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void clear() {
// TODO Auto-generated method stub
}
class ImageFileFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File file) {
if (file.isDirectory())
return false;
String name = file.getName().toLowerCase();
return (name.endsWith(".jpg") || name.endsWith(".png") || name
.endsWith(".gif"));
}
public String getDescription() {
return "Images (*.gif,*.bmp, *.jpg, *.png )";
}
}
}
Check whether you have Base ODBC DataSource in your ODBC DataSource Panel.

Categories