Posted by userl on July 02, 2017
Langsung aja ini contoh game sederhananya :
package Tank;
import java.awt.*;
import java.applet.Applet;
import java.applet.AudioClip;
public class BattleTank extends Applet implements Runnable
{
final double bulletspeed = 4;
final double tankspeed = 1;
final double pi=(double)3.141592653589793238462643383279502884197;
final int screendelay = 350;
final int rotsteps = 80;
final int bulletlife=70;
final int polycoords = 16; // should match the number of array entries below
final double tankpoly_x[] = { -10, -6, -6, -2, -2, 2, 2, 6, 6, 10, 10, 6, 6, -6, -6, -10 };
final double tankpoly_y[] = { -8, -8, -4, -4, -10, -10, -4, -4, -8, -8, 8, 8, 4, 4, 8, 8 };
final double collisionrange = 7;
final double blockers[] = { 0,24, 400, 30, // Upper wall
0,24, 6, 336,
394,24, 400,336,
0,330, 400,336,
100,177, 300,183,
100,150, 106,210,
294,150, 300,210,
150,70, 250, 76,
150,284, 250,290,
-1,-1,-1,-1 };
Dimension d;
Font largefont = new Font("Helvetica", Font.BOLD, 24);
Font smallfont = new Font("Helvetica", Font.BOLD, 14);
FontMetrics fmsmall, fmlarge;
Graphics goff;
Image ii;
Thread thethread;
boolean ingame=false;
Color tank1color = new Color(255,192,128);
Color tank2color = new Color(192,255,128);
Color backgnd = new Color(16,24,64);
double tank1x, tank1y, tank2x, tank2y;
double bullet1x, bullet1y, bullet2x, bullet2y;
double bullet1dx, bullet1dy, bullet2dx, bullet2dy;
boolean steerablebullets=true;
double tank1angle, tank2angle, bullet1angle, bullet2angle;
double tank1dangle, tank2dangle;
boolean bullet1fired, bullet2fired;
double tank1drive, tank2drive;
boolean showtitle;
boolean tank1dying, tank2dying;
int player1score, player2score;
int bullet1count,bullet2count;
int count = screendelay;
int[] xcoord;
int[] ycoord;
int dyingcount;
AudioClip shot;
AudioClip explosion;
public String getAppletInfo()
{
return("Battle Tank - by Dhean and Kevin");
}
public void init()
{
Graphics g;
int i;
d = size();
g=getGraphics();
g.setFont(smallfont);
fmsmall = g.getFontMetrics();
g.setFont(largefont);
fmlarge = g.getFontMetrics();
xcoord = new int[polycoords];
ycoord = new int[polycoords];
shot = getAudioClip(getDocumentBase(),"shot.wav");
explosion = getAudioClip(getDocumentBase(),"explosion.wav");
GameInit();
}
public void GameInit()
{
tank1x=50;
tank2x=350;
tank1y=180;
tank2y=180;
tank1angle=0;
tank2angle=pi;
bullet1fired = false;
bullet2fired = false;
tank1drive = 0;
tank2drive = 0;
showtitle = true;
tank1dying=false;
tank2dying=false;
dyingcount=30;
}
public boolean keyDown(Event e, int key)
{
if (ingame)
{
if (key=='d' || key=='D')
tank1dangle=-pi/(rotsteps/2);
if (key=='a' || key=='A')
tank1dangle=+pi/(rotsteps/2);
if (key=='w' || key=='W')
tank1drive=1.0;
if (key=='s' || key=='S')
tank1drive=-1.0;
if ((key=='f' || key=='F') && !bullet1fired)
{
bullet1fired=true;
bullet1x=tank1x;
bullet1y=tank1y;
bullet1dx=bulletspeed*Math.cos(tank1angle);
bullet1dy=-bulletspeed*Math.sin(tank1angle);
bullet1count=bulletlife;
shot.play();
}
if (key=='6' || key==Event.RIGHT)
tank2dangle=-pi/(rotsteps/2);
if (key=='4' || key==Event.LEFT)
tank2dangle=+pi/(rotsteps/2);
if (key=='8' || key==Event.UP)
tank2drive=1.0;
if (key=='2' || key==Event.DOWN)
tank2drive=-1.0;
if ((key=='/' || key=='?') && !bullet2fired)
{
bullet2fired=true;
bullet2x=tank2x;
bullet2y=tank2y;
bullet2dx=bulletspeed*Math.cos(tank2angle);
bullet2dy=-bulletspeed*Math.sin(tank2angle);
bullet2count=bulletlife;
shot.play();
}
}
return true;
}
public boolean keyUp(Event e, int key)
{
if (key=='d' || key=='D' || key=='a' || key=='A')
tank1dangle=0;
if (key=='4' || key=='6' || key==Event.LEFT || key==Event.RIGHT)
tank2dangle=0;
if (key=='w' || key=='W' || key=='s' || key=='S')
tank1drive=0;
if (key=='8' || key==Event.UP || key=='2' || key==Event.DOWN)
tank2drive=0;
if (key==Event.ESCAPE)
{
ingame=false;
}
if (!ingame)
{
if (key=='1')
{
ingame=true;
steerablebullets=true;
player1score = 0;
player2score = 0;
}
if (key=='2')
{
ingame=true;
steerablebullets=false;
player1score = 0;
player2score = 0;
}
}
return true;
}
public void paint(Graphics g)
{
if (goff==null && d.width>0 && d.height>0)
{
ii = createImage(d.width, d.height);
goff = ii.getGraphics();
}
if (goff==null || ii==null)
return;
goff.setColor(backgnd);
goff.fillRect(0, 0, d.width, d.height);
if (ingame)
PlayGame();
else
ShowIntroScreen();
g.drawImage(ii, 0, 0, this);
}
public void DoBullets()
{
if (bullet1fired)
{
goff.setColor(tank1color);
goff.fillRect((int)bullet1x,(int)bullet1y,2,2);
if (bullet1x>(tank2x-collisionrange) && bullet1x<(tank2x+collisionrange) &&
bullet1y>(tank2y-collisionrange) && bullet1y<(tank2y+collisionrange))
{
tank2dying=true;
player1score++;
explosion.play();
}
if (steerablebullets)
{
bullet1dx=bulletspeed*Math.cos(tank1angle);
bullet1dy=-bulletspeed*Math.sin(tank1angle);
}
bullet1x+=bullet1dx;
bullet1y+=bullet1dy;
bullet1count--;
if (bullet1count<=0 || CheckBullet(bullet1x, bullet1y))
{
bullet1fired=false;
}
}
if (bullet2fired)
{
goff.setColor(tank2color);
goff.fillRect((int)bullet2x,(int)bullet2y,2,2);
if (bullet2x>(tank1x-collisionrange) && bullet2x<(tank1x+collisionrange) &&
bullet2y>(tank1y-collisionrange) && bullet2y<(tank1y+collisionrange))
{
tank1dying=true;
player2score++;
explosion.play();
}
if (steerablebullets)
{
bullet2dx=bulletspeed*Math.cos(tank2angle);
bullet2dy=-bulletspeed*Math.sin(tank2angle);
}
bullet2x+=bullet2dx;
bullet2y+=bullet2dy;
bullet2count--;
if (bullet2count<=0 || CheckBullet(bullet2x, bullet2y))
{
bullet2fired=false;
}
}
}
public boolean CheckBullet(double x, double y)
{
boolean rc=false;
int j=0;
while(blockers[j]>-0.5 && !rc)
{
if (x>=blockers[j] && x<blockers[j+2] &&
y>=blockers[j+1] && y<blockers[j+3])
{
rc=true;
}
j+=4;
}
return rc;
}
public void CalcTank(double x, double y, double angle)
{
int i;
for (i=0; i<polycoords; i++)
{
xcoord[i] = (int)(x+(tankpoly_x[i]*Math.sin(angle)-tankpoly_y[i]*Math.cos(angle)));
ycoord[i] = (int)(y+(tankpoly_x[i]*Math.cos(angle)+tankpoly_y[i]*Math.sin(angle)));
}
}
public void MoveTank(double[] coord)
{
double dx,dy;
double x=coord[0],y=coord[1];
double angle=coord[2]+coord[3];
int i,j;
boolean hitwall=false;
if (angle>(2*pi))
angle-=(2*pi);
if (angle<0)
angle+=(2*pi);
dx=tankspeed*Math.cos(angle);
dy=-tankspeed*Math.sin(angle);
if (coord[4]>0.5)
{
x+=dx;
y+=dy;
} else if (coord[4]<-0.5)
{
x-=dx;
y-=dy;
}
CalcTank(x,y,angle); // determine where the tank coordinates will be
for (i=0; i<polycoords; i++) // now we're going to check whether the tank drives into a wall
{
j=0;
while(blockers[j]>-0.5)
{
if (xcoord[i]>blockers[j] && xcoord[i]<blockers[j+2] &&
ycoord[i]>blockers[j+1] && ycoord[i]<blockers[j+3])
{
hitwall=true;
}
j+=4;
}
}
if (!hitwall)
{
coord[0]=x;
coord[1]=y;
coord[2]=angle;
}
}
public void DoTanks()
{
double distance;
double temp[] = {0.0, 0.0, 0.0, 0.0, 0.0}; // why that stupid java doesn't have a call by reference
// is beyond me.... I hate doing work arounds
distance=Math.sqrt((tank1x-tank2x)*(tank1x-tank2x)+(tank1y-tank2y)*(tank1y-tank2y));
if (distance<(collisionrange*2) && !tank1dying && !tank2dying) // did the two tanks collide
{
player1score++;
player2score++;
tank1dying=true;
tank2dying=true;
explosion.play();
}
goff.setColor(tank1color);
CalcTank(tank1x, tank1y, tank1angle); // Calc coords for tank #1
goff.fillPolygon(xcoord,ycoord,polycoords); // and draw it
goff.setColor(tank2color);
CalcTank(tank2x, tank2y, tank2angle); // Calc coords for tank #2
goff.fillPolygon(xcoord,ycoord,polycoords); // and draw it
if (tank1dying)
{
tank1angle+=pi/15;
}
else
{
temp[0] = tank1x;
temp[1] = tank1y;
temp[2] = tank1angle; // workaround for java not being able to do call by reference
temp[3] = tank1dangle;
temp[4] = tank1drive;
MoveTank(temp); // Move the thing
tank1x=temp[0]; // copy x and y coords back
tank1y=temp[1];
tank1angle=temp[2];
}
if (tank2dying)
{
tank2angle-=pi/15;
}
else
{
temp[0] = tank2x;
temp[1] = tank2y;
temp[2] = tank2angle;
temp[3] = tank2dangle;
temp[4] = tank2drive;
MoveTank(temp);
tank2x=temp[0];
tank2y=temp[1];
tank2angle=temp[2];
}
}
public void PlayGame()
{
DrawPlayField();
ShowScore();
DoTanks();
if (tank1dying || tank2dying)
{
dyingcount--;
if (dyingcount==0)
GameInit();
if (player1score==5 || player2score==5)
ingame=false;
}
else
{
Minggu, 02 Juli 2017
THREADING PADA PEMROGRAMAN JAVA
Posted by user on July 02, 2017
Thread adalah rangkaian eksekusi dari sebuah aplikasi java dan setiap program java minimal memiliki satu buah thread. Sebuah thread bisa berada di salah satu dari 4 status, yaitu new, runnable, blocked, dan dead.
Buat file bernama Threading.java
public class Threading implements Runnable {
private int n = 1;
public void run() {
while (true) {
System.out.println(n++);
try{
Thread.sleep(500);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
public static void main(String args[]) {
Thread t = new Thread(new Threading());
t.start();
while(true) {
System.out.println("I love you");
try{
Thread.sleep(600);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
jika ingin lebih jelas silahkan download disini
Thread adalah rangkaian eksekusi dari sebuah aplikasi java dan setiap program java minimal memiliki satu buah thread. Sebuah thread bisa berada di salah satu dari 4 status, yaitu new, runnable, blocked, dan dead.
Buat file bernama Threading.java
public class Threading implements Runnable {
private int n = 1;
public void run() {
while (true) {
System.out.println(n++);
try{
Thread.sleep(500);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
public static void main(String args[]) {
Thread t = new Thread(new Threading());
t.start();
while(true) {
System.out.println("I love you");
try{
Thread.sleep(600);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
jika ingin lebih jelas silahkan download disini
CONTOH MEMBUAT NOTEPAD PADA JAVA
Posted by user on July 02, 2017
Langsung saja ini contoh membuat notepad sederhana pada java :
Library
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Script
public class Notepad extends JFrame {
private JTextArea textArea;
public Notepad(){
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
setSize(600,600);
JPanel panel= (JPanel) this.getContentPane();
GridLayout gridLayout = new GridLayout(1,0);
panel.setLayout(gridLayout);
// JTextField field = new JTextField();// JTextArea textArea; // JTextArea textArea = new JTextArea(); textArea = new JTextArea();
// panel.add(field); panel.add(textArea);
this.setTitle("Notepad");
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("File"),
view = new JMenu("View");
JMenuItem open= new JMenuItem("Open..."),
save= new JMenuItem("Save"),
saveAs= new JMenuItem("SaveAs");
JMenu font = new JMenu("Font");
JMenuItem size14 = new JMenuItem("14");
JMenuItem size16 = new JMenuItem("16");
JMenuItem size18 = new JMenuItem("18");
this.setLocationRelativeTo(null);
size14.setActionCommand("14");
size16.setActionCommand("16");
size18.setActionCommand("18");
//TODO Tambahkan menu baru juga untuk custom size JMenuItem customSize = new JMenuItem("Custom Size....");
customSize.setActionCommand("-");
ActionListener sizeListener = new ActionListener() {
@Override public void actionPerformed(ActionEvent actionEvent){
Integer size;
if(actionEvent.getActionCommand().equals("-")){
size = (Integer) JOptionPane.showInputDialog(Notepad.this, "Ukuran font : ", "Custom Size",
JOptionPane.INFORMATION_MESSAGE, null, new Integer[]{14,16,18,20,24,36,48}, "ukuran");
if(size == null)
return;
}else size = Integer.valueOf(actionEvent.getActionCommand());
Notepad.this.changeTextSize(size);
}
};
size14.addActionListener(sizeListener);
size16.addActionListener(sizeListener);
size18.addActionListener(sizeListener);
customSize.addActionListener(sizeListener);
file.add(open);
file.add(save);
file.add(saveAs);
JMenuItem test = new JMenuItem("Test");
test.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(Notepad.this, "cinta", "Hai sayang!", JOptionPane.WARNING_MESSAGE);
String jawaban = JOptionPane.showInputDialog(Notepad.this,"Apa jawaban anda!","Hai Sayang",
JOptionPane.WARNING_MESSAGE);
System.out.println(jawaban);
}
});
view.add(font);
view.add(test);
font.add(size14);
font.add(size16);
font.add(size18);
font.add(customSize);
menuBar.add(file);
menuBar.add(view);
this.setJMenuBar(menuBar);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
// this.setMinimumSize(this.getPreferredSize());
this.setVisible(true);
}
private void changeTextSize(Integer size) {
System.out.println(size);
Font originalFont = textArea.getFont();
Font newFont = new Font(originalFont.getFontName(), originalFont.getStyle(),size);
//Set font ke textarea textArea.setFont(newFont);
}
public static void main(String[] args){
Notepad notepad=new Notepad();
}
}
ingin file lengkap download disini
Langsung saja ini contoh membuat notepad sederhana pada java :
Library
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Script
public class Notepad extends JFrame {
private JTextArea textArea;
public Notepad(){
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
setSize(600,600);
JPanel panel= (JPanel) this.getContentPane();
GridLayout gridLayout = new GridLayout(1,0);
panel.setLayout(gridLayout);
// JTextField field = new JTextField();// JTextArea textArea; // JTextArea textArea = new JTextArea(); textArea = new JTextArea();
// panel.add(field); panel.add(textArea);
this.setTitle("Notepad");
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("File"),
view = new JMenu("View");
JMenuItem open= new JMenuItem("Open..."),
save= new JMenuItem("Save"),
saveAs= new JMenuItem("SaveAs");
JMenu font = new JMenu("Font");
JMenuItem size14 = new JMenuItem("14");
JMenuItem size16 = new JMenuItem("16");
JMenuItem size18 = new JMenuItem("18");
this.setLocationRelativeTo(null);
size14.setActionCommand("14");
size16.setActionCommand("16");
size18.setActionCommand("18");
//TODO Tambahkan menu baru juga untuk custom size JMenuItem customSize = new JMenuItem("Custom Size....");
customSize.setActionCommand("-");
ActionListener sizeListener = new ActionListener() {
@Override public void actionPerformed(ActionEvent actionEvent){
Integer size;
if(actionEvent.getActionCommand().equals("-")){
size = (Integer) JOptionPane.showInputDialog(Notepad.this, "Ukuran font : ", "Custom Size",
JOptionPane.INFORMATION_MESSAGE, null, new Integer[]{14,16,18,20,24,36,48}, "ukuran");
if(size == null)
return;
}else size = Integer.valueOf(actionEvent.getActionCommand());
Notepad.this.changeTextSize(size);
}
};
size14.addActionListener(sizeListener);
size16.addActionListener(sizeListener);
size18.addActionListener(sizeListener);
customSize.addActionListener(sizeListener);
file.add(open);
file.add(save);
file.add(saveAs);
JMenuItem test = new JMenuItem("Test");
test.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(Notepad.this, "cinta", "Hai sayang!", JOptionPane.WARNING_MESSAGE);
String jawaban = JOptionPane.showInputDialog(Notepad.this,"Apa jawaban anda!","Hai Sayang",
JOptionPane.WARNING_MESSAGE);
System.out.println(jawaban);
}
});
view.add(font);
view.add(test);
font.add(size14);
font.add(size16);
font.add(size18);
font.add(customSize);
menuBar.add(file);
menuBar.add(view);
this.setJMenuBar(menuBar);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
// this.setMinimumSize(this.getPreferredSize());
this.setVisible(true);
}
private void changeTextSize(Integer size) {
System.out.println(size);
Font originalFont = textArea.getFont();
Font newFont = new Font(originalFont.getFontName(), originalFont.getStyle(),size);
//Set font ke textarea textArea.setFont(newFont);
}
public static void main(String[] args){
Notepad notepad=new Notepad();
}
}
ingin file lengkap download disini
Sabtu, 01 Juli 2017
DATABASE CONNECTOR PADA PEMROGRAMAN JAVA
Kali ini kita akan mencoba membaca data di dalam database melalui aplikasi yang dibuat dari bahasa pemrograman java. Database yang akan kita gunakan adalah MySQL. Pada postingan sebelumnya saya sudah menjelaskan tentang bagaimana membuat database sederhana dengan MySQL. Sekarang tinggal kita hubungkan koneksinya pada program java nantinya.
Sebelum kita menghubungkan database dengan program java, kita membutuhkan sebuah library java yang nantinya berguna sebagai “perantara” antara database MySQL dengan program java kita. Library yang akan kita gunakan adalah MySQL connector java yang anda bisa download disini, untuk aplikasi ini saya menggunakan mysql-connector-java-5.1.7.
Setelah library di add dalam ide baru kita bisa memanggil ataupun menggunakan db tersebut.
Di dalam lab kami diberi penjelasan seperti diatas dan codenya diberi oleh aslab kami seperti dbawah ini :
Database.java
package Pertemuan6.Complex;
import java.sql.*;
public class Database {
private static final String dbName = "fedosdb", dbUsername = "root", dbPass = "";
public Statement makeStatement() throws SQLException {
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/" + dbName,
dbUsername,
dbPass
);
return connection.createStatement();
}
}
Model.java
package Pertemuan6.Complex;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public abstract class Model {
protected abstract String tableName();
public <T> List<T> select(String where, Class<? extends Model> className) {
Database db = new Database();
List<T> list = new ArrayList<>();
try {
Statement statement = db.makeStatement();
String str = "SELECT * FROM " + tableName();
if (where != null)
str += " WHERE " + where;
ResultSet result = statement.executeQuery(str);
HashMap<Integer, Method> methods = new HashMap<Integer, Method>();
for (int i = 1; i <= result.getMetaData().getColumnCount(); i++) {
String columnName = result.getMetaData().getColumnName(i);
try {
switch (result.getMetaData().getColumnType(i)) {
case Types.INTEGER:
case Types.SMALLINT:
case Types.TINYINT:
case Types.BIGINT:
methods.put(i, className.getDeclaredMethod("set" + columnName, Integer.class));
case Types.VARCHAR:
case Types.CHAR:
methods.put(i, className.getDeclaredMethod("set" + columnName, String.class));
}
} catch (NoSuchMethodException e) {
System.err.println("No method named set" + columnName);
}
}
while (result.next()) {
try {
T o = (T) className.newInstance();
for (int i = 1; i <= result.getMetaData().getColumnCount(); i++) {
Method method = methods.get(i);
if (method != null) {
switch (result.getMetaData().getColumnType(i)) {
case Types.INTEGER:
case Types.SMALLINT:
case Types.TINYINT:
case Types.BIGINT:
method.invoke(o, result.getInt(i));
break;
case Types.VARCHAR:
case Types.CHAR:
method.invoke(o, result.getString(i));
break;
}
}
}
list.add(o);
} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
User.java
package Pertemuan6.Complex;
import java.util.List;
public class User extends Model {
private Integer id;
private String username;
@Override
protected String tableName() {
return "user";
}
public static void main(String[] args) {
User user = new User();
List<User> list = user.select(null, User.class);
System.out.println(list);
}
public Integer getid() {
return id;
}
public void setid(Integer id) {
this.id = id;
}
public String toString() {
if (username != null)
return username.toString();
return null;
}
public String getusername() {
return username;
}
public void setusername(String username) {
this.username = username;
}
}
sekian~
Sebelum kita menghubungkan database dengan program java, kita membutuhkan sebuah library java yang nantinya berguna sebagai “perantara” antara database MySQL dengan program java kita. Library yang akan kita gunakan adalah MySQL connector java yang anda bisa download disini, untuk aplikasi ini saya menggunakan mysql-connector-java-5.1.7.
Setelah library di add dalam ide baru kita bisa memanggil ataupun menggunakan db tersebut.
Di dalam lab kami diberi penjelasan seperti diatas dan codenya diberi oleh aslab kami seperti dbawah ini :
Database.java
package Pertemuan6.Complex;
import java.sql.*;
public class Database {
private static final String dbName = "fedosdb", dbUsername = "root", dbPass = "";
public Statement makeStatement() throws SQLException {
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/" + dbName,
dbUsername,
dbPass
);
return connection.createStatement();
}
}
Model.java
package Pertemuan6.Complex;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public abstract class Model {
protected abstract String tableName();
public <T> List<T> select(String where, Class<? extends Model> className) {
Database db = new Database();
List<T> list = new ArrayList<>();
try {
Statement statement = db.makeStatement();
String str = "SELECT * FROM " + tableName();
if (where != null)
str += " WHERE " + where;
ResultSet result = statement.executeQuery(str);
HashMap<Integer, Method> methods = new HashMap<Integer, Method>();
for (int i = 1; i <= result.getMetaData().getColumnCount(); i++) {
String columnName = result.getMetaData().getColumnName(i);
try {
switch (result.getMetaData().getColumnType(i)) {
case Types.INTEGER:
case Types.SMALLINT:
case Types.TINYINT:
case Types.BIGINT:
methods.put(i, className.getDeclaredMethod("set" + columnName, Integer.class));
case Types.VARCHAR:
case Types.CHAR:
methods.put(i, className.getDeclaredMethod("set" + columnName, String.class));
}
} catch (NoSuchMethodException e) {
System.err.println("No method named set" + columnName);
}
}
while (result.next()) {
try {
T o = (T) className.newInstance();
for (int i = 1; i <= result.getMetaData().getColumnCount(); i++) {
Method method = methods.get(i);
if (method != null) {
switch (result.getMetaData().getColumnType(i)) {
case Types.INTEGER:
case Types.SMALLINT:
case Types.TINYINT:
case Types.BIGINT:
method.invoke(o, result.getInt(i));
break;
case Types.VARCHAR:
case Types.CHAR:
method.invoke(o, result.getString(i));
break;
}
}
}
list.add(o);
} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
User.java
package Pertemuan6.Complex;
import java.util.List;
public class User extends Model {
private Integer id;
private String username;
@Override
protected String tableName() {
return "user";
}
public static void main(String[] args) {
User user = new User();
List<User> list = user.select(null, User.class);
System.out.println(list);
}
public Integer getid() {
return id;
}
public void setid(Integer id) {
this.id = id;
}
public String toString() {
if (username != null)
return username.toString();
return null;
}
public String getusername() {
return username;
}
public void setusername(String username) {
this.username = username;
}
}
sekian~
Langganan:
Postingan (Atom)