drawing a rectangle and setting it to user specified color--help
I am an extreme newbie, so any help pointing me in the right direction would be amazing.
Below is code. I can draw the rectangles, but can't figure out how to make them the color the user specifies in Color #1 and Color #2.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
publicclass test{
publicstaticvoid main(String[] args)
{
JFrame frame =new JFrame("test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final MyComponent picture =new MyComponent();
picture.setPreferredSize(new Dimension(601, 601));
JPanel controls =new JPanel();
controls.setLayout(new GridLayout(2,6));
controls.add(new JLabel("rows", JLabel.CENTER));
controls.add(new JLabel("columns", JLabel.CENTER));
controls.add(new JLabel("color #1", JLabel.CENTER));
controls.add(new JLabel("color #2", JLabel.CENTER));
final JTextField rows =new JTextField("0");
controls.add(rows);
final JTextField columns =new JTextField("0");
controls.add(columns);
final JTextField color1 =new JTextField("color");
controls.add(color1);
final JTextField color2 =new JTextField("color");
controls.add(color2);
JPanel content = (JPanel)frame.getContentPane();
content.setLayout(new BorderLayout());
content.add(picture, BorderLayout.CENTER);
content.add(controls, BorderLayout.NORTH);
ActionListener action =new ActionListener( ){
publicvoid actionPerformed(ActionEvent evt){
int r=Integer.parseInt(rows.getText( ));
int c=Integer.parseInt(columns.getText( ));
String c1=color1.getText();
String c2=color2.getText();
System.out.println(c1);
System.out.println(c2);
picture.draw(r,c,c1,c2);
}
};
rows.addActionListener(action);
columns.addActionListener(action);
color1.addActionListener(action);
color2.addActionListener(action);
frame.pack();
frame.setVisible(true);
}
}
class MyComponentextends JComponent{
privateint rows = 0, columns = 0;
private String color1, color2;
publicvoid draw(int r,int c, String c1, String c2)
{
rows = r; columns = c; color1 = c1; color2 = c2;
repaint();
}
publicvoid paintComponent(Graphics g)
{
int row;
int column;
int x, y;
for (row = 0; row < rows; row++)
{
for (column = 0; column < columns; column++)
{
x = column * 60;
y = row * 60;
if ((row % 2) == (column % 2))
g.setColor(Color.yellow);
else
g.setColor(Color.magenta);
g.fillRect(x, y, 60, 60);
}
}
}
}
EDIT: I only have the 2 colors set as yellow and magenta currently to test it to see if it would draw. Setting it to what the user specifies is what I have no clue how to do.
Message was edited by:
futuregrad08

