今天在課堂上,我們整理了一個計算兩點之間距離的基本GUI。教師和我的同學都不知道爲什麼這個GUI不會處理。給我們的代碼是一個框架,我們只是編輯舊的代碼來開發這個。我將我的作品與另外兩個學生的作品進行了比較,他們的作品雖然我的作品沒有。爲什麼這個JAVA GUI過程不會超過第一個條目?
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Graphics;
import java.text.DecimalFormat;
import java.awt.Color;
import java.awt.Font;
import java.lang.Math;
public class D2 extends JFrame
{
//****************************************
//** GUI Structure
//** Title: Holston Middle School
//** Weight prompt (jlabel, jtext)
//** planet pulldown
//** Weight on planet (jlabel, jtext)
//** calculate button
//****************************************
public JTextField entry1, entry2, entry3, entry4, output1;
public JLabel label1, label2, label3, label4, label5;
public JButton CalculateButton;
public String mtitle, cmessage;
public D2()
{
setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));
label1 = new JLabel("x1");
add(label1);
entry1 = new JTextField(8);
add(entry1);
setEnabled(true);
setVisible(true);
label2 = new JLabel("x2");
add(label2);
entry2 = new JTextField(8);
add(entry2);
setEnabled(true);
setVisible(true);
label3 = new JLabel("y1");
add(label3);
entry3 = new JTextField(8);
add(entry3);
setEnabled(true);
setVisible(true);
label4 = new JLabel("y2");
add(label4);
entry4 = new JTextField(8);
add(entry4);
setEnabled(true);
setVisible(true);
label5 = new JLabel("Distance");
add(label5);
output1 = new JTextField(8);
add(output1);
setEnabled(false);
setVisible(true);
CalculateButton = new JButton("Calculate");
add(CalculateButton);
CalculateButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
String entry1string = entry1.getText();
Double e1value = Double.valueOf(entry1string);
String entry2string = entry2.getText();
Double e2value = Double.valueOf(entry2string);
String entry3string = entry3.getText();
Double e3value = Double.valueOf(entry3string);
String entry4string = entry4.getText();
Double e4value = Double.valueOf(entry4string);
String wmessage = "You selected ";
String wtitle = "Pop Up Box";
if (true) JOptionPane.showMessageDialog(null, wmessage, wtitle, JOptionPane.PLAIN_MESSAGE);
double distance = (Math.pow((e1value - e2value), 2) + Math.pow((e3value - e4value), 2));
DecimalFormat fmt = new DecimalFormat("####.##");
String outstring = fmt.format(distance);
output1.setText("");
output1.setText(outstring);
}//** actionPerformed
}); //** Action Listener
} //** D2 constructor
public static void main(String[] args)
{
D2 frame = new D2();
frame.setTitle("Distance Calculator");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 200);
frame.setBackground(Color.CYAN);
frame.getContentPane().setBackground(Color.lightGray);
frame.setVisible(true);
} //** main
} //** class
插入打印語句並將label1的值設置爲其他值將導致GUI不變。任何幫助?
什麼是不工作?什麼是預期的輸出? – user3437460