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

📄 listapplet2.java

📁 Java the UML Way 书中所有源码
💻 JAVA
字号:
/*
 * ListApplet2.java  E.L. 2001-08-22
 *
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class ListApplet2 extends JApplet {
  private DefaultListModel data = new DefaultListModel();
  private JList list = new JList(data);

  public void init() {
    Container guiContainer = getContentPane();
    guiContainer.add(new TextPanel(), BorderLayout.NORTH);
    guiContainer.add(new ListPanel(), BorderLayout.CENTER);
    guiContainer.add(new JButton(), BorderLayout.SOUTH);  // a little space
  }

  private class TextPanel extends JPanel {
    public TextPanel() {
      setLayout(new GridLayout(4, 1, 5, 5));
      add(new JLabel(" "));  // a little space
      add(new JLabel("Clicking 'New name' gives you a dialog to add a new name, "));
      add(new JLabel("clicking on an existing name removes this name from the list."));
      add(new JLabel(" "));  // a little space
    }
  }

  private class ListPanel extends JPanel {
    public ListPanel() {
      /* It's difficult to control the list width. We cheat a little...*/
      setLayout(new BorderLayout());
      add(new JButton(), BorderLayout.WEST);  // fills up on the left side...
      data.addElement("New name");
      list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      JScrollPane scrollPaneWithList = new JScrollPane(list);
      add(scrollPaneWithList, BorderLayout.CENTER);
      list.addListSelectionListener(new ListListener());
      add(new JButton(), BorderLayout.EAST);  // ...and on the right side
    }
  }

  private class ListListener implements ListSelectionListener {
    public void valueChanged(ListSelectionEvent event) {
      /* All messages except the last shall be ignored */
      if (!list.getValueIsAdjusting()) {
        int selection = list.getSelectedIndex();
        if (selection >= 0) {
          list.clearSelection();
          if (selection == 0) {  // 'New name' is selected
            String newName = JOptionPane.showInputDialog("Enter a new name: ");
            if (newName != null) data.addElement(newName);
          }
          else {  // removes an existing name
            String nameToBeRemoved = (String) data.get(selection);
            data.remove(selection);
            JOptionPane.showMessageDialog(null, "Now " + nameToBeRemoved +
              " is removed from the list.");
          }
        }
      }
    }
  }
}

⌨️ 快捷键说明

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