I would like to apologise in advance for writing this code in Estonian, not in English. I am beginner in Java(2-3hour experience so far). I am trying to write code for customizable chess table.(size customizable)So far I have been able to write code for the table but I have problem with coloring it. How do I color table according to the right colors of chess table ? package esimene;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Joonistame4 extends JComponent implements ActionListener{
int suurus = 10;
int korgus = 10;
int x = 50;
int y = 50;
JTextField tf = new JTextField(String.valueOf(suurus));
JTextField tf2 = new JTextField(String.valueOf(korgus));
JColorChooser varvivalik = new JColorChooser();
JPanel p = new JPanel(new GridLayout(3,2)); //rida , veerg
JCheckBox cb = new JCheckBox();
public Joonistame4(){
setLayout(new BorderLayout());
p.add(new Label("suurus: "));
p.add(tf);
add(p, BorderLayout.SOUTH);
//add(varvivalik, BorderLayout.EAST);
tf.addActionListener(this);
cb.addActionListener(this);
varvivalik.setPreviewPanel(new JPanel());
}
public void paintComponent(Graphics g){
int suurus_kokku = 8*suurus;
g.setColor(Color.BLUE);
for(int x = suurus; x < suurus_kokku; x = x+suurus) {
for(int y = suurus; y < suurus_kokku; y = y+suurus) {
if(cb.isSelected()){
g.fillRect(50, 50, suurus, suurus);
}else{
g.drawRect(50+y, 50+x, suurus, suurus);
}
}
}
}
public static void main(String[] args) {
JFrame aken = new JFrame("Esimene aken");
aken.setSize(600, 600);
aken.getContentPane().add(new Joonistame4());
aken.setVisible(true);
aken.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent arg0) {
suurus = Integer.parseInt(tf.getText());
repaint();
}
}
First let me tell you that this is a somewhat odd approach to creating a chessboard in Java. But that also depends on your goal - I guess for educational reasons you should continue :)
To use the Java Graphics
to draw with different colors you have to use the g.setColor(SOME_COLOR);
in front of each g.fillRect(...)
or g.drawRect(...)
or any other painting function. Those functions always paint with the "currently set" color.