当使用Java的Swing库来实现一个左右风格的SplitPanel时,可以使用JSplitPane
作为容器,并在左边的面板中放置三个按钮,以及在右边的面板中显示图片。以下是一个示例代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SplitPanelExample extends JFrame {
private JLabel imageLabel;
public SplitPanelExample() {
setTitle("SplitPanel Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(600, 400));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
splitPane.setDividerLocation(200); // 设置分割条位置
// 左边面板
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
JButton garenButton = createButton("盖伦");
JButton teemoButton = createButton("提莫");
JButton annieButton = createButton("安妮");
leftPanel.add(garenButton);
leftPanel.add(teemoButton);
leftPanel.add(annieButton);
// 右边面板
JPanel rightPanel = new JPanel();
rightPanel.setBackground(Color.WHITE);
imageLabel = new JLabel(new ImageIcon("garen.jpg")); // 默认显示盖伦图片
rightPanel.add(imageLabel);
// 添加左右面板到SplitPane
splitPane.setLeftComponent(leftPanel);
splitPane.setRightComponent(rightPanel);
// 监听按钮点击事件
garenButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
displayImage("garen.jpg");
}
});
teemoButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
displayImage("teemo.jpg");
}
});
annieButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
displayImage("annie.jpg");
}
});
add(splitPane);
pack();
setLocationRelativeTo(null); // 居中显示窗口
}
private JButton createButton(String text) {
JButton button = new JButton(text);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
return button;
}
private void displayImage(String imagePath) {
ImageIcon imageIcon = new ImageIcon(imagePath);
imageLabel.setIcon(imageIcon);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SplitPanelExample().setVisible(true);
}
});
}
}
在这个示例中,创建了一个SplitPanelExample
类,继承自JFrame
。在构造函数中,首先设置窗口的标题、关闭操作和首选大小。
然后,创建一个JSplitPane
作为主要容器,并设置分割条的位置。
左边的面板使用JPanel
,使用BoxLayout
布局管理器,垂直排列三个按钮。通过createButton
方法创建按钮,并将其添加到左边面板。
右边的面板也是一个JPanel
,背景设置为白色。创建一个JLabel
用于显示图片,默认显示盖伦的图片。将JLabel
添加到右边面板。
接下来,使用setLeftComponent
和setRightComponent
方法将左边面板和右边面板添加到JSplitPane
。
为三个按钮添加ActionListener
,当按钮被点击时,调用displayImage
方法来显示对应的图片。displayImage
方法将创建一个ImageIcon
对象,并将其设置为JLabel
的图标。
最后,将JSplitPane
添加到窗口中,并设置窗口的位置居中。通过SwingUtilities.invokeLater
在事件调度线程中创建并显示窗口。