Site Sponsors:
Order Of Operations 
When we set our layout *after* we have added our components, we do not need to use any of the size-oriented (setSize(), setPreferredSize(), setMaximumSize(), setMinimumSize()) operations:


import java.awt.CardLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
* Use the content of a panel for the main form. Application ends when a main form
* is closed.
*
* @author profnagy
*/
public class MainFrame extends JFrame implements Runnable {

public Thread pwThread = null;

public MainFrame(JPanel jPanel) {
super();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
if (jPanel == null) {
JLabel lbl = new JLabel();
lbl.setText(this.getClass().getName());
this.add(lbl);
} else {
this.add(jPanel); // do this first -
}
this.setLayout(new CardLayout()); // the layout (queries all children), afterwards
this.pack();
com.soft9000.gui.Misc.ScreenCenter(this);
}

public void start() {
pwThread = new Thread(this);
pwThread.start();
this.setVisible(true);
}

public void run() {
}
}


So if you ever see that your window size does not work, check to see when we have applied our layout manager. In general, simply remember to assign the layout manager just before calling pack().

Enjoy,

-Rn

[ view entry ] ( 1864 views )   |  permalink
Analog Clock - Combining two examples 
Went looking for an analog clock today. Found a nice one, designed for a Java Applet.

Converted it to an application - it was blinky, so we mixed-in another example.

Tried to share the result with the author, but the comment / post was too big.

Because I think Manoj's concept of having an outer "gear" revolving around the clock is cool, I decided to post the blend here so as to share-it with the author... as well as anyone else:


import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.Calendar;
import javax.swing.JFrame;

