⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 exercise15_3.java

📁 Introduction to java programming 一书中所有编程练习部分的源码
💻 JAVA
字号:
// Exercise15_3.java: Demonstrate array out of bound exception
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Exercise15_3 extends JFrame implements ActionListener {
  private JTextField jtfElement, jtfIndex;
  private JButton jbtShowElement = new JButton("Show Element");
  private int[] data = new int[100];

  public static void main(String[] args) {
    Exercise15_3 frame = new Exercise15_3();
    frame.pack();
    frame.setTitle("Exercise15_3: Show Bounds Error");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }

  public Exercise15_3() {
    // Initialize array
    for (int i = 0; i < 100; i++)
      data[i] = (int)(Math.random() * 10000);

    // Panel p to hold index and element of the array
    JPanel p = new JPanel();
    p.setLayout(new GridLayout(2, 2));
    p.add(new Label("Array Index"));
    p.add(jtfIndex = new JTextField(3));
    p.add(new Label("Array Element"));
    p.add(jtfElement = new JTextField(10));
    jtfElement.setEditable(false);

    // Add p and the button to the frame
    getContentPane().add(p, BorderLayout.CENTER);
    getContentPane().add(jbtShowElement, BorderLayout.SOUTH);

    // Register listener
    jbtShowElement.addActionListener(this);
  }

  // Handle ActionEvent
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == jbtShowElement) {
      int index = new Integer(jtfIndex.getText()).intValue();
      try {
        jtfElement.setText("" + data[index]);
      }
      catch (IndexOutOfBoundsException ex) {
        jtfElement.setText("Out of Bound");
      }
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -