I have an oval component on a panel in OvalShape.java that I would like to change the color of
public class OvalShape extends JPanel {
private int diameter = 100;
private Color myColor = Color.RED;
//create the actual panel
public OvalShape() {
Dimension size = getPreferredSize();
size.width = 300;
size.height= 300;
setPreferredSize(size);
setBorder(BorderFactory.createLoweredSoftBevelBorder());
}
public void setMyColor(Color theColor) {
this.myColor = theColor;
}
//create the oval
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(0, 0, diameter, diameter);
g.setColor(myColor);
}
//method for setting the diameter
public void setDiameter(int newDiameter) { //method to create diameter
//if diam invalid set to 10
diameter = (newDiameter >=0 ? newDiameter : 10);
repaint(); //repaint panel
}
}
from OvalPanel.java I want to be able to change the color. Here is what that class looks like
public class OvalPanel extends JPanel {
public int diameter = 100; //default diameter of the oval
public JSlider diamSlider;
public JLabel diamLabel;
public OvalShape ovalShape;
public OvalPanel() {
Dimension size = getPreferredSize();
size.width = 500;
setPreferredSize(size);
//create components
diamSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 300, 100);
diamSlider.setSnapToTicks(true);
diamSlider.setMajorTickSpacing(100);
diamSlider.setMinorTickSpacing(25);
diamSlider.setPaintTicks(true);
diamSlider.setPaintLabels(true);
diamLabel = new JLabel("Diameter = " + diameter);
ovalShape = new OvalShape();
ovalShape.setDiameter(diamSlider.getValue());
ovalShape.setMyColor(Color.RED);
//set listeners
diamSlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
diamLabel.setText("Diameter = " + diamSlider.getValue());
ovalShape.setDiameter(diamSlider.getValue());
}
});
//set layout
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
////////first row////////
gbc.gridx = 0;
gbc.gridy = 0;
add(ovalShape, gbc);
////////second row////////
gbc.gridx = 0;
gbc.gridy = 1;
add(diamSlider, gbc);
////////third row////////
gbc.gridx = 0;
gbc.gridy = 2;
add(diamLabel, gbc);
}
but I don't really understand why this isn't working. The oval just comes out black. I have tried to apply the same theory that I did when creating the diameter slider as I am able to change the diameter of the oval using the slider in OvalPanel.java
Thanks for any help
g.fillOval(0, 0, diameter, diameter);
g.setColor(myColor);
You need to set the color BEFORE you paint the oval.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.