,可以通过以下步骤实现:
以下是一个简单的示例代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ShapeDrawer extends JFrame {
private JList<String> shapeList;
private JPanel drawingPanel;
public ShapeDrawer() {
setTitle("Shape Drawer");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建形状选项列表
DefaultListModel<String> shapeListModel = new DefaultListModel<>();
shapeListModel.addElement("Circle");
shapeListModel.addElement("Rectangle");
shapeListModel.addElement("Triangle");
shapeList = new JList<>(shapeListModel);
// 创建绘图区域
drawingPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 绘制形状逻辑
String selectedShape = shapeList.getSelectedValue();
if (selectedShape != null) {
int width = (int) (Math.random() * 100) + 50; // 随机生成形状的宽度
int height = (int) (Math.random() * 100) + 50; // 随机生成形状的高度
if (selectedShape.equals("Circle")) {
g.drawOval(50, 50, width, height);
} else if (selectedShape.equals("Rectangle")) {
g.drawRect(50, 50, width, height);
} else if (selectedShape.equals("Triangle")) {
int[] xPoints = {50, 50 + width, 50 + width / 2};
int[] yPoints = {50 + height, 50 + height, 50};
g.drawPolygon(xPoints, yPoints, 3);
}
}
}
};
// 监听形状选项的选择事件
shapeList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
drawingPanel.repaint(); // 重新绘制形状
}
});
// 创建布局并添加组件
setLayout(new BorderLayout());
add(new JScrollPane(shapeList), BorderLayout.WEST);
add(drawingPanel, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ShapeDrawer().setVisible(true);
}
});
}
}
这个示例代码实现了一个简单的形状绘制应用程序。用户可以从JList中选择不同的形状,然后在绘图区域中绘制随机大小的所选形状。在实际应用中,可以根据需要扩展和优化这个基本框架。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云