Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,025

HOME > Java Programming > Java GUI สอน Java GUI เขียนโปรแกรม GUI ด้วย Java(Swing/AWT/JFC) > How to use : Java GUI Choose Data from JDialog to Main Frame



Clound SSD Virtual Server

How to use : Java GUI Choose Data from JDialog to Main Frame

How to use : Java GUI Choose Data from JDialog to Main Frame ตัวอย่างการเขียน Java GUI และเทคนิคการเขียน GUI การส่งค่าจาก Dialog มายัง Frame หลัก โดยเราจะออกแบบ Frame หลักเป็นตัว Input ข้อมูล แต่จะสามารถเปิด Dialog เพื่อค้นหาข้อมูลต่าง ๆ แล้วเลือกรายการนั้น และหลังจากที่เลือกค่าใน Dialog แล้ว รายการนั้น ๆ จะถูกส่งกลับมายัง Frame หลัก ซึ่งเป็นเทคนิคที่หลาย ๆ Application ใช้ ช่วยให้โปรแกรมใช้งานง่าย และ น่าสนใจยิ่งขึ้น

Java GUI Choose Data  from JDialog to Main Frame

How to use : Java GUI Choose Data from JDialog to Main Frame

Java GUI Choose Data  from JDialog to Main Frame

แสดง Dialog ด้วย JDialog เพื่อเลือกข้อมูล


ในตัวอย่างนี้จะเลือกใช้ Database ของ MySQL แต่ในกรณีที่จะใช้ร่วมกับ Database อื่น ๆ ก็สามารถทำได้ง่าย ๆ เพียงแค่เปลี่ยน Connector และ Connection String เท่านั้น และการแสดงข้อมูลจะใช้ JTable ของ Java Swing สามารถอ่านเพิ่มเติมได้ที่บทความนี้

Java Connect to MySQL Database (JDBC)


โครงสร้างของ MySQL และ Table

Java GUI Choose Data  from JDialog to Main Frame

