Jython-dialogs

提供:Dev Guides
移動先:案内検索

Jython-ダイアログ

Dialogオブジェクトは、ユーザーが操作するベースウィンドウの上に表示されるウィンドウです。 この章では、swingライブラリで定義された事前設定ダイアログを確認します。 それらは MessageDialog、ConfirmDialog および InputDialog です。 これらは、JOptionPaneクラスの静的メソッドのために利用可能です。

次の例では、[ファイル]メニューに、上記の3つのダイアログに対応する3つのJMenuアイテムがあります。それぞれが OnClick イベントハンドラーを実行します。

file = JMenu("File")
msgbtn = JMenuItem("Message",actionPerformed = OnClick)
conbtn = JMenuItem("Confirm",actionPerformed = OnClick)
inputbtn = JMenuItem("Input",actionPerformed = OnClick)
file.add(msgbtn)
file.add(conbtn)
file.add(inputbtn)

OnClick()ハンドラー関数は、メニュー項目ボタンのキャプションを取得し、それぞれのshowXXXDialog()メソッドを呼び出します。

def OnClick(event):
   str = event.getActionCommand()
   if str == 'Message':
      JOptionPane.showMessageDialog(frame,"this is a sample message dialog")
   if str == "Input":
      x = JOptionPane.showInputDialog(frame,"Enter your name")
      txt.setText(x)
   if str == "Confirm":
      s = JOptionPane.showConfirmDialog (frame, "Do you want to continue?")
      if s == JOptionPane.YES_OPTION:
         txt.setText("YES")
      if s == JOptionPane.NO_OPTION:
         txt.setText("NO")
      if s == JOptionPane.CANCEL_OPTION:
         txt.setText("CANCEL")

メニューからメッセージオプションを選択すると、メッセージがポップアップ表示されます。 入力オプションをクリックすると、入力を求めるダイアログが表示されます。 入力テキストは、JFrameウィンドウのテキストボックスに表示されます。 [確認]オプションを選択すると、[はい]、[いいえ]、[キャンセル]の3つのボタンを含むダイアログが表示されます。 ユーザーの選択はテキストボックスに記録されます。

コード全体を以下に示します-

from javax.swing import JFrame, JMenuBar, JMenu, JMenuItem, JTextField
from java.awt import BorderLayout
from javax.swing import JOptionPane
frame = JFrame("Dialog example")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setLocation(100,100)
frame.setSize(400,300)
frame.setLayout(BorderLayout())

def OnClick(event):
   str = event.getActionCommand()
   if str == 'Message':
      JOptionPane.showMessageDialog(frame,"this is a sample message dialog")
   if str == "Input":
      x = JOptionPane.showInputDialog(frame,"Enter your name")
      txt.setText(x)
   if str == "Confirm":
      s = JOptionPane.showConfirmDialog (frame, "Do you want to continue?")
      if s == JOptionPane.YES_OPTION:
         txt.setText("YES")
      if s == JOptionPane.NO_OPTION:
         txt.setText("NO")
      if s == JOptionPane.CANCEL_OPTION:
         txt.setText("CANCEL")

bar = JMenuBar()
frame.setJMenuBar(bar)

file = JMenu("File")
msgbtn = JMenuItem("Message",actionPerformed = OnClick)
conbtn = JMenuItem("Confirm",actionPerformed = OnClick)
inputbtn = JMenuItem("Input",actionPerformed = OnClick)
file.add(msgbtn)
file.add(conbtn)
file.add(inputbtn)
bar.add(file)
txt = JTextField(10)
frame.add(txt, BorderLayout.SOUTH)
frame.setVisible(True)

上記のスクリプトが実行されると、次のウィンドウがメニューの3つのオプションとともに表示されます-

ダイアログ

メッセージボックス

メッセージボックス

入力ボックス

入力ボックス

確認ダイアログ

確認ダイアログ