gpt4 book ai didi

java - 如何在 JFrame 中创建弹出 JPanel

转载 作者:行者123 更新时间:2023-12-01 23:33:00 26 4
gpt4 key购买 nike

我想帮助某人。我想创建一个 JPanel,当我单击按钮时会弹出,它必须出现在单击按钮的位置,并且不能影响其他组件。 JDateChooser 就是一个例子,当您单击该按钮时,日历就会出现在此处,但是当您单击其他任何位置时,该面板就会消失。我想要的是在该面板弹出时在该面板中放置一个名称列表。它与 JPopupmenu 类似,只是当您单击其他任何位置时它必须消失。

最佳答案

我不确定你在做什么,但它似乎对我来说很好......

enter image description here

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ButtonPopup {

public static void main(String[] args) {
new ButtonPopup();
}

public ButtonPopup() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

public TestPane() {
setLayout(new GridBagLayout());

final JPopupMenu popup = new JPopupMenu();
DefaultListModel<String> model = new DefaultListModel<>();
model.addElement("Item 1");
model.addElement("Item 2");
model.addElement("Item 3");
model.addElement("Item 4");
model.addElement("Item 5");
JList list = new JList(model);
popup.setLayout(new BorderLayout());
popup.add(new JScrollPane(list));

final JButton button = new JButton("Pop");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Dimension size = popup.getPreferredSize();
int x = (button.getWidth() - size.width) / 2;
int y = button.getHeight();
popup.show(button, x, y);
}
});

list.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
popup.setVisible(false);
}
});

add(button);
}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}

protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.dispose();
}
}
}

关于java - 如何在 JFrame 中创建弹出 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19064358/

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