gpt4 book ai didi

java - 如何在另一个类中使用一个类的方法

转载 作者:行者123 更新时间:2023-12-01 15:00:41 26 4
gpt4 key购买 nike

这里是头等舱

     // extending class from JPanel
public class MyPanel extends JPanel {
// variables used to draw oval at different locations
int mX = 200;
int mY = 0;

// overriding paintComponent method
public void paintComponent(Graphics g) {
// erasing behaviour – this will clear all the
// previous painting
super.paintComponent(g);
// Down casting Graphics object to Graphics2D
Graphics2D g2 = (Graphics2D) g;
// changing the color to blue
g2.setColor(Color.blue);

// drawing filled oval with blue color
// using instance variables
g2.fillOval(mX, mY, 40, 40);

现在我想在下面问号所在的地方使用方法 g2.setColot(Colot.blue) 。

// event handler method

public void actionPerformed(ActionEvent ae) {

// if ball reached to maximum width of frame minus 40 since diameter of ball is 40 then change the X-direction of ball

if (f.getWidth() - 40 == p.mX) {
x = -5;
????? set the color as red ????????

}

最佳答案

向您的类添加一个 Color 成员。当你想改变颜色时,改变成员的值并调用repaint():

    public class MyPanel extends JPanel {
int mX = 200;
int mY = 0;
Color myColor = Color.blue; //Default color is blue,
//but make it whatever you want

public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(myColor);

g2.fillOval(mX, mY, 40, 40);
}


public void actionPerformed(ActionEvent ae) {

if (f.getWidth() - 40 == p.mX) {
x = -5;
myColor = Color.red;
repaint();
}
}

关于java - 如何在另一个类中使用一个类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13691177/

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