ラベルに加えてボタンに画像を含むJOptionPaneをどのように作成しますか?たとえば、[OK]ボタンにチェックマークを付け、[キャンセル]ボタンにxアイコンを付けたい場合はどうすればよいですか?これは、ダイアログ全体をJFrame / JPanelとして最初から作成しなくても可能ですか?
3356 次
3 に答える
5
JOptionPane.showOptionDialog()
options
sの配列であるパラメータがありますComponent
。カスタムボタンの配列を渡すことができます。
JOptionPane.showOptionDialog( parent, question, title,
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE
new Component[]{ new JButton("OK", myIcon),
new JButton("cancel", myOtherIcon)
}
);
のドキュメントからJOptionPane
:
options-ユーザーが選択できる可能性のあるオブジェクトを示すオブジェクトの配列。オブジェクトがコンポーネントの場合、適切にレンダリングされます。
または、をサブクラス化JOptionPane
して、コンポーネントとそのレイアウトを直接変更することもできます。
于 2012-12-17T20:43:56.650 に答える
2
私は、実際に機能し、ボタンのクリックスルーとアクションリスナーに応答するように見えるJava2スクールで少し厄介なソリューションを見つけました。
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;
}
于 2012-12-17T21:22:08.700 に答える
1
私も同じ問題を抱えていました。このアクションリスナーで解決:
JButton ok = new JButton("OK");
ok.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Container parent = ok.getParent();
while (parent != null && !(parent instanceof JDialog)) {
parent = parent.getParent();
}
parent.setVisible(false);
}
});
于 2020-08-07T18:40:21.827 に答える