我必须做一个练习,需要在左侧放置一个黑色的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,左上角有星形一般路径,但我想做的是将它放在黑色面板的中间。
我在网上搜索过,但一无所获,有人有想法吗?
最佳答案
super.paintComponent(g);
AffineTransform move = AffineTransform.getTranslateInstance(x,y);
g.setTransform(move);
// draw the shape...
关于java - 如何设置 JPanel 中 GeneralPath 的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27604159/