CREATE TABLE `customer` (
  `CustomerID` varchar(4) NOT NULL,
  `Name` varchar(50) NOT NULL,
  `Email` varchar(50) NOT NULL,
  `CountryCode` varchar(2) NOT NULL,
  `Budget` double NOT NULL,
  `Used` double NOT NULL,
  PRIMARY KEY  (`CustomerID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- 
-- dump ตาราง `customer`
-- 

INSERT INTO `customer` VALUES ('C001', 'Win Weerachai', '[email protected]', 'TH', 1000000, 600000);
INSERT INTO `customer` VALUES ('C002', 'John  Smith', '[email protected]', 'UK', 2000000, 800000);
INSERT INTO `customer` VALUES ('C003', 'Jame Born', '[email protected]', 'US', 3000000, 600000);
INSERT INTO `customer` VALUES ('C004', 'Chalee Angel', '[email protected]', 'US', 4000000, 100000);

คำสั่งของ SQL ที่สามารถนำไปรันบน Query เพื่อสร้าง Table และ Rows ได้ทันที


Example ตัวอย่างการเขียน Java GUI การสร้าง Dialog Popup เพื่อเลือกข้อมูล

Java GUI Choose Data  from JDialog to Main Frame

MyForm.java
package com.java.myapp;

import java.awt.EventQueue;
import java.awt.TextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class MyForm extends JFrame {

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				MyForm frame = new MyForm();
				frame.setVisible(true);
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MyForm() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 474, 303);
		setTitle("ThaiCreate.Com Java GUI Tutorial");
		getContentPane().setLayout(null);

		// Header Customer Add
		JLabel hCustomerAdd = new JLabel("Customer Add");
		hCustomerAdd.setBounds(144, 21, 132, 14);
		getContentPane().add(hCustomerAdd);

		// *** Header ***//
		JLabel hCustomerID = new JLabel("CustomerID :");
		hCustomerID.setBounds(100, 51, 89, 14);
		getContentPane().add(hCustomerID);

		JLabel hName = new JLabel("Name :");
		hName.setBounds(100, 76, 89, 14);
		getContentPane().add(hName);

		JLabel hEmail = new JLabel("Email :");
		hEmail.setBounds(100, 100, 89, 14);
		getContentPane().add(hEmail);

		JLabel hCountryCode = new JLabel("CountryCode :");
		hCountryCode.setBounds(100, 123, 89, 14);
		getContentPane().add(hCountryCode);

		JLabel hBudget = new JLabel("Budget :");
		hBudget.setBounds(100, 146, 89, 14);
		getContentPane().add(hBudget);

		JLabel hUsed = new JLabel("Used :");
		hUsed.setBounds(100, 171, 89, 14);
		getContentPane().add(hUsed);

		// *** Add Form ***//
		// CustomerID
		final TextField txtCustomerID = new TextField("");
		txtCustomerID.setBounds(207, 51, 99, 20);
		getContentPane().add(txtCustomerID);

		// Name
		final TextField txtName = new TextField("");
		txtName.setBounds(207, 76, 99, 20);
		getContentPane().add(txtName);

		// Email
		final TextField txtEmail = new TextField("");
		txtEmail.setBounds(207, 100, 176, 20);
		getContentPane().add(txtEmail);

		// CountryCode
		final TextField txtCountryCode = new TextField("");
		txtCountryCode.setBounds(207, 123, 99, 20);
		getContentPane().add(txtCountryCode);

		// Budget
		final TextField txtBudget = new TextField("");
		txtBudget.setBounds(207, 146, 99, 20);
		getContentPane().add(txtBudget);

		// Used
		final TextField txtUsed = new TextField("");
		txtUsed.setBounds(207, 171, 99, 20);
		getContentPane().add(txtUsed);
		
		// Choose
		JButton btnChoose = new JButton("...");
		btnChoose.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				MyCustomer customer = new MyCustomer();
				customer.setModal(true);
				customer.setVisible(true);
				
				txtCustomerID.setText(customer.sCustomerID);
				txtName.setText(customer.sName);
				txtEmail.setText(customer.sEmail);
				txtCountryCode.setText(customer.sCountryCode);
				txtBudget.setText(customer.sBudget);
				txtUsed.setText(customer.sUsed);
			}
		});
		btnChoose.setBounds(313, 48, 31, 23);
		getContentPane().add(btnChoose);

	}
}


Java GUI Choose Data  from JDialog to Main Frame

สร้างไฟล์ Class ขึ้นมาใหม่ โดยเลือกเป็น JDialog

Java GUI Choose Data  from JDialog to Main Frame

ตั้งชื่อของ Class

Java GUI Choose Data  from JDialog to Main Frame

ออกแบบ Dialog ด้วย JTable








MyCustomer.java
package com.java.myapp;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class MyCustomer extends JDialog {

	public String sCustomerID;
	public String sName;
	public String sEmail;
	public String sCountryCode;
	public String sBudget;
	public String sUsed;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			MyCustomer dialog = new MyCustomer();
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the dialog.
	 */
	public MyCustomer() {
		setBounds(100, 100, 564, 241);
		setTitle("Choose Customer");

		getContentPane().setLayout(null);
		
		// ScrollPane
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(62, 27, 440, 93);
		getContentPane().add(scrollPane);
		
		// Table
		final JTable table = new JTable();
		scrollPane.setViewportView(table);
			
		// Model for Table
		DefaultTableModel model = (DefaultTableModel)table.getModel();
		model.addColumn("CustomerID");
		model.addColumn("Name");
		model.addColumn("Email");
		model.addColumn("CountryCode");
		model.addColumn("Budget");
		model.addColumn("Used");
		
		Connection connect = null;
		Statement s = null;
		
		try {
			Class.forName("com.mysql.jdbc.Driver");

			connect =  DriverManager.getConnection("jdbc:mysql://localhost/mydatabase" +
					"?user=root&password=root");
			
			s = connect.createStatement();
			
			String sql = "SELECT * FROM  customer ORDER BY CustomerID ASC";
			
			ResultSet rec = s.executeQuery(sql);
			int row = 0;
			while((rec!=null) && (rec.next()))
            {			
				model.addRow(new Object[0]);
				model.setValueAt(rec.getString("CustomerID"), row, 0);
				model.setValueAt(rec.getString("Name"), row, 1);
				model.setValueAt(rec.getString("Email"), row, 2);
				model.setValueAt(rec.getString("CountryCode"), row, 3);
				model.setValueAt(rec.getFloat("Budget"), row, 4);
				model.setValueAt(rec.getFloat("Used"), row, 5);
				row++;
            }

			rec.close();
             
		} catch (Exception e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(null, e.getMessage());
			e.printStackTrace();
		}
		
		try {
			if(s != null) {
				s.close();
				connect.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// Button  OK
		JButton btnOk = new JButton("OK");
		btnOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int index = table.getSelectedRow();
				sCustomerID = table.getValueAt(index, 0).toString();
				sName = table.getValueAt(index, 1).toString();
				sEmail = table.getValueAt(index, 2).toString();
				sCountryCode = table.getValueAt(index, 3).toString();
				sBudget = table.getValueAt(index, 4).toString();
				sUsed = table.getValueAt(index, 5).toString();
				dispose();
			}
		});
		btnOk.setBounds(176, 151, 83, 23);
		getContentPane().add(btnOk);
		
		// Button Cancel
		JButton btnCancel = new JButton("Cancel");
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});
		btnCancel.setBounds(292, 151, 89, 23);
		getContentPane().add(btnCancel);
		
	}

}

Output

Java GUI Choose Data  from JDialog to Main Frame

แสดง Frame หลัก ให้คลิกที่ปุ่ม Button เพื่อเปิด Dialog

Java GUI Choose Data  from JDialog to Main Frame

แสดง Dialog และเลือกรายการ

Java GUI Choose Data  from JDialog to Main Frame

รายการจะถูกส่งกลับมายัง Frame Main

อ่านเพิ่มเติม : พื้นฐาน Java GUI : Dialog และ Popup สร้าง Input Dialog และ Custom Modal Dialog









กรณีที่ใช้ร่วมกับ Database อื่น ๆ สามารถดูวิธีการใช้ Connector และ Connection String ได้ที่นี่


   
Share

Property & Method (Others Related)

Java GUI Example Windows and Form
How to use : Java GUI Menu/Menu Item (Icon Image Event Handler)
How to use : Java GUI Create Menu and Shortcut Key Control
How to use : Java GUI Create Menu and Open Another Panel Layout
How to use : Java GUI Member Register Form and Validation Data
How to use : Java GUI Login Username and Password via JDialog
How to use : Java GUI Authorized Menu Admin/User (Menu Level)
How to use : Java GUI Create Tab and Multiple Tab Item
How to use : Java GUI Create Frame Form for Send Mail / Attachment
How to use : Java GUI Upload file to Database via JFileChooser
How to use : Java GUI SwingWorker and JProgressBar
How to use : Java GUI SwingWorker and BackgroundWorker
How to use : Java GUI Import CSV/Text to Database
How to use : Java GUI Download file and Progress Bar
How to use : Java GUI JTable - Check Box (JCheckBox) in JTable Cell
How to use : Java GUI JTable - Row/Column / Hight / Font / Center
How to use : Java GUI JTable - ComboBox (JComboBox) in JTable Cell
How to use : Java GUI JTable - Disabled Cell Edit
How to use : Java GUI JTable - Header Sort Data
How to use : Java GUI JTable - Filter Data in JTable
How to use : Java GUI JTable - Alternate Rows/Background Color
How to use : Java GUI JTable - Update data from all Cell in JTable
How to use : Java GUI JTable - Update Data When Cell Change Value
How to use : Java GUI JTable - Add Rows Data to JTable Model
How to use : Java GUI ComboBox (JComboBox) from Database
How to use : Java GUI List (JList) from Database
How to use : Java GUI Spinner (JSpinner) from Database
How to use : Java GUI Pass Variable / Class Between Frame
How to use : Java GUI Example Database Class (Easy use)

ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท


ลองใช้ค้นหาข้อมูล


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2013-09-10 10:06:26 / 2017-03-27 21:55:41
  Download : No files
 Sponsored Links / Related

 
Java GUI Example Windows and Form
Rating :


ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 02
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่