public class Clock extends JFrame {
class MoveIt implements MouseMotionListener {

@Override
public void mouseMoved(MouseEvent me) {
}

@Override
public void mouseDragged(MouseEvent me) {
xmou = me.getX(); //changing the clock position on mouse drag
ymou = me.getY(); //changing the clock position on mouse drag
}
}

// The object we will use to write with instead of the standard screen graphics
Graphics bufferGraphics = null;
// The image that will contain everything that has been drawn on
// bufferGraphics.
Image offscreen = null;
// To get the width and height of the applet.
Dimension dim;
int xmou = 200; //set the center of circle
int ymou = 200; //set the center of circle
double theta = -0.1047; //theta for second's hand
int x = xmou; //x position of Second's hand
int y = ymou; //y position of second's hand
int p, b; //perpendicular and base of Second's hand
int h = 60; //hypotenous(heigth) of clock's hand
double the = -0.1047; //theta for creating outer circle
double thetamin = -0.1047; //theta for minutes hand
int xm = xmou; //x position of minute's hand
int ym = ymou; //y position of minute's hand
int pmin, bmin; //perpendicular and base of Minute's hand
double thetah = -0.1047; //theta for hour hand
int xh = xmou; //y position of hour's hand
int yh = ymou; //y position of hour's hand
int ph, bh; //perpendicular and base of hour's hand
double thetan = -0.0; //theta for numbers of clock
int xn = xmou; //x position of Clock numbers
int yn = ymou; //y position of Clock numbers
int pn, bn; //perpendicular and base of clock numbers
int num = 0; //for writing the numbers

public Clock(int x, int y) {
super();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Click and drag to move the clock");
dim = getSize();
dim.setSize(x, y);
setSize((int) dim.getWidth(), (int) dim.getWidth());
setBackground(Color.WHITE);
}

@Override
public void paint(Graphics g) {
if (offscreen == null) {
return;
}

bufferGraphics.clearRect(0, 0, dim.width, dim.width);
bufferGraphics.setColor(Color.red);
bufferGraphics.drawString("Bad Double-buffered", 10, 10);

doPaint(bufferGraphics);

if (g != null) {
g.drawImage(offscreen, 0, 0, this);
}
}

@Override
public void update(Graphics g) {
paint(g);
}

private void doPaint(Graphics g) {
//for writing numbers in clock and outer circle
for (int ss = 0; ss < 60; ss++) {

int xocir = xmou; //x position of outer circle
int yocir = ymou; //y position of outer circle
int pocir, bocir; //perpendicular and base of outer circle

pocir = (int) (Math.sin(the) * (h + 23));
bocir = (int) (Math.cos(the) * (h + 23));
xocir = xocir - pocir;
yocir = yocir - bocir;
the = the - 0.1047;

g.setColor(Color.BLUE);
g.drawLine(xocir + 5, yocir + 5, xocir, yocir);
g.setColor(Color.BLACK);
if (ss % 5 == 0) {
num++;
if (num > 12) {
num = 1;
}
xn = xmou;
yn = ymou;
if (thetan <= -6.28318531) {
thetan = 0.0;
}
thetan = thetan - 0.523598776;
pn = (int) (Math.sin(thetan) * (h + 10));
bn = (int) (Math.cos(thetan) * (h + 10));
xn = xn - pn;
yn = yn - bn;
g.drawString("" + num, xn - 3, yn + 5);
}

}
// Drawing Clock hands
g.setColor(Color.BLACK);
g.drawLine(xmou, ymou, xm, ym); //drawing minute's hand
g.drawLine(xmou, ymou, xh, yh); //drawing hour's hand

g.setColor(Color.RED);
g.drawLine(xmou, ymou, x, y); //drawing second's hand
}

public void newpoint() {
Calendar now = Calendar.getInstance(); //creating a Calendar variable for getting current time

// For the second hand:
x = xmou;
y = ymou;
theta = -0.1047;
theta = theta * now.get(Calendar.SECOND);
p = (int) (Math.sin(theta) * h);
b = (int) (Math.cos(theta) * h);
x = x - p;
y = y - b;
//theta=theta - 0.1047;

// For the minute hand:
xm = xmou;
ym = ymou;

thetamin = -0.1047;
thetamin = thetamin * now.get(Calendar.MINUTE);
pmin = (int) (Math.sin(thetamin) * (h - 6));
bmin = (int) (Math.cos(thetamin) * (h - 6));
xm = xm - pmin;
ym = ym - bmin;

// For the hour hand:
xh = xmou;
yh = ymou;
thetah = -0.1047;
thetah = thetah * now.get(Calendar.HOUR) * 5;

if (now.get(Calendar.MINUTE) >= 12 && now.get(Calendar.MINUTE) < 24) {
thetah = thetah - 0.1047;
} else if (now.get(Calendar.MINUTE) >= 24 && now.get(Calendar.MINUTE) < 36) {
thetah = thetah - (2 * 0.1047);
} else if (now.get(Calendar.MINUTE) >= 36 && now.get(Calendar.MINUTE) < 48) {
thetah = thetah - (3 * 0.1047);
} else if (now.get(Calendar.MINUTE) >= 48 && now.get(Calendar.MINUTE) < 60) {
thetah = thetah - (4 * 0.1047);
}

ph = (int) (Math.sin(thetah) * (h - 15));
bh = (int) (Math.cos(thetah) * (h - 15));
xh = xh - ph;
yh = yh - bh;
}

@Override
public void setVisible(boolean bVis) {
super.setVisible(bVis);
if (offscreen == null) {
offscreen = createImage(dim.width, dim.height);
if (offscreen != null) {
bufferGraphics = offscreen.getGraphics();
addMouseMotionListener(new MoveIt());
}
}
}

public static void main(String[] args) {
Clock analog = new Clock(500, 500);
analog.h = 60;
analog.setVisible(true);

while (true) {
analog.newpoint();
analog.repaint();
try {
Thread.sleep(6);
} catch (Exception e) {
}
}
}
}


Such is the joy of sharing examples: What would have taken most of us a day to think about, took about 10 minutes to glue together.

Enjoy,

-Rn


[ view entry ] ( 9883 views )   |  permalink  |  related link
Quick PHP Persistence  

Easy Enough?


One of the reasons why SQL databases are such a performance bottleneck in modern enterprise systems is that people store absolutely everything in them. Indeed, over the decades I encounter more and more blank stares when I respond to queries by telling friends that - even given the millions of search-able recipes, quotations, events, and graphics shared throughout my popular sites, that we have never felt the need to use SQL. -Binary searches, text indexing, and data storage routines are easy enough to write?

Requirement Triage


Indeed, it is due to the many fallacies one often discovers in the "one technology fits all" mantra that savvy technical folks refuse to do things like log HTML hits to an enterprise resource. -Without clear business justification, when it comes time to store billions of simple n-keyed records a day - into a bottleneck-sensitive database - perhaps folks are doing so because they do not realize that there is an easy alternative? (After all, to make any database work, someone had to write things like indexing and binary searches (and a whole lot more - wink - wink), at some point?)

