2012-12-17 156 views
1

除了標籤之外,你如何在按鈕上創建帶有圖片的JOptionPane?例如,如果我想要確認按鈕上的複選標記和取消按鈕上的x圖標?這可能沒有創建整個對話從頭開始作爲JFrame/JPanel?JOptionPane圖像在按鈕上?

回答

2

我找到了一個稍微混亂的尋找解決方案上java 2 schools,似乎實際上是通過和動作偵聽器工作,響應按鈕點擊:

JFrame frame = new JFrame(); 
    JOptionPane optionPane = new JOptionPane(); 
    optionPane.setMessage("I got an icon and a text label"); 
    optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE); 
    Icon icon = new ImageIcon("yourFile.gif"); 
    JButton jButton = getButton(optionPane, "OK", icon); 
    optionPane.setOptions(new Object[] { jButton }); 
    JDialog dialog = optionPane.createDialog(frame, "Icon/Text Button"); 
    dialog.setVisible(true); 

    } 

    public static JButton getButton(final JOptionPane optionPane, String text, Icon icon) { 
    final JButton button = new JButton(text, icon); 
    ActionListener actionListener = new ActionListener() { 
     public void actionPerformed(ActionEvent actionEvent) { 
     // Return current text label, instead of argument to method 
     optionPane.setValue(button.getText()); 
     System.out.println(button.getText()); 
     } 
    }; 
    button.addActionListener(actionListener); 
    return button; 
    } 
+1

一旦你開始自定義'JOptionPane'實例,就像你發現的那樣,它變得混亂。通常情況下,最好是側面使用「JDialog」。 +1來尋找解決方案,但也可以查看'Action' API來代替'ActionListener'。 –

5

JOptionPane.showOptionDialog()有一個參數options這是一個數組Component s。 你可以通過它的自定義按鈕數組:

JOptionPane.showOptionDialog(parent, question, title, 
    JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE 
    new Component[]{ new JButton("OK", myIcon), 
        new JButton("cancel", myOtherIcon) 
        } 
); 

JOptionPane文檔:

選項 - 顯示可能的選擇,用戶 可以使對象的數組;如果對象是組件,它們會被正確渲染;

或者,您可以繼承JOptionPane,並直接更改組件及其佈局。

+0

對於這似乎是正確的軌道解決方案的大部分但是,這對我來說並不完全適合。看起來好像有幾個參數需要指定(也許不是所有的Java版本都是相同的?我使用的是Java 7),但我沒有在按下OK或Cancel時添加空值。自定義按鈕是否需要動作偵聽器觸發「ok」動作? –