开发者

Adding an image to an exsisting JPanel inside of a JFrame

So, I'm in an AP Computer Science class, and our final project is to make a program that display a bunch of different concepts we have learned. Two of which are displaying images, and adding buttons.

I decided to make just a cheesy decision-based rpg that shows if-else branching. I figured out how to get a menu in that has the start button, and opens an input dialog box. But I can't figure out how to add an image to the same JFrame that the button is located on. You know so it displays the image either above or below the button. I learned how to display images, but the examples are all extended classes that only display an image. I can't figure out how to invoke some sort of draw or bufferedimage method within my existing code or where to put it. Maybe I could make a call to a different class that has the image code in it? Here is what I have so far.

public class Smashing extends JPanel
{

    public static void main(String[] args)
    {

    JFrame frame = new JFrame("Input Dialog Box Frame");
    JButton button = new JButton("Start Nigel's Adventure");      
    button.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent ae)
      {
        String str = JOptionPane.showInputDialog( "What should Nigel do? :  Enter a cardinal direction ex. n");
        if (str.equals("n"))
        {
          JOptionPane.showMessageDialog(null, "Nigel comes upon a tree ");
          String str2 = JOptionPane.showInputDialog( "What should Nigel do? :");
          if (str2.equals("climb"))
          JOptionPane.showMessageDialog(null, "Nigel climb开发者_运维技巧s up the tree ");
          if (str2.equals("s"))
          JOptionPane.showMessageDialog(null, "Nigel returns to the strating position ");
        }

         if (str.equals("s"))
        {
            JOptionPane.showMessageDialog(null, "Nigel comes upon boulder ");
            String str3 = JOptionPane.showInputDialog( "What should Nigel do? :");
        }



        } 

    });
    JPanel panel = new JPanel();
    panel.add(button);
    frame.add(panel);
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}

And I imported a bunch of packages already, I just didn't include that in the code, oh and this is also a regular application class, not an applet. Any help is greatly appreciated.


You can use a JLabel to store your image read from file or from a buffer:

ImageIcon image = new ImageIcon("path_to_image");
//or
ImageIcon image = new ImageIcon (data) //where data is byte[] data

then create your JLabel :

JLabel label = new JLabel(image) 

To decide how to position your image add your JLabel to a JPanel with the desired LayoutManager.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