Rabu, 21 Desember 2011

PBO2 Coding

PBO String



public class stringConstructors {

    public static void main(String args[]) {
        char charArray[] = {'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y'};
        String s = new String("hello");
        String s1 = new String();
        String s2 = new String(s);
        String s3 = new String(charArray);
        String s4 = new String(charArray, 6, 3);
        System.out.println("s1 = " + s1);
        System.out.println("s2 = " + s2);
        System.out.println("s3 = " + s3);
        System.out.println("s4 = " + s4);
        if (s.equals("hello")) {
            System.out.println("s is equals as \"hello\"");
        } else {
            System.out.println("s is not equals as \"hello\"");
        }
        if (s.equalsIgnoreCase("HELLO")) {
            System.out.println("s is equals as \"hello\"");
        } else {
            System.out.println("s is not equals as \"hello\"");
        }
        if (s3.contains("day")) {
            System.out.println("s3 contains \"day\"");
        } else {
            System.out.println("s3 do not contains \"day\"");
        }
        String s5 = s.concat(" " + s3);
        System.out.println(s5);
        String s6 = s5.replaceAll("hello", "happy");
        System.out.println(s6);
        String[] s7 = new String[3];
        s7 = s6.split(" ");

for
         (int i = 0; i < s7.length; i++) {
            System.out.println(s7[i]);
        }
        StringTokenizer tokens = new StringTokenizer(s6);
        System.out.println("Number of Token =" + tokens.countTokens());
        while (tokens.hasMoreTokens()) {
            System.out.println(tokens.nextToken());
        }
    }
}
___________________________________________________________________________
package Pertemuan11;


public class RagexSubstitution {

    public static void main(String args[]) {
        String firstString = "Every day is sunday";
        String secondString = "Vini pergi ke pasar 3 jam lalu, bersama 4 temannya";
        System.out.printf("Original String 1: %s\n", firstString);
        firstString = firstString.replaceAll("\\bday\\b", "week there"); // jelaskan
        System.out.printf(
                "Original string 1 become : %s\n", firstString);
        System.out.printf("Original String 2: %s\n", secondString);
        secondString = secondString.replaceAll("[a]", "o");//jelaskan
        System.out.printf(
                "Original string 2 become : %s\n", secondString);
        System.out.printf("Every word replaced by \"word\": %s\n\n",
                firstString.replaceAll("\\w+", "word")); // jelaskan
        secondString = secondString.replaceFirst("\\d", "digit");// jelaskan     
        System.out.printf("Ibu %s\n", secondString); //isilah ?? dengan kalimat yang sesuai
        String output = "String split at commas: [";
        String[] results = secondString.split(",\\s*"); // jelaskan
        for (String string : results) // jelaskan sintaks ini
        {
            output += "\"" + string + "\", ";
        }
        System.out.println("Hasil split : " + output);
        output = output.substring(0, output.length() - 2) + "]";
        System.out.println(output);
    } // end main
} // end class RegexSubstitution



PBO Stream



class JavaFilter extends FileFilter {
    private static final String JAVA  = "java";
    private static final char   DOT   = '.';
    public boolean accept(File f) {
        if (f.isDirectory()) {
            return true;
        }
        if (extension(f).equalsIgnoreCase(JAVA)) {
            return true;
        } else {
            return false;
        }
    }
    public String getDescription( ) {
        return "Java source files (.java)";
    }
    private String extension(File f) {
        String filename = f.getName();
        int    loc      = filename.lastIndexOf(DOT);
        if (loc > 0 && loc < filename.length() - 1) {
            return filename.substring(loc+1);
        } else {
            return "";
        }
    }
}
class FileManager  {
    private static final String EMPTY_STRING = "";
    private static String fileSeparator  = System.getProperty("file.separator");
    private static String lineTerminator = System.getProperty("line.separator");
   
    public FileManager( ) {}
    public String openFile( ) throws FileNotFoundException,
                                 IOException {
        String filename, doc = EMPTY_STRING;
        JFileChooser chooser = new JFileChooser();
        int reply = chooser.showOpenDialog(null);
        if(reply == JFileChooser.APPROVE_OPTION) {
              doc = openFile(chooser.getSelectedFile().getAbsolutePath());
        }
        return doc;
    }
    public String openFile(String filename)
                throws FileNotFoundException, IOException {
        String         line;
        StringBuffer   document = new StringBuffer(EMPTY_STRING);
        File           inFile     = new File(filename);
        FileReader     fileReader = new FileReader(inFile);
        BufferedReader bufReader  = new BufferedReader(fileReader);
        while (true) {
            line = bufReader.readLine();
            if (line == null) break;
            document.append(line + lineTerminator);
        }
        return document.toString();
    }
    public void saveFile(String data) throws IOException {
        String filename, doc = EMPTY_STRING;
        JFileChooser chooser = new JFileChooser();
        int reply = chooser.showSaveDialog(null);
        if(reply == JFileChooser.APPROVE_OPTION) {
            saveFile(chooser.getSelectedFile().getAbsolutePath(),data);
        }
    }
    public void saveFile(String filename, String data)
                throws IOException {
        File              outFile       = new File(filename);
        FileOutputStream  outFileStream = new FileOutputStream(outFile);
        PrintWriter       outStream     = new PrintWriter(outFileStream);
        outStream.print(data);
        outStream.close();
    }
}
class Ch12JavaViewer {
                private String document;
    public static void main(String[] args) {
        Ch12JavaViewer viewer = new Ch12JavaViewer();
        viewer.start( );
    }
    public Ch12JavaViewer() {}
                public void start( ) {
                                if (openFile()) {
                                                JOptionPane.showMessageDialog(null, document);
                                }
    }
    private boolean openFile( ) {
        JFileChooser chooser;
        int          status;
        chooser = new JFileChooser( );
        chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
        chooser.setFileFilter(new JavaFilter());
        status = chooser.showOpenDialog(null);
        if (status == JFileChooser.APPROVE_OPTION) {
            document =  readSource(chooser.getSelectedFile());
            return true;
        } else {
            JOptionPane.showMessageDialog(null, "Open File dialog canceled");
            return false;
        }
    }
    private String readSource(File file) {
                                String doc = "";
        try {
            FileManager fm = new FileManager();
            doc = fm.openFile(file.getAbsolutePath());
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "Error in opening a file: \n"
                                            + e.getMessage());
        }
                                return doc;
    }
}

PBO Graphic

public class Drawing extends JPanel {

    public Drawing() { // Constructor
        setBackground(Color.cyan);// untuk menset warna background
    }

    @Override
    public void paintComponent(Graphics g) {// method paintComponent dengan parameter Graphics g
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;// membuat objek baru dari kelas Graphics2D
        g.setColor(Color.pink);// memberi warna
        g.fillArc(10, 10, 50, 50, 30, 180);// membuat 1/2 lingkaran
        g.setColor(Color.black);// memberi warna
        g.drawString("Ini adalah arc", 10, 20);// membuat tulisan
        g2.setColor(Color.blue);// memberi warna
        g2.setStroke(new BasicStroke(20));// menembalkan garis
        g2.drawOval(100, 10, 40, 80);// membuat lingkaran utuh
        g.setColor(Color.yellow);// memberi warna
        BufferedImage b = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB); 
        // membuat objek baru dari kelas BufferedImage
        g2.setPaint(new TexturePaint(b, new Rectangle(10,10))); // menset paint pada objek b dan membuat kotak
        Graphics2D d = b.createGraphics();// membuat graphics d
        d.setColor(Color.red);// memberi warna merah
        d.fillRect(0, 0, 4, 4);// membuat kotak
        d.setColor(Color.magenta);//memberi warna magenta
        d.fillOval(0, 0, 10, 10);// membuat lingkaran

        int a[] = {230,270,310}; //mengatur tata letak, panjang dan lebar
        int c[] = {40,160,40};//mengatur tata letak, panjang dan lebar

        g.fillPolygon(a,c,3); // mencetak gambar
    }

    public static void main(String args[]) {
        JFrame frame = new JFrame("Drawing Arcs"); // membuat frame
        frame.addWindowListener(new WindowAdapter() { // membuat window listener

            @Override
             public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        frame.setLayout(new BorderLayout());
        Drawing draw = new Drawing();
        frame.add(draw, BorderLayout.CENTER);
        frame.setSize(450, 250);
        frame.setVisible(true);
    }
}
_______________________________________________________________________________

public class ShapePanel extends JPanel {

    public ShapePanel() {
        setBackground(Color.white);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.BLUE);
        g.drawLine(0, 10, 50, 60);
        g.setColor(Color.red);
        g.drawRect(50, 10, 50, 50);
        g.setColor(new Color(255, 0, 0));
        g.fillOval(100, 10, 50, 50);
        g.setColor(new Color(0, 255, 0));
        g.fillArc(150, 10, 50, 50, 0, 180);
        Graphics2D g2 = (Graphics2D) g;
// fill RoundRectangle2D.Double
        GradientPaint redtowhite = new GradientPaint(200, 10, Color.red, 250, 10, Color.black);
        g2.setPaint(redtowhite);
        g2.fill(new RoundRectangle2D.Double(200, 10, 50, 50, 10, 10));
//g2.setPaint();
        g2.drawString("Filled RoundRectangle2D", 200, 80);
    }

    public static void main(String args[]) {
        JFrame frame = new JFrame("Grafik 2 Dimensi");
        frame.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        frame.setLayout(new BorderLayout());
        ShapePanel shapePanel = new ShapePanel();
        frame.add(shapePanel, BorderLayout.CENTER);
        frame.setSize(450, 250);
        frame.setVisible(true);
    }
}

