📄 graphjframe.java
字号:
package graphics;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GraphJFrame extends JFrame{
boolean add = false;
private DrawPanel drawPanel;
private JPanel displayPanel=new JPanel();
private JTextField inputA=new JTextField(4);
private JTextField inputB=new JTextField(4);
private JTextField inputAA=new JTextField(4);
private JTextField inputBB=new JTextField(4);
private JButton button=new JButton("确定");
private JButton button2=new JButton("叠加");
public GraphJFrame(){
displayPanel.setBackground(Color.CYAN);
displayPanel.setSize(getSize().width,900);
inputA.setText("20");
inputB.setText("80");
inputAA.setText("20");
inputBB.setText("80");
displayPanel.add(new JLabel("绘制正弦曲线:y=b*sin*x/a),请输入a和b的值,a="));
displayPanel.add(inputA);
displayPanel.add(new JLabel("b="));
displayPanel.add(inputB);
displayPanel.add(button);
displayPanel.add(new JLabel("aa="));
displayPanel.add(inputAA);
displayPanel.add(new JLabel("bb="));
displayPanel.add(inputBB);
displayPanel.add(button2);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
drawPanel.repaint();
}
});
//叠加
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
add=true;
drawPanel.repaint();
}
});
getContentPane().setLayout(new BorderLayout());
getContentPane().add(displayPanel,"North");
drawPanel=new DrawPanel(this);
//将当前对象传入DrawPanel类的构造函数中做后续处理
getContentPane().add(drawPanel,"Center");
}
public static void main(String []args){
GraphJFrame GJ = new GraphJFrame() ;
GJ.setSize(800,400);
GJ.setVisible(true);
GJ.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
}
double f(double x){
double a=Double.valueOf(inputA.getText()).doubleValue();
// Double.valueOf返回保存用参数字符串 s 表示的 double 值的 Double 对象。
// Double.doubleValue()返回此 Double 对象的 double 值。所以这个函数是必须的
double b=Double.valueOf(inputB.getText()).doubleValue();
return (Math.sin(x/a)*b+getSize().height/2);
}
double f2(double x){
double a=Double.valueOf(inputA.getText()).doubleValue();
double b=Double.valueOf(inputB.getText()).doubleValue();
double aa=Double.valueOf(inputAA.getText()).doubleValue();
double bb=Double.valueOf(inputBB.getText()).doubleValue();
return (Math.sin(x/(a+aa))*(b+bb)+getSize().height/2);
}
}
class DrawPanel extends JPanel{
/**
* graApp不能直接引用 因为没有初始化
* 并且使
*/
GraphJFrame graApp;
public DrawPanel(GraphJFrame owner){
graApp=owner;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.ORANGE);
g.clearRect(0,0,getSize().width,getSize().height);
// 通过使用当前绘图表面的背景色进行填充来清除指定的矩形。
if(graApp.add == false){
for (int x = 0; x < getSize().width; x++) {
g.drawLine(x, (int) (graApp.f(x)), x + 1, (int) (graApp.f(x + 1)));
}
}
else {
for (int x = 0; x < getSize().width; x++)
g.drawLine(x, (int)(graApp.f2(x)), x+1,(int)(graApp.f2(x+1)));
graApp.add = false;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -