下面的示例将显示带有 jframe 窗口的按钮。我只想让按钮可见,如何实现?
public final void initUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
JButton quitButton = new JButton("Quit");
quitButton.setBounds(50, 60, 80, 30);
quitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
panel.add(quitButton);
setTitle("Quit button");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
最佳答案
根据您所说的“没有 jframe 或 jpanel 可见?”的意思,您可以创建一个透明窗口...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class GhostButton {
public static void main(String[] args) {
new GhostButton();
}
public GhostButton() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JButton ghostButton = new JButton("Boo!");
ghostButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JFrame frame = new JFrame("Testing");
frame.setUndecorated(true);
frame.setBackground(new Color(0,0,0,0));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(ghostButton);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
如果你删除 frame.setBackground(new Color(0,0,0,0));
,你会得到一个无框的窗口
ps- 这在 Java 7+ 下工作,有让它在 Java 6 下工作的技巧,但我没有在这里发布
关于java - 如何在不显示 jframe 或 jpanel 的情况下仅显示按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22625379/