簡體   English   中英

如何在 JOptionPane 選項對話框中使用 JSlider(或其他 JComponent)?

[英]How can I use a JSlider (or other JComponent) in a JOptionPane option dialog?

我有一個 UI,我想在其中顯示一個帶有滑塊和消息的彈出窗口,並讓用戶能夠在選擇一個值(或不選擇)后單擊 OK 或 Cancel。 JOptionPane 有各種顯示方法,它們看起來很有用,但我無法找到很多關於讓它們做我想做的事情的方法。

這實際上是一個我不得不尋找答案的問題,我將在下面提供。 我希望它對其他人有用。

我能夠找到的示例具有示例的標准缺陷:它們與我想告訴我的如何做到這一點不夠接近,並且沒有足夠解釋事情是如何自己改變它們的。 我終於遇到了一個教程,該教程解釋了對話框中的“消息”可以是組件,而 JOptionPane 代碼將呈現它們。 此示例使用 JSlider,我假設也可以使用其他 JComponent。

該文檔還討論了如果您想“直接顯示對話框”該怎么做,但我從來沒有弄清楚他們的意思。

在弄清楚以下內容之前,我偶然發現了各種形式的 JOptionPane 方法:

/**
 * display the dialog for entering the number of spots to move the first
 * marble chosen after a 7 is played. Returns 0 if the user cancelled this
 * operation.
 */
@Override
public int getMoveCount()
{
    int moveCount = 0;

    JSlider slider = createSlider();
    JPanel sliderPanel = createSliderPanel("myMessage", slider);
    String title = "myTitle"; 
    int dialogResponse = JOptionPane.showOptionDialog
            (this,                  // I'm within a JFrame here
             sliderPanel,
             title,
             JOptionPane.OK_CANCEL_OPTION,
             JOptionPane.QUESTION_MESSAGE,
             null, null, null
            );
    if (JOptionPane.OK_OPTION == dialogResponse) 
         { moveCount = slider.getValue(); }
    else { moveCount = 0; } // works for cancel button, red 'x', and keyboard escape key

    return moveCount;
}

private JSlider createSlider()
{
    JSlider slider = new JSlider(1,7);
    slider.setMajorTickSpacing(1);
    slider.setPaintTicks(true);
    slider.setPaintLabels(true);
    slider.setValue(7);                // default to 7

    return slider;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM