我必须做一个练习,需要在左边放置一个黑色JPanel
,我必须在那里画一个星形 GeneralPath
和一些按钮右边必须移动该通用路径,再加上一个重置按钮,它将在面板中间设置一般路径的位置。
这是代码:
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class SunGUI extends JFrame {
private Space space;
private Control control;
private final int DELTA = 50;
private int posX, posY;
public SunGUI() {
Container cnt = getContentPane();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
space = new Space();
control = new Control();
cnt.add(space, BorderLayout.CENTER);
cnt.add(control, BorderLayout.EAST);
pack();
setVisible(true);
}
public class Space extends JPanel {
private GeneralPath sun;
public Space() {
setPreferredSize(new Dimension(800, 600));
sun = createSun();
}
public GeneralPath createSun() {
GeneralPath sun = new GeneralPath();
sun.moveTo(-30, -30);
sun.lineTo(50, 50);
sun.moveTo(50, -30);
sun.lineTo(-30, 50);
sun.moveTo(10, -35);
sun.lineTo(10, 55);
sun.moveTo(-35, 10);
sun.lineTo(55, 10);
sun.moveTo(-5, -25);
sun.lineTo(25, 45);
sun.moveTo(25, -25);
sun.lineTo(-5, 45);
sun.moveTo(-25, -5);
sun.lineTo(45, 25);
sun.moveTo(45, -5);
sun.lineTo(-25, 25);
sun.closePath();
return sun;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
setBorder(BorderFactory.createLineBorder(Color.red));
setBackground(Color.black);
g2.setPaint(Color.white);
g2.draw(sun);
}
}
public class Control extends JPanel {
private JButton up, down, left, right, reset;
private JPanel arrows, panel, resetPanel, container;
public Control() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
panel = new JPanel();
arrows = new JPanel();
resetPanel = new JPanel();
container = new JPanel();
arrows.setLayout(new GridLayout(1, 4));
resetPanel.setLayout(new GridLayout(1, 1));
container.setLayout(new GridLayout(2, 1));
up = new JButton("^");
down = new JButton("v");
left = new JButton("<");
right = new JButton(">");
reset = new JButton("R");
arrows.add(up);
arrows.add(left);
arrows.add(right);
arrows.add(down);
resetPanel.add(reset);
container.add(arrows);
container.add(resetPanel);
arrows.setPreferredSize(new Dimension(160, 20));
resetPanel.setPreferredSize(new Dimension(160, 20));
panel.add(container);
panel.setBorder(new TitledBorder("Comandi"));
add(panel);
}
}
public static void main(String args[]) {
new SunGUI();
}
}
现在这段代码只会在左上角显示一个带有星形常规路径的静态GUI,但我想要做的是把它放在黑色的中间面板。
我在网上搜索过但我一无所获,是否有人有想法?
答案 0 :(得分:1)
super.paintComponent(g);
AffineTransform move = AffineTransform.getTranslateInstance(x,y);
g.setTransform(move);
// draw the shape...
答案 1 :(得分:0)
您可以使用g2.translate翻译整个图形上下文,由Andrew Thompson回答(然后重置转换),或使用AffineTransform的createTransformedShape方法仅转换形状。以下是一个示例:How to have rotated Ellipse shape in Java?