Reputation: 1272
Example below will display a button with jframe window. I want only button visible, how can it be implement?
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);
}
Upvotes: 1
Views: 683
Reputation: 347184
Depending on what you mean by "with out jframe or jpanel visible?" you create a transparent window...
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);
}
});
}
}
If you remove frame.setBackground(new Color(0,0,0,0));
, you will get a frameless window
ps- This works under Java 7+, there is trick to make it work under Java 6, but I've not posted it here
Upvotes: 3