Untuk membuat aplikasi gui garis dalam netbeans dibutuhkan beberapa elemen yaitu:
- Membuat variabel x Start, x End, y Start dan y End
- Event MouseDragged
- Event Mouse Pressed
- Event Mouse Released
- Metode lineBuffer dan lineCountainer
1. Buat Project baru dengan nama packages = "Drawing" dan JFrame form = "MainForm
2. Buatlah desain dengan menggunakan panel dengan nama variabel "jPanel1" dan radio button dengan nama variabel "jRadioLine"
3. Tuliskan script dibawah ini dalam sourcenya:
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.List;
public class MainForm extends javax.swing.JFrame {
/** Creates new form MainForm */
public MainForm() {
initComponents();
}
private int xStart;
private int yStart;
private int xEnd;
private int yEnd;
private Line2D lineBuffer;
private Graphics2D g2;
private List<Line2D> lineContainer = new ArrayList();
private void jPanel1MousePressed(java.awt.event.MouseEvent evt) {
if (g2 == null)
{
g2 = (Graphics2D) jPanel1.getGraphics();
}
xStart = evt.getX();
yStart = evt.getY();
xEnd = evt.getX();
yEnd = evt.getY();
}
private void jPanel1MouseDragged(java.awt.event.MouseEvent evt) {
if (jRadioLine.isSelected())
{
jPanel1.update(g2);
xEnd = evt.getX();
yEnd = evt.getY();
lineBuffer = new Line2D.Float ((float) xStart, (float) yStart, (float) xEnd, (float) yEnd);
DrawAll();
g2.draw(lineBuffer);
}
}
rivate void jPanel1MouseReleased(java.awt.event.MouseEvent evt) {
if (jRadioLine.isSelected())
{
jPanel1.update(g2);
xEnd = evt.getX();
yEnd = evt.getY();
lineBuffer = new Line2D.Float ((float) xStart, (float) yStart, (float) xEnd, (float) yEnd);
lineContainer.add(lineBuffer);
DrawAll();
}
}
private void DrawAll()
{
for (int i = 0; i < lineContainer.size(); i++)
{
g2.draw(lineContainer.get(i));
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new MainForm().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
private javax.swing.JRadioButton jRadioLine;
// End of variables declaration
}
4. Dan terakhir run Project atau F6, dan hasilnya lihat gambar diatas.
0 komentar:
Post a Comment