0

我有一个家庭作业,我必须编写一个程序,询问用户 4 个点,并计算线的斜率/方程。我想,一旦用户点击计算按钮,在我的程序窗口的左角显示一个简单的折线图。

我该怎么做呢?它只需要绘制 y 截距并显示线,我只是不知道如何真正解决这个问题。我的程序运行良好,一切正常,只需要在图表上开始,我不知道如何开始。有任何想法吗?

如果您将我的代码复制粘贴到 JGrasp 或任何 IDE 中,您会明白我的意思,我只想在组合中添加一个图表。

我应该如何制作图表,我应该如何将它放在窗口中,以便在我点击计算时它会改变?

这是我的代码:

public class lineCalculator extends javax.swing.JFrame {

public lineCalculator() {
initComponents();
}

@SuppressWarnings("unchecked")
private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    jLabel5 = new javax.swing.JLabel();
    jSeparator1 = new javax.swing.JSeparator();
    jTextField1 = new javax.swing.JTextField();
    jTextField2 = new javax.swing.JTextField();
    jTextField3 = new javax.swing.JTextField();
    jTextField4 = new javax.swing.JTextField();
    jLabel6 = new javax.swing.JLabel();
    jLabel7 = new javax.swing.JLabel();
    jButton1 = new javax.swing.JButton();
    jTextField5 = new javax.swing.JTextField();
    jTextField6 = new javax.swing.JTextField();
    jLabel8 = new javax.swing.JLabel();
    jTextField7 = new javax.swing.JTextField();
    jLabel9 = new javax.swing.JLabel();
    jTextField8 = new javax.swing.JTextField();
    jLabel10 = new javax.swing.JLabel();
    jTextField9 = new javax.swing.JTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); 
    jLabel1.setText("Line Calculator");

    jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); 
    jLabel2.setText("X1");

    jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); 
    jLabel3.setText("X2");

    jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); 
    jLabel4.setText("Y1");

    jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); 
    jLabel5.setText("Y2");

    jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); 
    jLabel6.setText("Slope");

    jLabel7.setFont(new java.awt.Font("Tahoma", 1, 12)); 
    jLabel7.setText("Distance between points");

    jButton1.setFont(new java.awt.Font("Tahoma", 1, 12)); 
    jButton1.setText("Calculate");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jLabel8.setFont(new java.awt.Font("Tahoma", 1, 12)); 
    jLabel8.setText("Angle(radians)");

    jLabel9.setFont(new java.awt.Font("Tahoma", 1, 12)); 
    jLabel9.setText("Angle(degrees)");

    jLabel10.setFont(new java.awt.Font("Tahoma", 1, 12)); 
    jLabel10.setText("Equation of the line");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(211, 211, 211)
                    .addComponent(jLabel1))
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(39, 39, 39)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel6)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(30, 30, 30)
                                    .addComponent(jLabel7)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel8)
                                    .addGap(18, 18, 18)
                                    .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(39, 39, 39)
                                    .addComponent(jLabel9)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jButton1)
                            .addGap(29, 29, 29)
                            .addComponent(jLabel10)
                            .addGap(18, 18, 18)
                            .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGroup(layout.createSequentialGroup()
                    .addGap(141, 141, 141)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel2)
                        .addComponent(jLabel3))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jTextField2)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(40, 40, 40)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel4)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jTextField4))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(jLabel5)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 509, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(26, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel1)
            .addGap(29, 29, 29)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2)
                .addComponent(jLabel4)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel3)
                .addComponent(jLabel5)
                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel6)
                .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel7)
                .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(33, 33, 33)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel8)
                .addComponent(jLabel9)
                .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(36, 36, 36)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel10)
                .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap(49, Short.MAX_VALUE))
    );

    pack();
}


public boolean isNumeric(String str)
{
try
{
Double.parseDouble(str);
}
catch(Exception e)
{
return (false);
}
return(true);
}

