gpt4 book ai didi

java - 无法使用引用访问组件

转载 作者:行者123 更新时间:2023-12-01 07:07:30 28 4
gpt4 key购买 nike

我无法从 Square 类中引用 Colors 类。我之前创建过一个引用,但是当该类扩展另一个类(例如本例中的 Canvas)时,似乎会发生这种情况。

这是我的代码:

颜色:

import java.awt.*;

import javax.swing.*;




public class Colours extends Canvas {

Colours(){
JPanel menupn;
ButtonGroup group;
JRadioButton square;
JRadioButton rect;
JRadioButton circle;
JFrame frame;
JPanel sqpn;
JPanel crpn;
JPanel rtpn;
Circle Circle;
Rect Rect;
Square Square;

Circle = new Circle();
Rect = new Rect();
Square = new Square(this);
menupn = new JPanel();
group = new ButtonGroup();
square = new JRadioButton("Square");
rect = new JRadioButton("Rectangle");
circle = new JRadioButton("Circle");
frame = new JFrame("Colours");

frame.setSize(1000,500);
frame.setLayout(null);

group.add(square);
group.add(circle);
group.add(rect);
group.setSelected(square.getModel(),true);

square.addActionListener(Square);

circle.addActionListener(Circle);

rect.addActionListener(Rect);

menupn.setLayout(new GridLayout(3,1));
menupn.add(square);
menupn.add(circle);
menupn.add(rect);
menupn.setBounds(0, 360, 1000, 100);

this.setBackground(new Color(255,255,255));
this.setBounds(0,0,1000,400);

frame.add(menupn);
frame.add(this);



frame.setVisible(true);


}

public void paint(Graphics g){

g.fillRect(0,0,50,50);
g.fillOval(100,100,50,50);
g.fillRect(200,200,100,50);
}



public static void main(String[] args) {

Colours Colours = new Colours();

}
}

形状:

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JLabel;



public class Square implements ActionListener {
Colours Colours;
JPanel panel;
JTextField colfld1;
JTextField colfld2;
JTextField colfld3;
JTextField locx;
JTextField locy;


Square(Colours Colours){
this.Colours = Colours;
}

public void actionPerformed(ActionEvent e) {

panel = new JPanel();
colfld1 = new JTextField(3);
colfld2 = new JTextField(3);
colfld3 = new JTextField(3);
locx = new JTextField(4);
locy = new JTextField(3);
JLabel positionx = new JLabel("X Axis Position");
JLabel positiony = new JLabel("Y Axis Position");
JLabel rgb = new JLabel("RGB Value");
panel.setBackground(new Color(0,0,0));
panel.setBounds(0, 0, 100, 200);

}

}

我可以使用 Colors 中的所有方法,但无法访问它的所有组件。现在不需要圆形和矩形类。我是新手

最佳答案

您在其构造函数内声明所有 Colors 的组件变量。这意味着这些变量在构造函数之外无法访问。您想将它们声明为类上的字段。

换句话说,移动这些行:

JPanel menupn;
ButtonGroup group;
JRadioButton square;
JRadioButton rect;
JRadioButton circle;
JFrame frame;
JPanel sqpn;
JPanel crpn;
JPanel rtpn;
Circle Circle;
Rect Rect;
Square Square;

此行上方:

Colours(){

关于java - 无法使用引用访问组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20752722/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com