3

我想在我的非 RCP SWT 应用程序中添加自定义按钮标题。

    MessageBox messageBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.ABORT | SWT.RETRY | SWT.IGNORE);
messageBox.setText("Warning");
messageBox.setMessage("Save the changes before exiting?");
 int buttonID = messageBox.open();
 switch(buttonID) {
   case SWT.YES:
  // saves changes ...
case SWT.NO:
 // exits here ...
  break;
 case SWT.CANCEL:
// does nothing ...
 }
                                    System.out.println(buttonID);

}

它工作正常,但我的按钮标题是“中止”、“重试”、“忽略”我想要自定义按钮标题,如“覆盖”、“重命名”、“取消”。怎么做?
请帮忙。

** * 编辑 * ** * ** * *

我也试过

MessageDialog dialog = new MessageDialog(null, "Dangerous Activity", null,
                                                    "Are you sure you want to delete?", MessageDialog.CONFIRM,
                                                    new String[]{"Preview>", "Delete", "Cancel"}, 0)
                                    {
                                    protected void buttonPressed(int buttonId) {
                                        setReturnCode(buttonId);
                                        // close(); Call close for Delete or Cancel?
                                    }};

但是 MessageDialog 要求应用程序是 RCP,因此不导入所需的包。帮助。

4

3 回答 3

7

这是一个非常简单的示例,说明如何在 SWT 中自己操作(不过,使用JFaceDialog可以使用更舒适的方法):

public class CustomDialog extends Dialog
{
    private String message = "";
    private Shell shell;

    public CustomDialog(Shell parent)
    {
        // Pass the default styles here
        this(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
        shell = parent;
    }

    public CustomDialog(Shell parent, int style)
    {
        // Let users override the default styles
        super(parent, style);
        shell = parent;
    }

    public String getMessage()
    {
        return message;
    }

    public void setMessage(String message)
    {
        this.message = message;
    }

    public void open()
    {
        shell.setText(getText());
        createContents(shell);
        shell.pack();
        shell.open();
        Display display = getParent().getDisplay();
        while (!shell.isDisposed())
        {
            if (!display.readAndDispatch())
            {
                display.sleep();
            }
        }
    }

    /**
     * Creates the dialog's contents
     * 
     * @param shell
     *            the dialog window
     */
    private void createContents(final Shell shell)
    {
        shell.setLayout(new GridLayout(3, true));

        // Show the message
        Label label = new Label(shell, SWT.NONE);
        label.setText(message);
        GridData data = new GridData();
        data.horizontalSpan = 3;
        label.setLayoutData(data);

        // Display the input box
        Label image = new Label(shell, SWT.NONE);
        image.setImage(shell.getDisplay().getSystemImage(SWT.ICON_ERROR));
        data = new GridData(SWT.FILL, SWT.BEGINNING, true, false);
        data.horizontalSpan = 3;
        image.setLayoutData(data);

        Button preview = new Button(shell, SWT.PUSH);
        preview.setText("Preview");
        data = new GridData(SWT.FILL, SWT.END, true, true);
        preview.setLayoutData(data);
        preview.addSelectionListener(new SelectionAdapter()
        {
            public void widgetSelected(SelectionEvent event)
            {
                System.out.println("Preview");
            }
        });

        Button delete = new Button(shell, SWT.PUSH);
        delete.setText("Delete");
        data = new GridData(SWT.FILL, SWT.END, true, true);
        delete.setLayoutData(data);
        delete.addSelectionListener(new SelectionAdapter()
        {
            public void widgetSelected(SelectionEvent event)
            {
                System.out.println("Delete");
            }
        });

        Button cancel = new Button(shell, SWT.PUSH);
        cancel.setText("Cancel");
        data = new GridData(SWT.FILL, SWT.END, true, true);
        cancel.setLayoutData(data);
        cancel.addSelectionListener(new SelectionAdapter()
        {
            public void widgetSelected(SelectionEvent event)
            {
                shell.close();
            }
        });

        shell.setDefaultButton(preview);
    }

    public static void main(String[] args)
    {
        CustomDialog dialog = new CustomDialog(new Shell());
        dialog.setText("Title");
        dialog.setMessage("Message");

        dialog.open();
    }
}

它看起来像这样:

在此处输入图像描述

于 2013-02-12T15:33:07.613 回答
3

MessageBox不能以这种方式扩展。你最好的选择——当不做RCP 应用程序时——可能是滚动你自己的对话框:-)

但是考虑到这些对话框的简单性质,这​​应该很容易。

于 2013-02-12T13:36:17.303 回答
0

我对此有点晚了,但是如果其他人正在寻找可定制的 MessageBox,那就是。创建一个类,然后将代码复制/粘贴到其中。我要感谢 Baz 给我的起点 :-)

import java.util.ArrayList;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