PBO Thread

public class Bintang extends JPanel {

    private static GeneralPath gp;
    int jum = 1;

    // draw general paths
    public void paintComponent(Graphics g) {
        super.paintComponent(g); // call superclass's paintComponent
      Random random = new Random(); // get random number generator
        Graphics2D g2d = (Graphics2D) g;


        g2d.translate(200, 200); // translate the origin to (200, 200)

        if (jum == 18) {
            jum = 0;
        }
        // rotate around origin and draw stars in random colors
        for (int count = 1; count <= jum; count++) {
            g2d.rotate(Math.PI / 8.0); // rotate coordinate system

//          set random drawing color
            g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));

            g2d.fill(starImage()); // draw filled star
        } // end for
        jum++;
    } // end method paintComponent

    public GeneralPath starImage() {
//        int xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };
//      int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };
        int xPoints[] = {5, 40, 90, 55};
        int yPoints[] = {50, 40, 90, 55};

        GeneralPath star = new GeneralPath(); // create GeneralPath object

        // set the initial coordinate of the General Path
        star.moveTo(xPoints[ 0], yPoints[ 0]);

        // create the star--this does not draw the star
        for (int count = 1; count < xPoints.length; count++) {
            star.lineTo(yPoints[ count], yPoints[ count]);
        }

        star.closePath(); // close the shape
        return star;
    }
}
**************

public class ThreadBintang extends Thread
{
   // execute application
   private static Bintang shapes2JPanel;
   public static void main( String args[] )
   {
      // create frame for Shapes2JPanel
      JFrame frame = new JFrame( "Drawing 2D Shapes" );
      frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

      shapes2JPanel = new Bintang();
      frame.add( shapes2JPanel ); // add shapes2JPanel to frame
//      frame.setBackground( Color.WHITE ); // set frame background color
      frame.setSize( 400, 400 ); // set frame size
      frame.setVisible( true ); // display frame
      ThreadBintang sh=new ThreadBintang();
      sh.start();
   } // end main


    public void run(){
        while (true){
            try{
                this.sleep(200);
            }
            catch(InterruptedException ie){break;}
            shapes2JPanel.repaint();
        }
    }
}
___________________________________________________________________________________

public class DasarAnimasi extends JFrame implements Runnable {

    Thread th;
// Objek yang akan ditampilkan menggunakan Array
    String frames[] = {"A", "AN", "ANT", "ANTO", "ANTON", "ANTONI", "ANTONIU", "ANTONIUS", "ANTONIUS ", "ANTONIUS R", "ANTONIUS RI"
        + "", "ANTONIUS RIA", "ANTONIUS RIAN", "ANTONIUS RIAND", "ANTONIUS RIANDI", "ANTONIUS RIANDIT", "ANTONIUS RIANDITY", "ANTONIUS RIANDITYA"};
// Menentukan variabel yang diperlukan
    int numFrames = frames.length;
    int currentFrame = 0;
    long lastDisplay = 0;

    public DasarAnimasi() {
        super("Animasi Sederhana");
        setSize(300, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
        setResizable(false);
        setLocation(300, 150);
        th = new Thread(this);
        th.start();
    }

    public void paint(Graphics g) {
        g.clearRect(0, 0, 300, 300);
        g.drawString("Dasar Animasi Java", 10, 45);
        g.drawString("By : ...", 10, 60);
        g.setColor(Color.blue);
        g.drawString(frames[currentFrame], 50, 100);//animasi tulisan berjalan
    }

    public void run() {
        do {
            long time = System.currentTimeMillis();
            if (time - lastDisplay > 100) {
                repaint();
                try {
                    Thread.sleep(200); //berhenti selama frameDelay=200
                } catch (InterruptedException ex) {
                }
                ++currentFrame;
                currentFrame %= numFrames;
                lastDisplay = time;
            }
        } while (true);
    }
}
*******
public class Main {
    public static void main(String args[]) {
DasarAnimasi app = new DasarAnimasi();
}
_______________________________________________________________________________

public class TimerThread extends JFrame implements Runnable {

