So basically when I try to increase the number of the variable which increases the number of rectangles, it starts to overlap. I'm sure it has an easy fix. I have a feeling that i need to add something to the coordinates but i'm not sure what exactly. Heres the code
public class Pattern extends JComponent implements ActionListener{
JPanel panel = new JPanel(new GridLayout(4, 4));
int width = 100;
int height = 100;
int number = 1;
JTextField tf = new JTextField(String.valueOf(width));
JTextField kl = new JTextField(String.valueOf(height));
JColorChooser color = new JColorChooser();
JCheckBox selection = new JCheckBox();
JTextField howMany =new JTextField(String.valueOf(number));
public Pattern(){
setLayout(new BorderLayout());
paneel.add(new Label("Width:"));
paneel.add(tf);
paneel.add(new Label("Height:"));
paneel.add(kl);
paneel.add(new Label("Filled in:"));
paneel.add(selection);
paneel.add(new Label("Number:"));
paneel.add(howMany);
tf.addActionListener(this);
kl.addActionListener(this);
selection.addActionListener(this);
howMany.addActionListener(this);
add(panel, BorderLayout.SOUTH);
add(color, BorderLayout.EAST);
color.setPreviewPanel(new JPanel());
}
public void paintComponent(Graphics g){
g.setColor(color.getColor());
for(int i=0; i<number; i++){
if(selection.isSelected()){
g.fillRect((width)*i, 10, width, height);
g.drawRect((width)*i, 110, width, height);
g.drawRect((width)*i+width, 10, width, height);
g.fillRect((width)*i+width, 110, width, height);
} else {
g.drawRect((width)*i, 10, width, height);
g.fillRect((width)*i, 110, width, height);
g.fillRect((width)*i+width, 10, width, height);
g.drawRect((width)*i+width, 110, width, height);
}
}
}
public static void main(String[] args){
JFrame window = new JFrame("Window");
window.setSize(1000, 1000);
window.getContentPane().add(new Pattern());
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(tf.getText());
System.out.println(kl.getText());
width = Integer.parseInt(tf.getText());
height = Integer.parseInt(kl.getText());
number =Integer.parseInt(howMany.getText());
repaint();
}
}
Aucun commentaire:
Enregistrer un commentaire