-
May 22nd, 2009, 08:13 AM
#1
Adding Buttons to Jframe app, Help Please!
I'm making a paint program for my end of the year project and my teacher has no idea how to do graphics/apps, so i was wondering if anyone here could tell me the proper way to add a button with a color changing ability? (I'd assume add an action listener that sets color, but that hasn't been working). My main issue is whenever i do get a button successfully in the program, it covers up my drawing area so it is just a button and the drawing doesn't work. It just draws by making lots of small vectors.
Here is the code (Sorry if i'm adding it wrong)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Vector;
public class Paint_Area extends JFrame{
private final int WIDTH = 500, HEIGHT = 400;
int x1,y1;
int x2,y2;
Vector lines = new Vector();
Vector colors = new Vector();
JButton red;
public Paint_Area()
{
super("Dave's Drawing Program");
getContentPane().add(new JLabel("Draw in this Area"), BorderLayout.SOUTH);
addMouseListener(
new MouseAdapter(){
public void mouseDragged(MouseEvent event){
event.consume();
colors.addElement(getForeground());
lines.addElement(new Rectangle(x1, y1, event.getX(), event.getY()));
x1 = event.getX();
y1 = event.getY();
repaint();
}
public void mousePressed(MouseEvent event){
event.consume();
colors.addElement(getForeground());
lines.addElement(new Rectangle(event.getX(), event.getY(), -1, -1));
x1 = event.getX();
y1 = event.getY();
repaint();
}
}
);
addMouseMotionListener(
new MouseMotionAdapter(){
public void mouseDragged(MouseEvent event){
event.consume();
colors.addElement(getForeground());
lines.addElement(new Rectangle(x1, y1, event.getX(), event.getY()));
x1 = event.getX();
y1 = event.getY();
repaint();
}
public void mousePressed(MouseEvent event){
event.consume();
colors.addElement(getForeground());
lines.addElement(new Rectangle(event.getX(), event.getY(), -1, -1));
x1 = event.getX();
y1 = event.getY();
repaint();
}
}
);
setSize(WIDTH, HEIGHT);
setBackground(Color.white);
setVisible(true);
}
public void paint(Graphics g) {
int np = lines.size();
/* draw the current lines */
// g.setColor(getForeground());
for (int i=0; i < np; i++) {
Rectangle p = (Rectangle)lines.elementAt(i);
g.setColor((Color)colors.elementAt(i));
if (p.width != -1) {
g.drawLine(p.x, p.y, p.width, p.height);
} else {
g.drawLine(p.x, p.y, p.x, p.y);
}
}
}
public static void main(String args[])
{
Paint_Area application = new Paint_Area();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|