swing 中如何实现单击一个按钮在同一层次弹出一个txt文本框悬浮在原界面上,有效果图~
2个回答
展开全部
Swing的话,没有现成的控件,只能靠JPopupMenu和JButton组合在一起。
范例代码:
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
/**
*
* @author Jeky
*/
public class PopupDemo extends JFrame implements ActionListener {
public PopupDemo() {
super("Popup Demo");
field = new JTextField(10);
popupButton = new JButton("...");
popupButton.addActionListener(this);
menu = new JPopupMenu();
textArray = new String[]{"aaa", "bbb", "ccc", "ddd"};
for (String s : textArray) {
JMenuItem item = new JMenuItem(s);
item.addActionListener(this);
menu.add(item);
}
this.setLayout(new FlowLayout());
this.add(new JLabel("Text:"));
this.add(field);
this.add(popupButton);
this.pack();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == popupButton) {
menu.show(popupButton, 0, popupButton.getHeight());
} else {
JMenuItem item = (JMenuItem) e.getSource();
field.setText(item.getText());
}
}
public static void main(String[] args) {
new PopupDemo().setVisible(true);
}
private String[] textArray;
private JTextField field;
private JButton popupButton;
private JPopupMenu menu;
}
范例代码:
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
/**
*
* @author Jeky
*/
public class PopupDemo extends JFrame implements ActionListener {
public PopupDemo() {
super("Popup Demo");
field = new JTextField(10);
popupButton = new JButton("...");
popupButton.addActionListener(this);
menu = new JPopupMenu();
textArray = new String[]{"aaa", "bbb", "ccc", "ddd"};
for (String s : textArray) {
JMenuItem item = new JMenuItem(s);
item.addActionListener(this);
menu.add(item);
}
this.setLayout(new FlowLayout());
this.add(new JLabel("Text:"));
this.add(field);
this.add(popupButton);
this.pack();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == popupButton) {
menu.show(popupButton, 0, popupButton.getHeight());
} else {
JMenuItem item = (JMenuItem) e.getSource();
field.setText(item.getText());
}
}
public static void main(String[] args) {
new PopupDemo().setVisible(true);
}
private String[] textArray;
private JTextField field;
private JButton popupButton;
private JPopupMenu menu;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询