- Swing 程式設計範例
- 範例 - 主頁
- 範例 - 環境設定
- 範例 - 邊框
- 範例 - 按鈕
- 範例 - 複選框
- 範例 - 組合框
- 範例 - 顏色選取器
- 範例 - 對話方塊
- 範例 - 編輯器窗格
- 範例 - 檔案選取器
- 範例 - 格式化的文字欄位
- 範例 - 框架
- 範例 - 列表
- 範例 - 佈局
- 範例 - 選單
- 範例 - 密碼欄位
- 範例 - 進度條
- 範例 - 滾動窗格
- 範例 - 滑塊
- 範例 - 微調框
- 範例 - 表格
- 範例 - 工具欄
- 範例 - 樹
- Swing 有用資源
- Swing - 快速指南
- Swing - 有用資源
- Swing - 討論
Swing 範例 - 顯示帶有自定義按鈕的確認對話方塊 p>
以下範例展示瞭如何在基於 swing 的應用程式中顯示帶有自定義按鈕文字的確認對話方塊。
我們正在使用以下 API。
JOptionPane - 建立一個標準對話方塊。
JOptionPane.showOptionDialog() - 顯示帶有多個選項的訊息提示。
JOptionPane.YES_NO_OPTION - 獲取“是”和“否”按鈕。
範例
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(final JFrame frame){
JPanel panel = new JPanel();
LayoutManager layout = new FlowLayout();
panel.setLayout(layout);
JButton button = new JButton("Click Me!");
final JLabel label = new JLabel();
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String[] options = {"Yes! Please.", "No! Not now."};
int result = JOptionPane.showOptionDialog(
frame,
"Sure? You want to exit?",
"Swing Tester",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, //no custom icon
options, //button titles
options[0] //default button
);
if(result == JOptionPane.YES_OPTION){
label.setText("You selected: Yes! Please");
}else if (result == JOptionPane.NO_OPTION){
label.setText("You selected: No! Not now.");
}else {
label.setText("None selected");
}
}
});
panel.add(button);
panel.add(label);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
輸出
swingexamples_dialogs.htm
廣告