我不明白参数和参数之间的连接或区别。你能用这两种方法吗?你怎么回答论点?非常感谢任何帮助。
答案 0 :(得分:6)
警告:很多人不区分“参数”和“参数”。他们应该,但他们不这样做 - 所以你很可能会看到许多页面使用不正确的术语。
当您声明方法或构造函数时,参数是您在声明中放置以接收要使用的值的位。例如:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimpleGui implements ActionListener {
private MyDrawPanel drawPanel;
public static void main(String[] args) {
Runnable r = new Runnable () {
@Override
public void run () {
new SimpleGui ().go ();
}
};
EventQueue.invokeLater ( r );
}
public void go() {
drawPanel = new MyDrawPanel();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
JButton button = new JButton( "Change colors" );
button.addActionListener( this );
frame.add( drawPanel, BorderLayout.CENTER );
frame.add( button, BorderLayout.PAGE_END );
frame.pack ();
frame.setLocationByPlatform ( true );
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
drawPanel.setValues ();
}
}
class MyDrawPanel extends JPanel {
private int width = 300;
private int height = 300;
private int red;
private int green;
private int blue;
private Color randomColor;
/*
* Make this one customary habbit,
* of overriding this method, when
* you extends a JPanel/JComponent,
* to define it's Preferred Size.
* Now in this case we want it to be
* as big as the Image itself.
*/
@Override
public Dimension getPreferredSize () {
return new Dimension ( width, height );
}
public void setValues () {
red = ( int ) ( Math.random() * 255 );
green = ( int) ( Math.random() * 255 );
blue = ( int ) ( Math.random() * 255 );
randomColor = new Color( red, green, blue );
repaint ();
}
/*
* This is where the actual Painting
* Code for the JPanel/JComponent goes.
* Here the first line super.paintComponent(...),
* means we want the JPanel to be drawn the usual
* Java way first (this usually depends on the opaque
* property of the said JComponent, if it's true, then
* it becomes the responsibility on the part of the
* programmer to fill the content area with a fully
* opaque color. If it is false, then the programmer
* is free to leave it untouched. So in order to
* overcome the hassle assoicated with this contract,
* super.paintComponent(g) is used, since it adheres
* to the rules, and performs the same task, depending
* upon whether the opaque property is true or false),
* then later on we will add our image to it, by
* writing the other line, g.drawImage(...).
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent ( g );
g.setColor(randomColor);
g.fillOval(70, 70, 100, 100);
}
}
此处public void foo(int x, int y)
和x
是参数。在方法中,它们就像局部变量一样。
当您调用方法或构造函数时,参数是您传入的值。这些参数用作参数的初始值。例如:
y
此处5和3是参数 - 因此参数foo(5, 3);
将以值5开头,参数x
将以值3开头。当然,您可以使用参数(或任何其他变量)也作为参数。例如:
y
此处public void foo(int x, int y) {
System.out.println(y);
}
是y
方法中的参数,但其值被用作foo
方法的参数。
你能用它作为方法吗?
不,他们是一个完全不同的概念。
你如何回归论点?
同样,这并没有多大意义。您可以在return语句中使用参数的值:
println