I have to do an exercise where is required to put a black JPanel
on the left where I have to draw a star-shaped GeneralPath
and some buttons on the right that will have to move that general path, plus a reset button that will set the position of the general path in the middle of the panel.
This is the code:
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();
}
}
Right now this code will only show a static GUI with the star-shaped general path in the top-left corner, but what I want to do is to put it in the middle of the black panel.
I've searched around the web but I found nothing, does anybody has an idea?