/**
 * Custom MessageBox which allows custom button captions, such as using language specific text<br>
 * <br>
 * <code><b>
 * int cancelResult = 0;<br>
 * int deleteResult = 1;<br>
 * <br>
 * CustomMessageBox messageBox = new CustomMessageBox( ivShell, CustomMessageBox.ImageCode.QUESTION, "Confirm Delete", "Are you sure you want to delete:\n\n" + key );<br>
 * <br>
 * messageBox.addButton( "Cancel", cancelResult, true );<br>
 * messageBox.addButton( "Delete " + key, deleteResult );<br>
 * <br>
 * if (messageBox.getResult() == deleteResult)<br>
 * &nbsp;&nbsp;remove( key );<br>
 * </b></code>
 */
public class CustomMessageBox extends Dialog
{
    /**
     * Standard SWT icons used in a message box
     */
    public enum ImageCode
    {
    INFORMATION(SWT.ICON_INFORMATION),
    QUESTION(SWT.ICON_QUESTION),
    WARNING(SWT.ICON_WARNING),
    ERROR(SWT.ICON_ERROR);

    private int ivImageCode;

    private ImageCode( int imageCode )
    {
        ivImageCode = imageCode;
    }

    private int getImageCode()
    {
        return ivImageCode;
    }
}

private static final int           FORM_SPACING   = 5;
private static final String        OK_CAPTION     = "Ok";   //$NON-NLS-1$
private static final int           SCREEN_MINIMUM = 20;

private Shell                      ivParentShell;
private Shell                      ivShell;

private Composite                  ivCompositeImage;
private Composite                  ivCompositeMessage;
private Composite                  ivCompositeDummy;
private Composite                  ivCompositeButtons;

private Label                      ivLabelImage;
private Label                      ivLabelMessage;

private Color                      ivMessageForegroundColor;
private Color                      ivMessageBackgroundColor;
private Font                       ivMessageFont;

private ImageCode                  ivImageCode;
private String                     ivTitle;
private String                     ivMessage;
private ArrayList<ButtonParameter> ivButtons;

private int                        ivResult;

/**
 * Create a custom message box. You must {@link #addButton(String, int, boolean)} before calling {@link #getResult()}
 * @param parentShell - the parent shell. The message box will be centered within this shell
 * @param imageCode - the image to be shown in the upper/left corner
 * @param title - the title for the message box
 * @param message - the message shown to the user. You can have newlines in the message
 */
public CustomMessageBox( Shell parentShell, ImageCode imageCode, String title, String message )
{
    super( parentShell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL );

    ivParentShell = parentShell;

    ivImageCode = imageCode;
    ivTitle = title;
    ivMessage = message;

    ivButtons = new ArrayList<>();

    ivMessageForegroundColor = null;
    ivMessageBackgroundColor = null;
    ivMessageFont = null;
}

/**
 * Buttons are created right to left, so add the right-most button first. This will not be the default button
 * @param caption - the caption for the button
 * @param result - the returned result when the button is chosen. Should be unique!
 */
public void addButton( String caption, int result )
{
    addButton( caption, result, false );
}

/**
 * Buttons are created right to left, so add the right-most button first.<br><br>
 * If more than one button is set to be the default or no buttons are set to be the default, then the last one added will actually become the default.
 * @param caption - the caption for the button
 * @param result - the returned result when the button is chosen. Should be unique!
 * @param isDefault - this will be the default button.
 */
public void addButton( String caption, int result, boolean isDefault )
{
    ivButtons.add( new ButtonParameter( caption, result, isDefault ) );
}

/**
 * Set the message foreground color
 * @param foregroundColor
 */
public void setMessageForegroundColor( Color foregroundColor )
{
    ivMessageForegroundColor = foregroundColor;
}

/**
 * Set the message background color
 * @param backgroundColor
 */
public void setMessageBackgroundColor( Color backgroundColor )
{
    ivMessageBackgroundColor = backgroundColor;
}

/**
 * Set the message font
 * @param messageFont
 */
public void setMessageFont( Font messageFont )
{
    ivMessageFont = messageFont;
}

/**
 * Open the window and get the result. If no buttons were added, a stock "Ok" button will be created
 */
public int getResult()
{
    Display display = Display.getDefault();

    // bad programmer, bad
    if (ivButtons.size() == 0)
        addButton( OK_CAPTION, 0, true );

    ivShell = new Shell( SWT.BORDER | SWT.TITLE | SWT.APPLICATION_MODAL );

    createContents( display );

    ivShell.pack();

    ivShell.setLocation( centerOnParent( ivParentShell, ivShell ) );

    ivShell.open();

    while (!ivShell.isDisposed())
    {
        if (!display.readAndDispatch())
        {
            display.sleep();
        }
    }

    return ivResult;
}

/**
 * Centers the message box within the parent shell
 */
private Point centerOnParent( Shell parentShell, Shell childShell )
{
    Rectangle parent = parentShell.getBounds();
    Rectangle child = childShell.getBounds();
    int x = (int) (parent.x + (parent.width - child.width) * 0.5f);
    int y = (int) (parent.y + (parent.height - child.height) * 0.5f);

    // just to keep the left edge on the screen
    if (x < SCREEN_MINIMUM)
        x = SCREEN_MINIMUM;

    // just to keep the top edge on the screen
    if (y < SCREEN_MINIMUM)
        y = SCREEN_MINIMUM;

    return new Point( x, y );
}

/**
 * Creates the contents and places them in the shell
 */
private void createContents( Display display )
{
    FormData formData;
    GridData gridData;
    Button button;
    Button lastButton;

    ivShell.setLayout( new GridLayout( 2, false ) );
    ivShell.setText( ivTitle );

    {
        ivCompositeImage = new Composite( ivShell, SWT.NONE );
        ivCompositeImage.setLayout( new FormLayout() );

        gridData = new GridData();
        gridData.grabExcessHorizontalSpace = true;
        gridData.grabExcessVerticalSpace = true;
        gridData.verticalAlignment = SWT.TOP;
        gridData.horizontalAlignment = SWT.LEFT;
        ivCompositeImage.setLayoutData( gridData );
    }
    {
        ivCompositeMessage = new Composite( ivShell, SWT.NONE );
        ivCompositeMessage.setLayout( new FormLayout() );

        gridData = new GridData();
        gridData.grabExcessHorizontalSpace = true;
        gridData.grabExcessVerticalSpace = true;
        ivCompositeMessage.setLayoutData( gridData );
    }
    {
        ivCompositeDummy = new Composite( ivShell, SWT.NONE );
        ivCompositeDummy.setLayout( new FormLayout() );
    }
    {
        ivCompositeButtons = new Composite( ivShell, SWT.NONE );
        ivCompositeButtons.setLayout( new FormLayout() );

        gridData = new GridData();
        gridData.grabExcessHorizontalSpace = true;
        gridData.grabExcessVerticalSpace = true;
        gridData.horizontalAlignment = SWT.END;
        ivCompositeButtons.setLayoutData( gridData );
    }

    {
        ivLabelImage = new Label( ivCompositeImage, SWT.NONE );

        formData = new FormData();
        formData.top = new FormAttachment( 0, 0 );
        formData.left = new FormAttachment( 0, 0 );
        ivLabelImage.setLayoutData( formData );

        ivLabelImage.setImage( display.getSystemImage( ivImageCode.getImageCode() ) );
    }
    {
        ivLabelMessage = new Label( ivCompositeMessage, SWT.WRAP );

        formData = new FormData();
        formData.top = new FormAttachment( 0, 0 );
        formData.left = new FormAttachment( 0, 0 );
        formData.right = new FormAttachment( 100, 0 );
        formData.bottom = new FormAttachment( 100, 0 );
        ivLabelMessage.setLayoutData( formData );

        // we add a new line to place white-space between the message and the buttons
        // the trailing space is required!
        ivLabelMessage.setText( ivMessage + System.getProperty( "line.separator" ) + " " ); //$NON-NLS-1$ //$NON-NLS-2$

        if (ivMessageForegroundColor != null)
            ivLabelMessage.setForeground( ivMessageForegroundColor );

        if (ivMessageBackgroundColor != null)
            ivLabelMessage.setBackground( ivMessageBackgroundColor );

        if (ivMessageFont != null)
            ivLabelMessage.setFont( ivMessageFont );
    }

    lastButton = null;

    for (ButtonParameter parm : ivButtons)
    {
        button = new Button( ivCompositeButtons, SWT.PUSH );
        formData = new FormData();

        if (lastButton == null)
            formData.right = new FormAttachment( 100, -FORM_SPACING );
        else
            formData.right = new FormAttachment( lastButton, -FORM_SPACING, SWT.LEFT );

        formData.bottom = new FormAttachment( 100, -FORM_SPACING );

        button.setLayoutData( formData );
        button.setText( parm.getCaption() );

        button.addMouseListener( new ButtonMouseListener( parm.getResult() ) );

        lastButton = button;

        if (parm.isDefault())
            ivShell.setDefaultButton( button );
    }

    if (ivShell.getDefaultButton() == null)
        ivShell.setDefaultButton( lastButton );
}

/**
 * Internal class which holds the button parameters. This is created by the {@link  CustomMessageBox#addButton(String, int, boolean)} method
 */
private class ButtonParameter
{
    private String  ivCaption;
    private int     ivResult;
    private boolean ivIsDefault;

    /**
    * Create a button parameter
    * @param caption - the caption for the button
    * @param result - the returned result when the button is chosen
    * @param isDefault - this will be the default button.
    */
    private ButtonParameter( String caption, int result, boolean isDefault )
    {
        super();

        ivCaption = caption;
        ivResult = result;
        ivIsDefault = isDefault;
    }

    private String getCaption()
    {
        return ivCaption;
    }

    private int getResult()
    {
        return ivResult;
    }

    private boolean isDefault()
    {
        return ivIsDefault;
    }
}

/**
 * Mouse listener for the buttons.
 */
private class ButtonMouseListener extends MouseAdapter
{
    private int ivButtonResult;

    /**
     * Creates the listener
     * @param result - The result returned when the button is pressed
     */
    private ButtonMouseListener( int result )
    {
        super();

        ivButtonResult = result;
    }

    @Override
    public void mouseUp( MouseEvent e )
    {
        ivResult = ivButtonResult;

        ivShell.close();
    }
}

}

于 2019-08-22T17:53:46.530 回答