sam ak
sam ak

Reputation: 11

Inheriting classes in JButton

Hi guyz i have a prob in writing java code for my project as am unable to tackle that, i want my "Categories" button to perform action like it should show bread class in it but am unable to inherit it and put a pic on it so can anyone here just tell me whats the problem in it.. here is the code:

   JButton b1  = new JButton("Categories");
   b1.setSize(120,25);
   b1.setLocation(130,650);
   b1.setBackground(Color.LIGHT_GRAY) ;
   b1.addActionListener(new AL());
   f.add(b1);
   public class AL implements ActionListener{

     public void actionPerformed(ActionEvent ae){
       JFrame f3 = new JFrame("Delicious Bakery");
       f3.setVisible(true);
       f3.setSize(400,200);

       f3.add(Bread);

Now here is the Bread class:

  public class Bread extends AL implements ActionListener
{

 Bread() 
 {         

    ImageIcon BreadImage = new ImageIcon("C:\\Users\\Baba\\Downloads\\Documents\\Bread1.jpg");
    JButton Bread = new JButton("Bread",BreadImage);
    Bread.setSize(128,96);


}}

Upvotes: 0

Views: 525

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

You appear to be making several basic mistakes including what looks to be trying to add a class that implements ActionListener to your GUI as if it were a button, but it's not. This suggests that you'd greatly benefit from first reading through the JButton Tutorial and the ActionListener Tutorial.

Note that if this were my project, I'd use AbstractActions a concept that is sort of like an "ActionListener on steroids". You would set your JButton with this Action and in doing so, gain the button its name text, its icon and its ActionListener behavior.


Some notes on your code:

JButton b1  = new JButton("Categories"); // (1)
b1.setSize(120,25); // (2)
b1.setLocation(130,650); // (3)
b1.setBackground(Color.LIGHT_GRAY) ;
b1.addActionListener(new AL()); // (4)
f.add(b1); // (5)
  1. You here create a JButton with a String name text
  2. Here you try to set absolute size, something that we don't recommend as doing this, and using null layouts leads to rigid hard to improve and debug programs
  3. Same for setting locations
  4. You appear to be adding an ActionListener OK
  5. And then add your button to a container (the JFrame perhaps)?


public class AL implements ActionListener{  // (6)
    public void actionPerformed(ActionEvent ae){
        JFrame f3 = new JFrame("Delicious Bakery"); // (7)
        f3.setVisible(true);  // (8)
        f3.setSize(400,200); // (9)
        f3.add(Bread);   // (10)
  1. OK, so the AL class implements ActionListener and has an actionPerformed method, so far so good
  2. OK, so inside it you create a new JFrame, a bit unusual since most GUI's have only one JFrame
  3. You're calling setVisible(true) on the JFrame before adding components -- not code, since this may sometimes not allow the JFrame to fully render components added after this setVisible was called
  4. Same notes as previous about setting sizes
  5. Now you add Bread to the JFrame. But Bread looks to not be a component but rather only an ActionListener. This line should not compile.


public class Bread extends AL implements ActionListener { // (11)

    Bread() {    
        // (12)
        ImageIcon BreadImage = new ImageIcon("C:\\Users\\Baba\\Downloads\\Documents\\Bread1.jpg");
        JButton Bread = new JButton("Bread",BreadImage); // (13)
        Bread.setSize(128,96);  // (14)
    }
}
  1. Your Bread class extends AL but also implements ActionListener which is redundant since AL already implements ActionListener.
  2. You are creating an image icon using a file and an absolute path, a slight no-no. Better to use resources and absolute paths
  3. OK you create a new JButton, but you give it the same name as the non-JButton class -- very confusing. Simply don't do this. Ever. Name your fields with unique names, and obey Java naming issues.
  4. Same issue regarding setting sizes.

For example:

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.*;

public class TestBread extends JPanel {
    // String to url for bread image
    private static final String BREAD_IMG_PATH = "http://findicons.com/files/icons/339/"
            + "coffee_break/128/sliced_bread.png";
    // preferred size of jpanel
    private static final int PREF_W = 400;
    private static final int PREF_H = 300;
    private BreadAction breadAction; // our abstract action
    private JButton breadButton; // our jbutton

    public TestBread() {
        Icon breadIcon = null;
        try {
            // get image and put into Icon
            URL breadUrl = new URL(BREAD_IMG_PATH);
            BufferedImage breadImg = ImageIO.read(breadUrl);
            breadIcon = new ImageIcon(breadImg);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }

        breadAction = new BreadAction("Bread", KeyEvent.VK_B, breadIcon); // create Action
        breadButton = new JButton(breadAction); // create button with Action
        breadButton.setVerticalTextPosition(AbstractButton.BOTTOM); // position text
        breadButton.setHorizontalTextPosition(SwingConstants.CENTER);

        add(breadButton);
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    private static void createAndShowGui() {
        TestBread mainPanel = new TestBread();

        JFrame frame = new JFrame("TestBread");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

Our AbstractAction or "super" ActionListener

@SuppressWarnings("serial")
class BreadAction extends AbstractAction {
    public BreadAction(String name, int mnemonic, Icon icon) {
        super(name);
        putValue(MNEMONIC_KEY, mnemonic);
        putValue(LARGE_ICON_KEY, icon);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("bread pressed");
    }
}

Upvotes: 4

Related Questions