    Thread th;
    boolean running;
    int i;
    long detik;
    int menit;
    int jam;
    Image start;

    public TimerThread() {
        running = true;
        th = new Thread(this);
        setTitle("Timer Thread");
        setSize(200, 100);
        int w = Toolkit.getDefaultToolkit().getScreenSize().width;
        int h = Toolkit.getDefaultToolkit().getScreenSize().height;
        setLocation(w / 2 - this.getWidth() / 2, h / 2 - this.getHeight() / 2);
        setVisible(true);
        th.start();
    }

    public void paint(Graphics g) {
        g.clearRect(0, 0, 500, 500);
        g.setColor(Color.blue);
        Font f = new Font("Times new Roman", 1, 20);
        g.setFont(f);
        g.drawString("Time : " + jam + ":" + menit + ":" + detik, 20, 70);
    }

    public void run() {
        while (running) {
            try {
                Thread.sleep(20);
            } catch (Exception e) {
            }
            if (i == 60) {
                detik = detik + 1;
                i = 1;
            }
            if (detik == 60) {
                menit = menit + 1;
                detik = 1;
            }
            if (menit == 60) {
                jam = jam + 1;
                menit = 1;
            }
            i++;
            repaint();
        }
    }
}
***************
 public static void main(String[] args) {
        TimerThread asd = new TimerThread();
    }


______________________________________________________________



public class Segitiga extends JPanel {

    private static GeneralPath gp;
    int jum=1;

   // draw general paths
   public void paintComponent( Graphics g )
   {
      super.paintComponent( g ); 
      Random random = new Random(); 
      Graphics2D g2d = ( Graphics2D ) g;

      g.setColor( Color.BLUE );

      g.translate( 200, 200 );          

      if (jum==14)
          jum=0;

      for ( int count = 1; count <= jum; count++ )
      {
         g.fillRect( 5, 0, 54, 54 );
         g2d.rotate( Math.E/ 2.75 );

         g.setColor( new Color( random.nextInt( 256 ),
         random.nextInt( 256 ), random.nextInt( 256 ) ) );

//         g2d.fill( SegitigaImage() ); // draw filled star
      } 
      jum++;
   } 
******************

public class Main extends Thread {

   private static Segitiga shapes2JPanel;
   public static void main( String args[] )
   {

      JFrame frame = new JFrame( "Drawing 2D Shapes" );
      frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

      shapes2JPanel = new Segitiga();
      frame.add( shapes2JPanel ); 

      frame.setSize( 400, 400 ); 
      frame.setVisible( true ); 
      Main sh=new Main();
      sh.start();
   }


    public void run(){
        while (true){
            try{
                this.sleep(500);
            }
            catch(InterruptedException ie){break;}
            shapes2JPanel.repaint();
        }
    }

}

PBO Exception



public class Pegawai extends Exception {
    private String NIP ;
    private String name ;
    private String golongan ;
    
    public String getNIP() {
        return NIP;
    }
    public void setNIP(String NIP) {
        this.NIP = NIP;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGolongan() {
        return golongan;
    }
    public void setGolongan(String golongan) throws Exception {
        if(golongan.equals("Ia") || golongan.equals("Ib") || golongan.equals("Ic") || golongan.equals("Id")
                || golongan.equals("IIa") || golongan.equals("IIb") || golongan.equals("IIc")
                || golongan.equals("IId") || golongan.equals("IIIa") || golongan.equals("IIIb")
                || golongan.equals("IIIc") || golongan.equals("IIId"))
        this.golongan = golongan;
        else {
            throw new Exception("Golongan Yang Anda Masukkan Tidak Tersedia");
        }
    }
}


**************************

public class TestPegawai_java {
    public static void main(String[]args){
        Pegawai pgw = new Pegawai();
        try{
            String NIP=JOptionPane.showInputDialog(null, "Masukkan NIP Anda");
            pgw.setNIP(NIP);
            String name=JOptionPane.showInputDialog(null, "Masukkan Nama Anda");
            pgw.setName(name);
            String golongan=JOptionPane.showInputDialog(null, "Masukkan Golongan Anda");
            pgw.setGolongan(golongan);


            JOptionPane.showMessageDialog(null, "NIP=" + pgw.getNIP() + "\n"
                    + "Nama=" + pgw.getName() + "\n" + "Golongan=" + pgw.getGolongan());


        }
        catch(NumberFormatException a){
            JOptionPane.showMessageDialog(null,"");
        }
        catch(Exception a){
            JOptionPane.showMessageDialog(null, a.getMessage());
        }
    }
}





Tidak ada komentar:

Posting Komentar