0% found this document useful (0 votes)
46 views

Programas Java

This document provides code to display an image as the background of a JFrame and add a popup menu. It creates a JDesktopPane with a custom paintComponent method that draws the background image. A JPopupMenu is added to the desktop pane and displayed when the right mouse button is clicked. Menu items are added to the popup menu. The image is retrieved from the classpath and scaled to fit the JFrame size before being drawn.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Programas Java

This document provides code to display an image as the background of a JFrame and add a popup menu. It creates a JDesktopPane with a custom paintComponent method that draws the background image. A JPopupMenu is added to the desktop pane and displayed when the right mouse button is clicked. Menu items are added to the popup menu. The image is retrieved from the classpath and scaled to fit the JFrame size before being drawn.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Dynamically add row to JTable

import javax.swing.table.DefaultTableModel;
1
2 public class DynRowAdd extends javax.swing.JFrame {
3 DefaultTableModel model ;
4 /** Creates new form DynRowAdd */
5 public DynRowAdd() {
6 initComponents();
model = new DefaultTableModel();
7 jTable1.setModel(model);
8 model.addColumn("Id");
9 model.addColumn("First Name");
1 model.addColumn("Last Name");
0 model.addColumn("Company Name");
1 }
private void jButton1ActionPerformed(java.awt.event.ActionEvent
1 evt) {
1
2 model.addRow(new Object[]{jTextField1.getText(),
1 jTextField2.getText(),jTextField3.getText(),jTextField4.getText()}
3 );
1
4 }
1
5 private void jButton2ActionPerformed(java.awt.event.ActionEvent
1 evt) {
// TODO add your handling code here:
6 // remove all row from table
1 if (jTable1.getRowCount() > 0) {
7 for (int i = jTable1.getRowCount() - 1; i > -1; i--) {
1 model.removeRow(i);
8 }
1 }
}
9
2 /**
0 * @param args the command line arguments
2 */
1 public static void main(String args[]) {
2 java.awt.EventQueue.invokeLater(new Runnable() {
2
2 public void run() {
new DynRowAdd().setVisible(true);
3
}
2 });
4 }
2 // Variables declaration - do not modify
5 private javax.swing.JButton jButton1;
2 private javax.swing.JButton jButton2;
private javax.swing.JPanel jPanel1;
6
private javax.swing.JScrollPane jScrollPane1;
2 private javax.swing.JTable jTable1;
7 private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
2 private javax.swing.JTextField jTextField3;
8 private javax.swing.JTextField jTextField4;
2 // End of variables declaration
9 }
3
0
3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2
4
3
4
4
4
5
4
6
4
7
4
8
4
9
5
0
5
1
5
2
5
3

Here are some tips on working with date in Java.

Display Day Name From Date:

1 import java.text.DateFormat;
2 import java.text.ParseException;
3 import java.text.SimpleDateFormat;
4 import java.util.Date;
5
6 public class DayNameFromDate {
7
8 public static void main(String[] args) throws ParseException {
9 String input_date = "19/09/2013";
SimpleDateFormat format1 = new
10
SimpleDateFormat("dd/MM/yyyy");
11 Date dt1 = format1.parse(input_date);
12 DateFormat format2 = new SimpleDateFormat("EEEE");
13 DateFormat format3 = new SimpleDateFormat("EE");
14 String fullDay = format2.format(dt1);
15 String shortDay = format3.format(dt1);
16 System.out.println(fullDay);
17 System.out.println(shortDay);
18 }
19}

Output:
Thursday
Thu
Display Day Name From Date-Another Way:

1 import java.text.DateFormatSymbols;
2 import java.util.Calendar;
3
4 public class DayNameFromDate2 {
5
public static void main(String[] args) {
6
String dayNames[] = new DateFormatSymbols().getWeekdays();
7 Calendar date2 = Calendar.getInstance();
8 System.out.println("Today is "
9 + dayNames[date2.get(Calendar.DAY_OF_WEEK)]);
10 }
11}
12

