是的,我认为通过在组件上使用 .getComponents()
会相对简单,它将返回 JOptionPane
的 JPanel
他们通过使用 JPanel
再次使用该方法来检索 JButton
,但是我遇到了困难。
我想在 JOptionPane
按钮上使用鼠标监听器,以便可以在鼠标悬停时更改按钮的颜色。有没有更简单的方法来实现这一目标?
这是我到目前为止的类(class)..
package rsapp.gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
public class RSJPaneComponent extends JOptionPane {
/**
*
*/
private static final long serialVersionUID = 13453253L;
private JOptionPane j=this;
final Color WHITE = Color.WHITE;
public RSJPaneComponent(){
UIManager.put("OptionPane.background",WHITE);
UIManager.put("Panel.background",WHITE);
UIManager.put("Button.background",WHITE);
UIManager.put("Button.foreground",new Color(85,153,187));
UIManager.put("activeCaption", WHITE);
}
protected String initJPaneInput(final JFrame f, final String message){
return j.showInputDialog(f,message);
}
public int generateDialog(int error_code, String title_message, String message, final JFrame f){
return JOptionPane.showConfirmDialog(
f,
message,
"Error "+error_code+": "+title_message,
JOptionPane.YES_NO_OPTION);
}
}
最佳答案
Is there a simpler way of achieving this?
使用JDialog
。长期的经验告诉我,虽然 JOptionPane
是一个功能强大且方便的组件,但一旦需要自定义它,您最好只使用 JDialog
。
代码
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
class CustomDialog {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
JFrame frame = new JFrame("Show Custom Dialog");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setLocationRelativeTo(null);
final JDialog dialog = new JDialog(frame, "Dialog", true);
JPanel mainGui = new JPanel(new BorderLayout());
mainGui.setBorder(new EmptyBorder(20,20,20,20));
mainGui.add( new JLabel("Contents go here"), BorderLayout.CENTER );
JPanel buttonPanel = new JPanel(new FlowLayout());
mainGui.add(buttonPanel, BorderLayout.SOUTH);
JButton close = new JButton("Close");
close.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae) {
dialog.setVisible(false);
}
} );
buttonPanel.add(close);
frame.setVisible(true);
dialog.setContentPane(mainGui);
dialog.pack();
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
<小时/>
屏幕截图
<小时/>
请注意,此示例尚未将所有功能内置到 JOptionPane
中。
例如,如果打开 JOptionPane
并且用户按转义键,则对话框将被关闭。您可以使用 KeyListener
或 ActionMap
添加该功能。
关于java - 访问 JOption Pane 的按钮以向其中添加 MouseListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5689773/