public double Round(double val, int plc)
{
 double pwr = Math.pow(10,plc);
 val = val * pwr;
 double tmp = (int) val;

if( ((int)(val + .5)) == (int) val)
return (tmp/pwr);
else
return((tmp + 1.0)/pwr);
}


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
double x1;
double x2;
double y1;
double y2;
double length_of_x;
double length_of_y;
double slope;
double opposite;

double angle_degrees;
double angle_radians;
double y_intercept;
double distance_between_2_points;

x1 = (double) (Double.parseDouble(jTextField1.getText()));
x2 = (double) (Double.parseDouble(jTextField2.getText()));
y1 = (double) (Double.parseDouble(jTextField4.getText()));
y2 = (double) (Double.parseDouble(jTextField3.getText()));

length_of_x = x2 - x1;
length_of_y = y2 - y1;
slope = length_of_y / length_of_x;
slope = (double) Round(slope,2);
opposite = y2 - y1;
distance_between_2_points = Math.sqrt((length_of_x * length_of_x) + (length_of_y * length_of_y));
distance_between_2_points = (double) Round(distance_between_2_points,2);
angle_radians = opposite / distance_between_2_points;
angle_radians = (double) Round(angle_radians,2);
angle_degrees = angle_radians * (180 / 3.14159);
angle_degrees = (double) Round(angle_degrees,2);
y_intercept = (y1)-(angle_radians * x1);

jTextField5.setText(slope + "");
jTextField6.setText(distance_between_2_points + "");
jTextField7.setText(angle_radians + "");
jTextField8.setText(angle_degrees + "");
jTextField9.setText("Y = " + slope + "" + "X + " + y_intercept + "");
}

