从控制台程序迁移到 GUI 程序需要的不仅仅是更改主要方法。 GUI 程序是事件驱动的。
我所说的事件驱动的意思是,例如,一个按钮被按下,一个事件被触发。作为程序员,您有责任对触发该事件时发生的情况进行编码。
所以我的一些建议。
所以从技术上讲,如果我来回答你的问题,
您可以使用 Java Swing 将控制台应用程序转换为 GUI 应用程序。
- 您正在从控制台获取输入。取而代之的是,您可以使用
JTextFields 或 JTextArea 作为您希望获得的输入。
- 你可以使用一些
JButtons来触发需要的进程
填写 JTextFields 后执行。
- 您可以使用
JTextArea 将您在控制台上写入的内容写入控制台,而不是将您通常编写的内容写入控制台。如果你有系列或句子,你可以使用 JTextArea 的append() 方法。
这是我使用 NetBeans IDE 在 Swing 中创建的代码,
import java.util.Arrays;
public class StackOverflow extends javax.swing.JFrame {
String[] list;
/**
* Creates new form StackOverflow
*/
public StackOverflow() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
mainPanel = new javax.swing.JPanel();
inputTxt = new javax.swing.JTextField();
scrollPane = new javax.swing.JScrollPane();
consoleTxt = new javax.swing.JTextArea();
stdvBtn = new javax.swing.JButton();
modeBtn = new javax.swing.JButton();
medianBtn = new javax.swing.JButton();
meanBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
inputTxt.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
inputTxtKeyReleased(evt);
}
});
consoleTxt.setColumns(20);
consoleTxt.setRows(5);
scrollPane.setViewportView(consoleTxt);
stdvBtn.setText("STDV");
stdvBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stdvBtnActionPerformed(evt);
}
});
modeBtn.setText("Mode");
modeBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
modeBtnActionPerformed(evt);
}
});
medianBtn.setText("Median");
medianBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
medianBtnActionPerformed(evt);
}
});
meanBtn.setText("Mean");
meanBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
meanBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(inputTxt)
.addComponent(scrollPane)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
.addGap(0, 370, Short.MAX_VALUE)
.addComponent(meanBtn)
.addGap(18, 18, 18)
.addComponent(medianBtn)
.addGap(18, 18, 18)
.addComponent(modeBtn)
.addGap(18, 18, 18)
.addComponent(stdvBtn)))
.addContainerGap())
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(inputTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(scrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 78, Short.MAX_VALUE)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(stdvBtn)
.addComponent(modeBtn)
.addComponent(medianBtn)
.addComponent(meanBtn))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
setSize(new java.awt.Dimension(730, 381));
setLocationRelativeTo(null);
}// </editor-fold>
private void inputTxtKeyReleased(java.awt.event.KeyEvent evt) {
list = inputTxt.getText().split(" ");
}
private void meanBtnActionPerformed(java.awt.event.ActionEvent evt) {
int sum = 0;
for (String n : list) {
sum += Integer.parseInt(n);
}
consoleTxt.append("The mean of the data set is " + ((double) sum / list.length) + "\n");
}
private void medianBtnActionPerformed(java.awt.event.ActionEvent evt) {
Arrays.sort(list);
if (list.length % 2 == 0) {
consoleTxt.append("The median of the data set is: " + Double.parseDouble(list[list.length / 2]) + Double.parseDouble(list[list.length / 2 - 1]) / 2 + "\n");
} else {
consoleTxt.append("The median of the data set is: " + list[list.length / 2] + "\n");
}
}
private void modeBtnActionPerformed(java.awt.event.ActionEvent evt) {
int maxNumber = -1;
int maxAppearances = -1;
for (int i = 0; i < list.length; i++) {
int count = 0;
for (int j = 0; j < list.length; j++) {
if (list[i].equals(list[j])) {
count++;
}
}
if (count > maxAppearances) {
maxNumber = Integer.parseInt(list[i]);
maxAppearances = count;
}
count = 0;
}
consoleTxt.append("The mode of the data set: " + maxNumber + "\n");
}
private void stdvBtnActionPerformed(java.awt.event.ActionEvent evt) {
double STDVsum = 0.0, standardDeviation = 0.0;
int length = list.length;
for (String num : list) {
STDVsum += Double.parseDouble(num);
}
double mean = STDVsum / length;
for (String num : list) {
int num_to_Integer = Integer.parseInt(num);
standardDeviation += Math.pow(num_to_Integer - mean, 2);
}
consoleTxt.append("STDV " + Math.sqrt(standardDeviation / length) + "\n");
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(StackOverflow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StackOverflow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StackOverflow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StackOverflow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new StackOverflow().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextArea consoleTxt;
private javax.swing.JTextField inputTxt;
private javax.swing.JPanel mainPanel;
private javax.swing.JButton meanBtn;
private javax.swing.JButton medianBtn;
private javax.swing.JButton modeBtn;
private javax.swing.JScrollPane scrollPane;
private javax.swing.JButton stdvBtn;
// End of variables declaration
}
如果你通过代码,
使用的组件JTextField、JTextArea、JButton、JPanel、
JFrame.
private javax.swing.JTextArea consoleTxt;
private javax.swing.JTextField inputTxt;
private javax.swing.JPanel mainPanel;
private javax.swing.JButton meanBtn;
private javax.swing.JButton medianBtn;
private javax.swing.JButton modeBtn;
private javax.swing.JButton stdvBtn;
使用ActionListeners触发函数。
例如,ActionListener 调用函数(在您的情况下查找平均值)一旦按下平均值按钮,它将触发 meanBtnActionPerformed(evt); 函数。
meanBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
meanBtnActionPerformed(evt);
}
});
meanBtnActionPerformed(evt); 里面的内容。
private void meanBtnActionPerformed(java.awt.event.ActionEvent evt) {
int sum = 0;
for (String n : list) {
sum += Integer.parseInt(n);
}
consoleTxt.append("The mean of the data set is " + ((double) sum / list.length) + "\n");
}
另一个主要的事情是,在您的控制台应用程序中,当您键入数字并输入它时,String[] list 将填充。为此,我使用了KeyListener。当用户按下或释放键盘键时,键事件由具有键盘焦点的组件触发。因此,在您的情况下,当您键入 10 20 30 40 50 时,它会通过调用 inputTxtKeyReleased(evt); 函数将这些数字添加到列表中。
inputTxt.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
inputTxtKeyReleased(evt);
}
});
所以我建议检查代码,尝试一下,阅读 java 文档并从教程中学习。快乐编码!