When it comes to demonstrating customized, responsive solutions to domain-specific challenges, such was the case when I was recently showing off a performance-boosting notion designed to use PHP CRUD. When discussing how we can quickly & easily save data to an indexed file, the "I'm from Missouri" (i.e. 'show me') -urge came up with a succinct demonstration:


class user_info {

var $data = array();

function __construct() {
$this->data[0] = -1;
$this->data[1] = '';
$this->data[2] = '';
$this->data[3] = '';
$this->data[4] = false;

}

public function getPayload() {
return $this->data[4];
}

public function setPayload($str) {
$this->data[4] = $str;
}

public function getAlias() {
return $this->data[3];
}

public function setAlias($str) {
$this->data[3] = $str;
}

public function getPassword() {
return $this->data[2];
}

public function setPassword($str) {
$this->data[2] = $str;
}

public function getEmailt() {
return $this->data[1];
}

public function setEmail($email) {
$this->data[1] = $email;
}

public function getAccount() {
return $this->data[0];
}

public function setAccount($ss) {
$this->data[0] = $ss;
}

public function isNull() {
return ($this->data[0] === -1);
}

public function toString() {
$result = implode('|', $this->data);
return $result;
}

public function fromString($str) {
$this->data = explode('|', $str);
return true; // gigo
}

}


Simple String


The crux of the above example is a demonstration of how we can quickly read and write class information to a string. No XML. No JSON. Just a nice, efficient, cross platform representation of an easily extensible data format.

Exploding Arrays


By using arrays, encapsulation, and PHP's implode() and explode() feature, a classy lifestyle can get instances stored relatively quickly. -Best of all, when using an encapsulated array(), we are free to rapidly extend the number of fields / columns we keep without change requests, hours of meetings, or ever contacting your friendly neighborhood DBA ;-)

After storing data, comes the searching. While I consider my indexing technologies to be intellectual property, at the end of the day such things are easy enough to write for oneself.

Class Egocentricity


For what it is worth, working within the confines of typeless languages (such as PHP) can also bring a few conveniences to mind. Indeed, while an accomplished object-oriented designer might be interested in designing an instance out of a controller, for maintenance reasons some odd 'typeless-convenience' patterns may surface:


class user_info_crud extends user_info {
var $info;
var $db;

public function __construct() {
user_info::__construct();
$this->info = new IndexedDataInfo();
$this->info->data_min = 1024;
$df = home('front_end_data/user_info.crud');
$this->info->setFileNames($df);
$this->db = new IndexedData();
}

public function create() {
$res = $this->db->append($this->info, '');
if ($res === false)
return false;
$this->setAccount($res);
return $this->update();
}

public function read($ss) {
$str = $this->db->read($this->info, $ss);
if ($str === false)
return false;
return $this->fromString($str);
}

public function update() {
if ($this->isNull() == false) {
$str = $this->toString();
return $this->db->update($this->info, $this->getAccount(), $str);
}
return false;
}

public function delete() {
if ($this->isNull() == false)
return $this->db->update($this->info, $this->getAccount(), '');
return true;
}

public function tally() {
return $this->db->tally($this->info);
}

public function destroyDatabase() {
return $this->info->delete();
}
}


The above demonstrates how we might use PHP CRUD to maintain a list of user accounts. By using the logical, zero-based record-offset as the record identifier / account number, users have that identifier, as well as the email address (etc.) to manage their front-end web-access account. --In addition to leveraging file-level POSIX securities (usr/group, etc), the security conscious can even use PHP CRUD's base64 encoding as another line of defense.

Proper Packaging


But the real point is this: In as much as PHP is - for the moment - extremely typeless - rather than having your CRUD operations return - and manage - objects - it is often easier in PHP to use the above design pattern. While it always seems laughably obscene to derive a controller from an entity (such as we do above), doing so can often make OIOO (One-In One-Out - pronounced "ohio") operations far, far easier to deal with.

Indeed, in the final analysis, the ability to wrap a controller around an object is often what templates (also referred to as parametrized types) are all about.

Better still, if push comes to shove (as it often may), we can always retrieve or otherwise manage an array of user_info.

Enjoy,


-Rn



[ view entry ] ( 1889 views )   |  permalink  |  related link

<<First <Back | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | Next> Last>>