Output:
Today is Thursday
Add Day to Date:
import java.text.SimpleDateFormat;
1 import java.util.Calendar;
2
3 public class AddDayToDate {
4
5 public static void main(String[] args) throws Exception {
6 SimpleDateFormat sdf = new SimpleDateFormat("yyyy−MM−dd");
7 Calendar c1 = Calendar.getInstance();
8 //c1.set(2013, 9, 19); // set date if you need
9 System.out.println("Date is : " +
sdf.format(c1.getTime()));
10
System.out.println("Next 7 dates from the date are :
11");
12 for (int i = 1; i < 8; i++) {
13 c1.add(Calendar.DATE, i); // or Calendar.DAY_OF_MONTH
14which is a synonym
15 System.out.println(sdf.format(c1.getTime()));
16 c1 = Calendar.getInstance();
17 }
18 }
}

Output:
Date is : 2013−09−19
Next 7 dates from the date are :
2013−09−20
2013−09−21
2013−09−22
2013−09−23
2013−09−24
2013−09−25
2013−09−26
Date To String:

1 import java.text.DateFormat;
import java.text.SimpleDateFormat;
2
import java.util.Calendar;
3 import java.util.Date;
4
5 public class DateToString {
6
7 public static void main(String[] args) {
8 DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss
9 a");
10 Date today = Calendar.getInstance().getTime();
String curDate = df.format(today);
11 System.out.println("Current Date: " + curDate);
12 }
13}
14

String To Date:

1 import java.text.ParseException;
2 import java.text.SimpleDateFormat;
3 import java.util.Date;
4
5 public class StringToDate {
public static void main(String[] args) throws ParseException{
6
String input_date = "19/09/2013";
7 SimpleDateFormat format1 = new
8 SimpleDateFormat("dd/MM/yyyy");
9 Date dt1 = format1.parse(input_date);
10 System.out.println(dt1);
11 }
12}

Display Age At Date:

1 import java.util.Calendar;
2 import java.util.GregorianCalendar;
3
4 public class AgeAtDate {
5
6 public static void main(String[] args) {
// remember ... months are 0−based : jan=0 feb=1 ...
7 System.out.println("1962−11−11 : " + age(1962, 10, 11));
8 System.out.println("1979−02−07 : " + age(1979, 01, 07));
9 }
10
11 private static int age(int y, int m, int d) {
12 Calendar cal = new GregorianCalendar(y, m, d);
13 Calendar now = new GregorianCalendar();
14 int res = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
15 if ((cal.get(Calendar.MONTH) > now.get(Calendar.MONTH))
16 || (cal.get(Calendar.MONTH) ==
now.get(Calendar.MONTH)
17
& cal.get(Calendar.DAY_OF_MONTH) >
18now.get(Calendar.DAY_OF_MONTH))) {
19 res--;
20 }
21 return res;
22 }
23}

In my previous post I have shown you how to insert image with resizing to MySQL db. In
this example I want to display the stored images on to JFrame.

The following method retrieves image from database.

1 public void getImageById(int id) {


2 String query = "select image from save_image where id =
3 ?";
4 try {
5 PreparedStatement stmt = con.prepareStatement(query);
6 stmt.setInt(1, id);
7 ResultSet result = stmt.executeQuery();
byte[] bytes = null;
8
if (result.next()) {
9 bytes = result.getBytes(1);
10 }
11 if (bytes != null) {
12 image = toImage(bytes);
13 }
14
15 } catch (Exception ex) {
16 System.out.println(ex.getMessage());
17 }
18 }

I want to display the image on to a JPanel, so I have created the class-

1private class PicturePanel extends JPanel {


2 @Override
3 public void paintComponent(Graphics g) {
4 super.paintComponent(g);
5 g.drawImage(image, 0, 0, null);
6 this.revalidate();
7 this.repaint();
8 }
}
9

In my JFrame I have created a JPanel like this-

1JPanel pictuLabel;
2pictuLabel = new PicturePanel();
Screenshot:

How to add JPopupMenu to JFrame and image as


background of JFrame
Posted on May 6, 2013 by admin Leave a comment

In this example you can learn how to display an image as a background of JFrame and also
display a popup menu. There are several ways to add image as background of JFrame but in
this way you can use any size of image.

1 import java.awt.*;
2 import java.awt.MediaTracker;
3 import java.awt.Toolkit;
import java.awt.event.*;
4
import javax.swing.*;
5
6 public class BackGroundImage extends JFrame {
7
8 int x, y;
9 JDesktopPane desk;
10 private Image img;
11 JPopupMenu deskMenu;
12 JMenuItem refreshMI, mit2, mit3;
13
14public BackGroundImage() throws HeadlessException {
15 Dimension dim =
Toolkit.getDefaultToolkit().getScreenSize();
16
x = dim.width;
17 y = dim.height;
18 setSize(x, y);
19 setTitle("Background image demo");
20 setDefaultCloseOperation(EXIT_ON_CLOSE);
21 desk = new JDesktopPane() {
22
23 @Override
24 public void paintComponent(Graphics g) {
25 bakImage(g);
26 }
};
27 add(desk);
28 // creating the popup menu items
29 refreshMI = new JMenuItem("Refresh");
30 mit2 = new JMenuItem("New");
31 mit3 = new JMenuItem("Send to..");
32 refreshMI.setBackground(new Color(205, 210, 195));
33 //creating the popup menu which will display when user
34 clicks the right mouse button
35 deskMenu = new JPopupMenu();
deskMenu.add(refreshMI);
36 deskMenu.addSeparator();
37 deskMenu.add(mit2);
38 deskMenu.addSeparator();
39 deskMenu.add(mit3);
40
41 addMouseListener(new MouseAdapter() {
42
43 @Override
44 public void mouseReleased(MouseEvent e) {
45 if (e.isPopupTrigger()) {
46 deskMenu.show(BackGroundImage.this, e.getX(),
e.getY());
47
}
48 }
49 });
50 }
51
52 public void bakImage(Graphics g) {
53 try {
54 String s = "/images/images.jpg";//you need to place
55 the image in images folder.
56 Toolkit kit = Toolkit.getDefaultToolkit();
img = kit.getImage(getClass().getResource(s));
57
img = img.getScaledInstance(1500, -1,
58Image.SCALE_FAST);
59 MediaTracker t = new MediaTracker(this);
60 t.addImage(img, 0);
61 while (true) {
62 try {
63 t.waitForAll();
64 break;
65 } catch (Exception ee) {
66 }
}
67 g.drawImage(img, 0, 0, x, y, null);
68
69 } catch (Exception re) {
70 System.out.println("nor found");
71 }
72 }
73
74 public static void main(String[] args) {
75 new BackGroundImage().setVisible(true);
76 }
77}
78
79
JMenuBar Background Image Example
Posted on November 21, 2013 by admin 2 comments

Several example about JMenuBar background image I have found so far have one limitation
that when you maximize or re-size JFrame, the background image does not fit the width of
JFrame. Here I have used Dimension class to overcome the limitation. Hope you will enjoy.

JMenuBarBackgroundDemo.java

import java.awt.*;
1 import javax.swing.JFrame;
2 import javax.swing.JMenuBar;
3 import javax.swing.JMenu;
4 import javax.swing.JMenuItem;
5
6 public class JMenuBarBackgroundDemo extends JFrame {
7
8 private JMenu mnFile;
9 private JMenuItem mntmNew;
1 private JMenuItem mntmSave;
private JMenuBar menuBar;
0
1
/**
1 * Create the frame.
1 */
2 public JMenuBarBackgroundDemo() {
1 super("Background Image JMenuBar");
3 setResizable(true);
1 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
4 setBounds(100, 100, 482, 361);
1
5 menuBar = new JMenuBar() {
1
@Override
6
public void paintComponent(Graphics g) {
1 Dimension size = this.getSize();
7 g.drawImage(Toolkit.getDefaultToolkit().getImage(ge
1 tClass().getResource("/images/menubg.png")), 0, 0, size.width,
8 size.height, this);
1 }
9 };
2
0 mnFile = new JMenu("File");
2 mntmNew = new JMenuItem("New");
1 mntmSave = new JMenuItem("Save");
2
menuBar.add(mnFile);
2
mnFile.add(mntmNew);
2 mnFile.add(mntmSave);
3
2 setJMenuBar(menuBar);
4 setLocationRelativeTo(null);
2 }
5
/**
2
* Launch the application.
6 */
2 public static void main(String[] args) {
7 EventQueue.invokeLater(new Runnable() {
2
8 @Override
2 public void run() {
9 try {
3 JMenuBarBackgroundDemo frame = new
0 JMenuBarBackgroundDemo();
frame.setVisible(true);
3
1
} catch (Exception e) {
3 e.printStackTrace();
2 }
3 }
3 });
3 }
4 }
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2
4
3
4
4
4
5
4
6
4
7
4
8
4
9
5
0
5
1
5
2
5
3
5
4
5
5
5
6
5
7
5
8
5
9
6
0
6
1
6
2

Status Bar Example for JFrame


Posted on May 21, 2013 by admin 2 comments

This example demonstrates how to create a status bar for JFrame. May be you can try with
different way. This can be a very good idea to add a status bar for java application. Let’s see
how to do this.

Add the following lines to the constructor

1 //Three panels that are to added to the JFrame


2 JPanel statusBar = new JPanel();
3 JLabel welcomedate;
4 JLabel msg;
5
6 //Creating the StatusBar.
7 setLayout(new BorderLayout());//frame layout
8 msg = new JLabel(" " + "Good Day!", JLabel.LEFT);
9 msg.setForeground(Color.black);
msg.setToolTipText("Tool Tip Here");
1 welcomedate = new JLabel();
0 welcomedate.setOpaque(true);//to set the color for jlabel
1 welcomedate.setBackground(Color.black);
1 welcomedate.setForeground(Color.WHITE);
1 statusBar.setLayout(new BorderLayout());
2 statusBar.setBorder(javax.swing.BorderFactory.createEtched
1 Border());
3 statusBar.setBackground(Color.LIGHT_GRAY);
1 statusBar.add(msg, BorderLayout.WEST);
statusBar.add(welcomedate, BorderLayout.EAST);
4
add("South", statusBar);
1 //display date time to status bar
5 timee = new javax.swing.Timer(1000, new ActionListener() {
1
6 @Override
1 public void actionPerformed(ActionEvent e) {
7 java.util.Date now = new java.util.Date();
1 String ss =
8 DateFormat.getDateTimeInstance().format(now);
1 welcomedate.setText(ss);
welcomedate.setToolTipText("Welcome, Today is " +
9
ss);
2
0 }
2 });
1 timee.start();
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
3
3

Upon menu selection change the status bar

1msg.setText("You Clicked on Edit Menu1");

Backup & Restore MySQL Database Using Java-


Complete Solution
Posted on May 8, 2013 by admin 25 comments

MySQL is one of the most commonly used database in the world. It provides a great
command line utility to take backup and restore or we can easily done this job by using
MySQL GUI Tools. But both the cases we need some technical knowledge to do this.

That’s why sometimes we need to integrate a backup & restore system to our Java application
in consideration for user. This is a complete solution about backing up and restoring your
MySQL database through a Java Application.

Basic concept for creating backup:

Process p = null;
1 try {
2 Runtime runtime = Runtime.getRuntime();
3 p = runtime.exec("mysqldump -uroot -pdbpass --add-
4 drop-database -B dbname -r " + "filepath" + "Filename" + ".sql");
5 //change the dbpass and dbname with your dbpass and dbname
6 int processComplete = p.waitFor();
7
if (processComplete == 0) {
8
9
System.out.println("Backup created
10successfully!");
11
12 } else {
13 lblMessage.setText("Could not create the
14backup");
15 }
16
17
18 } catch (Exception e) {
19 e.printStackTrace();
}
Basic concept for restore backup

String[] restoreCmd = new String[]{"mysql ", "--user=" +


1 dbUserName, "--password=" + dbPassword, "-e", "source " + source};
2
3 Process runtimeProcess;
4 try {
5
6 runtimeProcess =
7 Runtime.getRuntime().exec(restoreCmd);
int processComplete = runtimeProcess.waitFor();
8
9
if (processComplete == 0) {
10 System.out.println("Restored successfully!");
11 } else {
12 System.out.println("Could not restore the
13backup!");
14 }
15 } catch (Exception ex) {
16 ex.printStackTrace();
}

Dynamically add row to JTable


Posted on November 8, 2012 by admin 9 comments

Dynamically add row to JTable

1
2 import javax.swing.table.DefaultTableModel;
3
public class DynRowAdd extends javax.swing.JFrame {
4 DefaultTableModel model ;
5 /** Creates new form DynRowAdd */
6 public DynRowAdd() {
7 initComponents();
8 model = new DefaultTableModel();
9 jTable1.setModel(model);
1 model.addColumn("Id");
0 model.addColumn("First Name");
1 model.addColumn("Last Name");
model.addColumn("Company Name");
1 }
1 private void jButton1ActionPerformed(java.awt.event.ActionEvent
2 evt) {
1
3
1 model.addRow(new Object[]{jTextField1.getText(),
4 jTextField2.getText(),jTextField3.getText(),jTextField4.getText()}
1 );
5
1 }
6
private void jButton2ActionPerformed(java.awt.event.ActionEvent
1
evt) {
7 // TODO add your handling code here:
1 // remove all row from table
8 if (jTable1.getRowCount() > 0) {
1 for (int i = jTable1.getRowCount() - 1; i > -1; i--) {
9 model.removeRow(i);
2 }
0 }
2 }
1
/**
2
* @param args the command line arguments
2 */
2 public static void main(String args[]) {
3 java.awt.EventQueue.invokeLater(new Runnable() {
2
4 public void run() {
2 new DynRowAdd().setVisible(true);
5 }
2 });
6 }
2 // Variables declaration - do not modify
private javax.swing.JButton jButton1;
7 private javax.swing.JButton jButton2;
2 private javax.swing.JPanel jPanel1;
8 private javax.swing.JScrollPane jScrollPane1;
2 private javax.swing.JTable jTable1;
9 private javax.swing.JTextField jTextField1;
3 private javax.swing.JTextField jTextField2;
0 private javax.swing.JTextField jTextField3;
3 private javax.swing.JTextField jTextField4;
1 // End of variables declaration
}
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2
4
3
4
4
4
5
4
6
4
7
4
8
4
9
5
0
5
1
5
2
5
3

You might also like