Цвет фона JOptionPane - PullRequest
       32

Цвет фона JOptionPane

0 голосов
/ 16 апреля 2020

Вот JOptionPane, который я пробовал

Вот код, который я даже пытался использовать, используя свойство Panel.background UIManager, но проблема в том, что он меняет фон всех Панель, которую я использовал в своем проекте.

msgLabel.setFont(StoreAction.STORE_FONT);
JPanel dialogPanel = new JPanel();
dialogPanel.setBackground(Color.lightGray);
dialogPanel.add(msgLabel);
JOptionPane.showOptionDialog(null, dialogPanel, moduleTitle, JOptionPane.NO_OPTION, msgType, null, StoreGUIConstants.OPTIONS, StoreGUIConstants.OPTIONS[0]);```

Ответы [ 2 ]

0 голосов
/ 17 апреля 2020

Я пробовал так много вещей. ( решение aterai ) спасибо aterai за хорошее решение. Он отлично работает для фона. Но все же у меня есть некоторые требования, чтобы выполнить это, я использовал другой подход. в котором я могу изменить все отображаемые на JoptionPane.

Для одного варианта. (Диалог сообщений)

public static void messagePane(Component parentComponent, String msg, String moduleTitle, int msgType) {

    JDialog dialog;
    JPanel panel = new JPanel();
    panel.setBackground(new Color(184, 174, 245));
    JDialog.setDefaultLookAndFeelDecorated(true);
    UIManager.put("OptionPane.background", new Color(168, 156, 240));

    GroupLayout groupLayout = new GroupLayout(panel);
    groupLayout.setAutoCreateGaps(true);
    groupLayout.setAutoCreateContainerGaps(true);
    panel.setLayout(groupLayout);

    JLabel label = new JLabel("<html>" + msg.replaceAll("\n", "<br>"));
    label.setFont(PANE_FONT);
    ImageIcon image = getImageIcon(msgType);

    label.setIcon(image);
    MyButton button = new MyButton("OK");
    button.setFont(PANE_BTN_FONT);

    button.setBackground(new Color(50, 79, 107));
    button.setHoverColor(new Color(147, 170, 191));
    button.setPressedColor(new Color(255, 255, 255));

    button.setMaximumSize(new Dimension(60, 40));

    groupLayout.setHorizontalGroup(groupLayout.createSequentialGroup()
            .addGroup(groupLayout.createParallelGroup(Alignment.CENTER).addComponent(label).addComponent(button)));

    groupLayout.setVerticalGroup(groupLayout.createSequentialGroup()
            .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(label))
            .addGroup(groupLayout.createParallelGroup(Alignment.CENTER).addComponent(button)));

    JOptionPane optionPane = new JOptionPane(panel, JOptionPane.PLAIN_MESSAGE, JOptionPane.NO_OPTION, null,
            new Object[] {}, null);

    dialog = optionPane.createDialog(moduleTitle);
    dialog.setBackground(new Color(29, 83, 99));
    button.addActionListener(e -> dialog.dispose());
    dialog.setVisible(true);

}

Для нескольких вариантов. (Диалог параметров)

public static int optionPane(Component parentComponent, String msg, String moduleTitle, Object[] options) {

    JDialog dialog;
    JPanel panel = new JPanel();
    panel.setBackground(new Color(184, 174, 245));
    JDialog.setDefaultLookAndFeelDecorated(true);
    UIManager.put("OptionPane.background", new Color(168, 156, 240));

    GroupLayout groupLayout = new GroupLayout(panel);
    groupLayout.setAutoCreateGaps(true);
    groupLayout.setAutoCreateContainerGaps(true);
    panel.setLayout(groupLayout);

    JLabel label = new JLabel("<html>" + msg.replaceAll("\n", "<br>"));
    label.setFont(PANE_FONT);
    ImageIcon image = getImageIcon(JOptionPane.WARNING_MESSAGE);

    label.setIcon(image);

    ParallelGroup parallelGroup1 = groupLayout.createParallelGroup(Alignment.LEADING);
    SequentialGroup sequentialGroup1 = groupLayout.createSequentialGroup();

    LinkedList<MyButton> btnList = new LinkedList<MyButton>();
    if (options instanceof String[] || options instanceof Integer[]) {
        MyButton button;
        for (Object option : options) {
            button = new MyButton((String) option);
            button.setFont(PANE_BTN_FONT);
            button.setMaximumSize(new Dimension(60, 40));
            button.setBackground(new Color(82, 122, 161));
            button.setHoverColor(new Color(147, 170, 191));
            button.setPressedColor(new Color(255, 255, 255));
            btnList.add(button);
            parallelGroup1.addComponent(button);
            sequentialGroup1.addComponent(button);
        }
    }

    groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.LEADING)
            .addGroup(groupLayout.createSequentialGroup()
                    .addGroup(groupLayout.createParallelGroup(Alignment.CENTER)
                            .addGroup(groupLayout.createSequentialGroup().addComponent(label))
                            .addGroup(sequentialGroup1))));

    groupLayout.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(
            groupLayout.createSequentialGroup().addComponent(label).addGap(15, 20, 25).addGroup(parallelGroup1)));

    JOptionPane optionPane = new JOptionPane(panel, JOptionPane.PLAIN_MESSAGE, JOptionPane.NO_OPTION, null,
            new Object[] {}, null);

    dialog = optionPane.createDialog(moduleTitle);
    dialog.setBackground(new Color(29, 83, 99));

    int i = 0;
    for (MyButton button : btnList) {
        Integer in = new Integer(i);
        button.addActionListener(e -> {
            selected = in;
            dialog.dispose();
        });
        i++;
    }

    dialog.setVisible(true);
    return selected;
}

Вот мое решение image

0 голосов
/ 17 апреля 2020

По умолчанию JOptionPane состоит из JPanel с именами OptionPane.messageArea, OptionPane.realBody, OptionPane.separator, OptionPane.body и OptionPane.buttonArea, поэтому вы можете установить их все на setOpaque(false).

  • Добавьте HierarchyListener к msgLabel, чтобы получить отображаемые события.
  • Используйте метод SwingUtilities.getAncestorOfClass(JOptionPane.class, msgLabel), чтобы получить JOptionPane, который является родителем msgLabel
  • Находит дочерний элемент JPanel s в JOptionPane и устанавливает setOpaque(false)
import java.awt.*;
import java.awt.event.HierarchyEvent;
import java.util.stream.Stream;
import javax.swing.*;

public class OptionPaneBackgroundTest {
  private Component makeUI() {
    UIManager.put("OptionPane.background", Color.LIGHT_GRAY);

    JLabel msgLabel = new JLabel("<html>Do you really want to delete<br>user(1/user) from your system.");
    msgLabel.addHierarchyListener(e -> {
      Component c = e.getComponent();
      if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0 && c.isShowing()) {
        stream(SwingUtilities.getAncestorOfClass(JOptionPane.class, c))
            .filter(JPanel.class::isInstance)
            .map(JPanel.class::cast) // TEST: .peek(cc -> System.out.println(cc.getName()))
            .forEach(pnl -> pnl.setOpaque(false));
      }
    });

    JButton button = new JButton("show");
    button.addActionListener(e -> JOptionPane.showMessageDialog(
        button.getRootPane(), msgLabel, "Remove User", JOptionPane.WARNING_MESSAGE));

    JPanel p = new JPanel(new GridBagLayout());
    p.add(button);
    return p;
  }

  private static Stream<Component> stream(Container parent) {
    return Stream.of(parent.getComponents())
        .filter(Container.class::isInstance)
        .map(c -> stream((Container) c))
        .reduce(Stream.of(parent), Stream::concat);
  }

  public static void main(String[] args) {
    EventQueue.invokeLater(() -> {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(new OptionPaneBackgroundTest().makeUI());
      f.setSize(320, 240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}
...