Java 如何在另一个类中使用一个类的方法
这是头等舱Java 如何在另一个类中使用一个类的方法,java,Java,这是头等舱 // 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
// 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 ????????
}
如果我了解您需要的是使
Graphics2D g2
成为类属性。这样,类中的所有方法都可以访问该“全局”变量:
public class MyPanel extends JPanel {
Graphics2D g2;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g2 = (Graphics2D) g;
...
}
public void actionPerformed(ActionEvent ae) {
g2.setColor(...);
}
}
向类中添加
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();
}
}