单击按钮时如何定义Java中选项卡的操作

我有一个名为addAlbum的JButton,并希望它在单击时启动一个选项卡.所以我补充说:

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

但我不知道在哪里定义选项卡中发生的事情.现在我有一个addAlbumPage定义,因为我以前打开过页面,但现在我认为标签更清晰.

最佳答案 你可以创建一个面板&使用以下语法将其添加到您的选项卡

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.

现在,您必须根据上述语法调整代码

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"); 
}

在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");
        }
    }
}
点赞