java语言玫瑰花代码
时间: 2023-12-20 18:29:43 浏览: 134
以下是一个简单的Java语言玫瑰花代码的例子:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RoseNJFrame extends JFrame implements ActionListener, ComponentListener {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private JButton btnDraw;
private JRadioButton[] radiobutton;
private int select = 0;
private int width = 600;
private int height = 600;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RoseNJFrame frame = new RoseNJFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public RoseNJFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(10, 10, 200, 30);
contentPane.add(textField);
textField.setColumns(10);
btnDraw = new JButton("Draw");
btnDraw.setBounds(220, 10, 80, 30);
contentPane.add(btnDraw);
btnDraw.addActionListener(this);
String[] rosestr = { "Rose1", "Rose2", "Rose3", "Rose4", "Rose5" };
radiobutton = new JRadioButton[5];
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < 5; i++) {
radiobutton[i] = new JRadioButton(rosestr[i]);
radiobutton[i].setBounds(320 + i * 80, 10, 80, 30);
radiobutton[i].addActionListener(this);
group.add(radiobutton[i]);
contentPane.add(radiobutton[i]);
}
radiobutton[0].setSelected(true);
addComponentListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnDraw) {
String str = textField.getText();
if (str.length() > 0) {
Graphics g = getGraphics();
g.clearRect(0, 0, width, height);
drawRose(g, select, str);
}
} else {
for (int i = 0; i < 5; i++) {
if (e.getSource() == radiobutton[i]) {
select = i;
break;
}
}
}
}
public void componentResized(ComponentEvent e) {
width = getWidth();
height = getHeight();
}
public void componentMoved(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
}
public void componentHidden(ComponentEvent e) {
}
private void drawRose(Graphics g, int select, String str) {
int n = 3 + select * 2;
double d = 2 * Math.PI / n;
int r = Math.min(width, height) / 2 - 50;
int x0 = width / 2;
int y0 = height / 2;
g.setColor(Color.RED);
for (int i = 0; i < n; i++) {
double theta = i * d;
double r1 = r * Math.sin(n * theta);
double r2 = r * Math.cos(n * theta);
int x1 = (int) (x0 + r1 * Math.cos(theta) - r2 * Math.sin(theta));
int y1 = (int) (y0 + r1 * Math.sin(theta) + r2 * Math.cos(theta));
g.drawString(str, x1, y1);
}
}
}
```
阅读全文