gpt4 book ai didi

java - 修改 JPopupMenu/JMenuItem 外观

转载 作者:行者123 更新时间:2023-12-04 03:39:04 24 4
gpt4 key购买 nike

我正在尝试创建一个具有不同颜色和圆形边框的自定义 JPopupMenu。我尝试了以下代码,但 PopupMenu 的外观没有任何变化。

JButton button = new JButton("Test");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e){
TPopupMenu popup = new TPopupMenu();
JMenuItem item1 = new JMenuItem("Item 1");
JMenuItem item2 = new JMenuItem("Item 2");
popup.add(item1);
popup.add(item2);
}
}

自定义弹出菜单

public class TPopupMenu extends JPopupMenu{

public TPopupMenu(){
super();
super.setOpaque(false);
init();
}

private void init(){
setBackground(Color.green);
}

@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);

g.setColor(Color.pink);

int w = getWidth();
int h = getHeight();
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTILIAS_ON);

g2.fillRoundRect(0,0,w-1, h-1, 10, 10);
g2.drawRoundRect(0,0,w-1, h-1, 10, 10);

g2.setBackground(Color.red);
g2.setColor(Color.green);
}

}

这就是我希望我的圆形弹出菜单看起来像这样:

enter image description here

我是不是在我的 paintComponent 方法中做错了什么?

最佳答案

您的弹出窗口永远不可见,调用 show (Component invoker, int x, int y) 方法来显示 JPopupMenu 类。

Displays the popup menu at the position x,y in the coordinate space of the component invoker...

      JPopupMenu popup = new JPopupMenu();
JMenuItem item = new JMenuItem("Item");
popup.add(item);
popup.show(frame, frame.getWidth()/2, frame.getHeight()/2);

或者您也可以调用 JPopupMenu.setVisible(boolean b) 方法。

参见 JPopupMenu#show , JPopupMenu#setVisible


自定义

对于圆角边框,可以使用new LineBorder(Color.black, 2, true)LineBorder doc

如果你想要大的自定义,我建议你使用/写一个外观。参见 tutorial|uiswing

这是我的测试:

    public class Test {

private static void createAndShowGUI() {
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

JButton button = new JButton("Test");

JPopupMenu popup = new JPopupMenu();
popup.setBorder(new LineBorder(Color.black, 2, true));

{
JMenuItem item = new JMenuItem("Cut");
item.setForeground(Color.ORANGE);
popup.add(item);
}

{
JMenuItem item = new JMenuItem("Copy");
item.setBackground(Color.RED);
popup.add(item);
}

{
JMenuItem item = new JMenuItem("Paste");
popup.add(item);
}

button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
popup.show(frame, frame.getWidth() / 2, frame.getHeight() / 2);
System.out.println("perfome");
}
});

frame.getContentPane().add(button);
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}

}

enter image description here

关于java - 修改 JPopupMenu/JMenuItem 外观,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66382489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com