public static void main(String args[]) {
try {
  for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
    if ("Nimbus".equals(info.getName())) {
      javax.swing.UIManager.setLookAndFeel(info.getClassName());
      break;
    }
  }
} catch (ClassNotFoundException ex) {
  java.util.logging.Logger.getLogger(lineCalculator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
  java.util.logging.Logger.getLogger(lineCalculator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
  java.util.logging.Logger.getLogger(lineCalculator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
  java.util.logging.Logger.getLogger(lineCalculator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {

  public void run() {
    new lineCalculator().setVisible(true);
  }
});
}

private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField5;
private javax.swing.JTextField jTextField6;
private javax.swing.JTextField jTextField7;
private javax.swing.JTextField jTextField8;
private javax.swing.JTextField jTextField9;
}
4

4 回答 4

2

..我应该怎么把它放在窗户里..?

线计算器

在之前更改代码,layout.setHorizontalGroup(..例如:

JPanel gui = new JPanel(new BorderLayout());
JPanel graphPanel = new JPanel(new GridBagLayout());
JPanel controls = new JPanel();
GroupLayout layout = new GroupLayout(controls);
controls.setLayout(layout);

gui.add(graphPanel, BorderLayout.LINE_START);
BufferedImage img = new BufferedImage(
    200,200,BufferedImage.TYPE_INT_RGB);
JLabel l = new JLabel(new ImageIcon(img));
graphPanel.add(l);

gui.add(controls);
getContentPane().add(gui);

layout.setHorizontalGroup(..

..我应该如何制作图表..?

将其绘制到BufferedImage,然后repaint()是显示它的标签。

于 2012-11-27T01:59:11.293 回答
2

您可以创建一个扩展 JPanel 的新类。然后将该 JPanel 添加到您现有的 Frame 到您的组布局中。在 JPanel 中,您只需覆盖 paintComponent(Graphics) 方法并在其中进行绘图。

这只是一个使用 400x400 像素的固定屏幕的简单示例,其中 1 个像素等于 1 个坐标。

您可能想要对显示的屏幕进行一些标准化,其中屏幕根据线条放大或缩小。我建议您始终在中间绘制坐标系的原点 (0|0),然后根据需要进行缩放。

private class Graph extends JPanel {
    final int screenWidth = 400;
    final int screenHeight = screenWidth;

    final int xAxisPos = screenHeight/2;
    final int yAxisPos = screenWidth/2;

    public Graph() {
        this.setBounds(0, 0, screenWidth, screenHeight);
    }

    private double y(double x) {
        return 2*x; // This is an example for y=2x
    }

    public void paintComponent(Graphics g) {
        g.setColor(Color.BLACK);
        g.drawLine(0, xAxisPos, screenWidth, xAxisPos); // draws the x-axis
        g.drawLine(yAxisPos, 0, yAxisPos, screenHeight); // draws the y-axis

        int yValueStart = (int) y(-yAxisPos); // calculates the y value on the left edge of the screen
        int yValueEnd = (int) y(screenWidth-yAxisPos); // calculates the y value on the right edge of the screen

        g.setColor(Color.BLUE);
        g.drawLine(0, -yValueStart, screenWidth, -yValueEnd);       
    }
}

在上面的示例中,我将计算结果放入函数 y(double) 中,该函数返回某个 x 值的双精度值。另请注意,在 Swing 中绘制时,坐标系会翻转,这就是为什么在 drawLine 函数中必须将 y 值设为负值的原因。

于 2012-11-27T01:30:43.213 回答
2

本质上,您将需要“标准化”这些点,以便您可以使它们适合已知范围(因为您的图表可能是固定/已知大小)。

这意味着用户不限于输入适合您图形的值,他们可以自由输入他们想要的任何值。

这基本上意味着你要缩放点......就像......

// Size of the component
int width = getWidth();
int height = getHeight();

// p1 and p1 two are java.awt.Point references
// The maximum extend of the points
int maxX = Math.max(p1.x, p2.x);
int maxY = Math.max(p1.y, p2.y);

// Generate a "scale to fit"
float scale = Math.min(width / (float)maxX, height / (float)maxY);

// Scale the points..
int x1 = (int)(p1.x * scale);
int y1 = (int)(p1.y * scale);

int x2 = (int)(p2.x * scale);
int y2 = (int)(p2.y * scale);

这是一个生成随机点的相对简单的示例

public class TestGraph {

    public static void main(String[] args) {
        new TestGraph();
    }

    public TestGraph() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new GraphPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class GraphPane extends JPanel    {

        private Point p1;
        private Point p2;

        public GraphPane() {

            // Generate random points, replace with your own coordinates
            p1 = getRandomPoint();
            p2 = getRandomPoint();

        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            int width = getWidth();
            int height = getHeight();

            int maxX = Math.max(p1.x, p2.x);
            int maxY = Math.max(p1.y, p2.y);

            float scale = Math.min(width / (float)maxX, height / (float)maxY);

            int x1 = (int)(p1.x * scale);
            int y1 = (int)(p1.y * scale);

            int x2 = (int)(p2.x * scale);
            int y2 = (int)(p2.y * scale);

            g.drawLine(x1, y1, x2, y2);

        }

        protected Point getRandomPoint() {
            return new Point(getRandomValue(), getRandomValue());
        }

        protected int getRandomValue() {
            return (int)Math.round(Math.random() * 1000);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

}

可能想通读

欲了解更多信息和想法

于 2012-11-27T00:32:50.960 回答
0

您必须使用 awt 包中的一个对象,并使用他们称为paint 的方法。

然后你必须覆盖每个组件继承的方法......这就是方法

public void paint(Graphics g) {
  super.paint(g);
  g.drawLine(25, 0, 25, 50);
  g.setColor(Color.black);
}

完成此操作后,您必须使用图形类创建线

您的代码的问题在于您使用的是轻量级和预打包组件的摆动组件,我个人不会使用它们来绘制自定义项目。

以下是一些来源:

让您开始:http ://docs.oracle.com/javase/tutorial/uiswing/painting/index.html

一个工作示例:http ://www.java2s.com/Code/Java/2D-Graphics-GUI/Drawline.htm

于 2012-11-27T00:08:18.593 回答