Nicky Mirfallah
Nicky Mirfallah

Reputation: 1054

How to define action of a tab in Java when a button is clicked

I have a JButton called addAlbum and want it to start a tab when clicked. So I added:

private void addAlbumButtonActionPerformed(java.awt.event.ActionEvent evt) {
    new AddAlbumPage().setVisible(true);
    JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.addTab("Add Album", addAlbumButton); 
}

But I don't know where to define what happens in the tab. Right now I have a addAlbumPage defined since I used to open pages before, but now I think tabs are cleaner.

Upvotes: 4

Views: 423

Answers (1)

Raju
Raju

Reputation: 2962

You can create a panel & add it to your tab using below syntax

addTab(String title, Icon icon, Component component, String tip)  

Adds a component and tip represented by a title and/or icon, either of which can be null.

Now, you have to adjust your code according to above syntax

private void addAlbumButtonActionPerformed(java.awt.event.ActionEvent evt) {
    new AddAlbumPage().setVisible(true);
    JTabbedPane tabbedPane = new JTabbedPane();
    ImageIcon icon = createImageIcon("images/middle.gif");
    ExamplePanel panel1 = new ExamplePanel("Album");
    tabbedPane.addTab("New Album", icon,panel1,"New Album"); 
}

Define controls in the ExamplePanel.java

ExamplePanel.java

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class ExamplePanel extends JPanel implements ActionListener{
JButton btn, btn2;
    public ExamplePanel1(String title) {
        setBackground(Color.lightGray);
        setBorder(BorderFactory.createTitledBorder(title));
        btn = new JButton("Ok");
        btn2= new JButton("Cancel");
        setLayout(new FlowLayout());
        add(btn);
        add(btn2);
        btn.addActionListener(this);
        btn2.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
         if(e.getSource()==btn){
        JOptionPane.showMessageDialog(null, "Hi");
        }

        if(e.getSource()==btn2){
        JOptionPane.showConfirmDialog(null, "Hi there");
        }
    }
}

Upvotes: 1

Related Questions