【问题标题】:how to display only button with out jframe or jpanel visible?如何仅显示不可见 jframe 或 jpanel 的按钮?
【发布时间】:2014-03-25 04:21:14
【问题描述】:

下面的示例将显示一个带有 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);
}

【问题讨论】:

  • 无框 -> 无按钮
  • +1 哦..那么人们在图像(启动画面、.jpg 等)上显示按钮的常见做法是什么?

标签: java swing jframe jbutton


【解决方案1】:

根据你的意思,“没有 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 下工作,但我没有在这里发布

【讨论】:

  • 是的,我支持这个答案。在几分钟内评估你的答案
猜你喜欢
  • 2015-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-24
  • 1970-01-01
  • 2019-08-05
相关资源
最近更新 更多