这是一个示例代码。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
public class SidePane extends JPanel {
Color c[] = {Color.RED, Color.CYAN, Color.BLACK, Color.BLUE, Color.YELLOW};
public SidePane() {
setLayout(new BorderLayout(10, 10));
ButtonGroup group = new ButtonGroup();
JToggleButton[] buttons = new JToggleButton[5];
JPanel leftTop = new JPanel(new GridLayout(buttons.length, 1, 10, 10));
leftTop.setOpaque(false);
JPanel left = new JPanel();
left.setOpaque(false);
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JToggleButton(i + "");
group.add(buttons[i]);
leftTop.add(buttons[i]);
buttons[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(SidePane.this, ((JToggleButton)e.getSource()).getText()); // Write whatever you like.
}
});
}
buttons[0].setSelected(true);
left.add(leftTop);
add(left, "East");
setBackground(Color.red);
}
public static void main(String[] args) {
JFrame frame = new JFrame("My Side Pane");
frame.add(new SidePane());
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}