如何将JButton合并到图形中?

时间:2012-04-05 18:33:40

标签: java swing user-interface graphics jbutton

我正在尝试编写棋盘游戏RISK的在线版本。我想把JButton放在电路板上。所以基本上我想在一些图像上面放置JButton,但是我无法让它工作。这是我的代码:

 public void main(String[] args){
    JFrame frame = new JFrame("RISK");
    frame.setSize(800, 600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    JPanel panel = new JPanel();
    panel.setLayout(null);
    frame.add(panel);
    JButton button = new JButton("test");
    button.setBounds(100, 100, 150, 150);
    panel.add(button);

    frame.setVisible(true);
    frame.add(new graphics());
 }

 public void paintComponent(Graphics g) {
    super.paintComponent(g);
    try{
      BufferedImage board = ImageIO.read(new File("board.jpg"));
    }catch(IOException e){}
    g.drawImage(board, 0, 0, null);
 }

非常感谢您提前。   - 你的答案不需要参考这个特定的代码,只是图形和JButton的一般例子会很棒!

2 个答案:

答案 0 :(得分:3)

如果愿意,可以在按钮上添加图像。这是一个示例代码。


BufferedImage myPictur =ImageIO.read(getClass().getResourceAsStream("/resources/shoppingicon.png"));
JButton shoppingButton = new JButton("Shopping",new ImageIcon(myPicture));

答案 1 :(得分:3)

首先,对于特殊网络的在线应用程序,Swing将无法正常工作,因为它是专为桌面应用程序设计的。如果您想要像Web应用程序一样的Swing,那么使用

  • Java Web Start

  • JApplet的

  • GWT

现在为botton包含背景图片使用:

BufferedImage buferedImage;
JButton buttonImage;

buferedImage = ImageIO.read(getClass().getResourceAsStream("button-image-1.jpg")); 
buttonImage = new JButton("Start", new ImageIcon(buferedImage)); 
相关问题