[英]Changing the value of a outer class member via a inner class
I am trying to manipulate a an outer class member via an inner class event handling method. 我试图通过内部类事件处理方法来操纵外部类成员。
A class MyColorChooser
has a private member sliderColor
. MyColorChooser
类具有私有成员sliderColor
。 The default value of sliderColor
is set to black in the constructor. 在构造函数中,
sliderColor
的默认值设置为black。
An inner class is used to handle the construction of new colors via user input from JSliders
. 内部类用于通过
JSliders
用户输入来处理新颜色的构造。 I then set the value of sliderColor
to this new colour via a setter method in the outer class. 然后,通过外部类中的setter方法将
sliderColor
的值设置为此新颜色。
Problem is that an instance of the outer class uses its own getColor
method which always returns the value set by the constructor (black), and not the new value it has been assigned. 问题是外部类的实例使用其自己的
getColor
方法,该方法始终返回构造函数设置的值(黑色),而不是返回已为其分配的新值。 How can I make it so that the inner class method is able to directly alter the value in the outer member variable? 如何使内部类方法能够直接更改外部成员变量中的值?
UPDATED 更新
yes it seems like it should be working but got me stumped why its not......have posted soem of what i belive are the relevant bits f code: 是的,似乎它应该工作,但是让我感到困惑,为什么它不............贴出了我相信的东西是相关的f代码:
NB Apologies in advance if code unsuitable as wasnt sure how much to insert.... NB事先致歉,如果代码不合适,请确保插入多少...。
Debugging: i have debugged and noted that colour is the colour it should be in the inner class and also the setColour outerclass method...so im suspecting its been changed Back to the default constructor value...just not sure where or by what...ill just keep debugging 调试:我已经调试并注意到color是它应该在内部类中以及setColour外类方法中应该使用的颜色...因此我怀疑它已更改为默认构造函数值...只是不确定在哪里或通过什么方式...只是继续调试
Class MyColorChooser with which allows creation of color object via input fom JSliders handled by a inner class event hander: MyColorChooser类,该类允许通过内部类事件处理程序处理的输入JSlider创建颜色对象:
* Part 4
* JPanel subclass that alloews the user define the color attributes for shapes
* utlising 3 JSliders
*/
package Assignment2;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
*
* @author Ciaran Mooney dancingbush@gmail.com
*/
public class MyColorChooser4 extends JPanel {
//declare instance varibles
//JSlider colors
private JSlider blueSlider;
private JSlider greenSlider;
private JSlider redSlider;
//display color chossen by user varibles
private JTextField redChoice;
private JTextField greenChoice;
private JTextField blueChoice;
private DrawPanel shapeColor = new DrawPanel(); //set color of drawpanel onbject
//prompts for user input
private JLabel redInput;
private JLabel blueInput;
private JLabel greenInput;
//color object created
private Color colorChoice ; ;
private JTextField theColor;
//no arg GUI construtor gets user input and constructs color
public MyColorChooser4() {
//default layout of panel is set to GridLayout 4 cols 4 rows
this.setLayout(new GridLayout(4, 4));
greenInput = new JLabel("Green: ");
greenSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 1);
greenChoice = new JTextField("0", 4);//default text
greenChoice.setEditable(false);
add(greenInput);
add(greenSlider);
add(greenChoice);
redInput = new JLabel("Red: ");
redSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 1);
redChoice = new JTextField("0", 4);//default text
redChoice.setEditable(false);
add(redInput);
add(redSlider);
add(redChoice);
blueInput = new JLabel("Blue: ");
blueSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 1);
blueChoice = new JTextField("0", 4);//default text
blueChoice.setEditable(false);
add(blueInput);
add(blueSlider);
add(blueChoice);
//set default color black and declare inner class event handlers
//sliders utlise ChengeListeners
greenSlider.addChangeListener(new SlideHandler());
redSlider.addChangeListener(new SlideHandler());
blueSlider.addChangeListener(new SlideHandler());
colorChoice = Color.RED;
//label to diplay color chosen, and blnk JLabel to move color to center
theColor = new JTextField(4);
JLabel preview = new JLabel(" ");
add(preview);
add(theColor);
theColor.setBackground(colorChoice);
}//end GUI constructor
//set color
public void setSlideColor(Color colorSlide) {
colorChoice = colorSlide;
}//end set colorChoice
//get methods for fields
public Color getColor() {
return colorChoice;
}//end getColor
//return slider for red value
public JSlider getRedSlider() {
return redSlider;
}//edn get red slider
//retirn slider for green value
public JSlider getGreenSlider() {
return greenSlider;
}//edn getGreenSlider
//return slider for blue value
public JSlider getBlueSlider() {
return blueSlider;
}//end getGreenSlider
//private inner class for event handliing on sliders & implement abstract class
private class SlideHandler implements ChangeListener {
private Color colorSlide;
@Override
public void stateChanged(ChangeEvent e) {
//return integers from sliders
int blue = blueSlider.getValue();
int green = greenSlider.getValue();
int red = redSlider.getValue();
//now construct a new color based on these values
colorSlide = new Color(red, green, blue);
setSlideColor(colorSlide);
//display integer value of color chosen in relative textfield
//use String method valueOf to return string rep of integer
//display chossen color in text area
redChoice.setText(String.valueOf(red));
redChoice.setBackground(new Color(red, 0, 0));
greenChoice.setText(String.valueOf(green));
greenChoice.setBackground(new Color(0, green, 0));
blueChoice.setText(String.valueOf(blue));
blueChoice.setBackground(new Color(0, 0, blue));
//set chosen color preview
theColor.setBackground(colorChoice);
theColor.setText("Preview");
}//end stateChanged method
}//end inner class SlideHandler
}//end class MyColorChooser4
Then Class ShapePanel which is a menu for which user can select various attributes of a shape to be drawn including colour. 然后是ShapePanel类,这是一个菜单,用户可以选择要绘制的形状的各种属性(包括颜色)。 Color determined thrught slection via a JComobobox of an array of clolor objects.
通过一个Clolo对象数组的JComobobox,颜色决定了整体的选择。 The colour from MyColorCHooser4 is acquired via an instance of teh class invoking the its getColor method:
MyColorCHooser4的颜色是通过teh类的实例调用其getColor方法获取的:
declaration and intilisation of the above 声明和使用
public DrawPanel draw = new DrawPanel();
private MyColorChooser4 sliderColor = new MyColorChooser4();
//array holding color objects
private Color colors[] = {Color.BLACK, Color.BLUE, Color.CYAN,
Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY,
Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE,
Color.YELLOW, sliderColor.getColor()};
//array carrying color strings
private String colorNames[] = {"Black", "Blue", "Cyan",
"Dark Gray", "Gray", "Green", "Light Gray", "Magenta",
"Orange", "Pink", "Red", "White", "Yellow", "Slider Color"};
Event handler method of class ShapePanel which allows selection of colour.... ShapePanel类的事件处理程序方法,允许选择颜色。
color = new JComboBox(colorNames);
color.setMaximumRowCount(6);
color.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
draw.setCurrentColor((colors[color.getSelectedIndex()]));;
} //end if
}//end itemStateChnaged
});//end annmonouys class and action event method
componments.add(color);
The instance draw of class DrawPanel sets the colour the shape shoudl be drawn in via the following set method..... DrawPanel类的实例绘制通过以下set方法设置应绘制形状的颜色。
//set current color
public void setCurrentColor(Color color) {
//set currentColor from JCombox input handler
currentColor = color;
//generate a random startColor for Gradient color
int red = (int) (Math.random() * 256);
int green = (int) (Math.random() * 256);
int blue = (int) (Math.random() * 256);
//cyclic vs acylic fill
colorFillStyle = new Random();
boolean gradientShift = colorFillStyle.nextBoolean();
//create gradient object
Color startColor = new Color(red, green, blue);
gradientColor = new GradientPaint(10f, 10f, startColor, 350f, 350f, currentColor, gradientShift);
}//end set color method
However when the shape is drawn the colour is always red, reflecting the colour intilization value in the MyColorChooser4 constructor.... 但是,绘制形状时,颜色始终为红色,反映了MyColorChooser4构造函数中的颜色转化值。
Hopefully this is somewhat useful...... 希望这是有用的......
Without seeing your code, it is impossible to know for certain what the issue is, but there are a couple of possibilities: 如果没有看到您的代码,就无法确定是什么问题,但是有两种可能:
1: The set method in your outer class is incorrect. 1:您的外部类中的set方法不正确。 Seems unlikely, but always worth checking since perhaps it is written as:
似乎不太可能,但始终值得检查,因为它可能写为:
public void setColor(Color color)
{
// Should be this.color =
color = color;
}
2: Your inner class is not calling the outer classes set method, perhaps the inner class has declared its own set method that takes precedence in your call. 2:您的内部类没有调用外部类的set方法,也许内部类已经声明了自己的set方法,该方法优先于您的调用。
3: The inner class is never actually being called, possibly because your event is not being triggered. 3:永远不会真正调用内部类,这可能是因为未触发您的事件。
Ultimately, your setMethod is not being called, it is not doing what you think it should be doing, or something else is resetting the value after you call the set method. 最终,没有调用setMethod,没有按照您认为的方式运行,或者在调用set方法后,其他操作正在重置该值。 As far as I can tell, these are the only possibilities for why your value would not be set as expected.
据我所知,这是为什么您的价值无法达到预期的唯一可能性。
If you post your code then we can arrive at a more specific answer to your problem. 如果您发布代码,那么我们可以为您的问题提供更具体的答案。
@increment1 I avoided the the singleton tactic and got wat i needed by creating all instances req in the one class and achieved the changes needed by attaching listeners to event handlers . @ increment1我避免了单例策略,并通过在一个类中创建所有实例req来获得所需的资源,并通过将侦听器附加到事件处理程序来实现所需的更改。 .
。
My problem was i was expecting the same behaviour from two separate instances of my drawPanel class, not well thought out and inexperience. 我的问题是我期望我的drawPanel类的两个单独实例具有相同的行为,但没有深思熟虑和缺乏经验。
Thanks again C 再次感谢C
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.