Я пытался выяснить, как добавить объект Graphics2D в JFrame, а также кнопки к тому же объекту фрейма / панели. Я хочу, чтобы кнопки могли как-то редактировать изображение, но у меня много проблем с отображением кнопок и изображения на одном и том же JFrame. Ниже код и получающееся окно, которое я вижу, что я делаю не так? И спасибо за ваше время.
package carEditor;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CarIcon extends JPanel{
public void paint(Graphics g){
int x = 10;
int y = 50;
int width = 100;
Graphics2D g2 = (Graphics2D) g;
Rectangle2D.Double body
= new Rectangle2D.Double(x, y + width / 6,
width - 1, width / 6);
Ellipse2D.Double frontTire
= new Ellipse2D.Double(x + width / 6, y + width / 3,
width / 6, width / 6);
Ellipse2D.Double rearTire
= new Ellipse2D.Double(x + width * 2 / 3, y + width / 3,
width / 6, width / 6);
// The bottom of the front windshield
Point2D.Double r1
= new Point2D.Double(x + width / 6, y + width / 6);
// The front of the roof
Point2D.Double r2
= new Point2D.Double(x + width / 3, y);
// The rear of the roof
Point2D.Double r3
= new Point2D.Double(x + width * 2 / 3, y);
// The bottom of the rear windshield
Point2D.Double r4
= new Point2D.Double(x + width * 5 / 6, y + width / 6);
Line2D.Double frontWindshield
= new Line2D.Double(r1, r2);
Line2D.Double roofTop
= new Line2D.Double(r2, r3);
Line2D.Double rearWindshield
= new Line2D.Double(r3, r4);
g2.fill(frontTire);
g2.fill(rearTire);
g2.setColor(Color.red);
g2.fill(body);
g2.draw(frontWindshield);
g2.draw(roofTop);
g2.draw(rearWindshield);
}
public static void main(String[] args){
JFrame frame= new JFrame();
JPanel jpb = new JPanel();
JButton zoomOutButton = new JButton("Zoom Out");
JButton zoomInButton = new JButton("Zoom In");
frame.setLayout(new FlowLayout());
//zoomOutButton.addActionListener(event ->
// textField.setText("Goodbye"));
//zoomInButton.addActionListener(event ->
//textField.setText("Hello"));
jpb.add(zoomInButton);
jpb.add(zoomOutButton);
frame.add(jpb, BorderLayout.SOUTH);
frame.setContentPane(new CarIcon());
//frame.pack();
frame.setSize(600, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
}
}
Вот результат, который я вижу:
На этом кадре должны быть кнопки, но их нет. Это почему? Спасибо за вашу помощь, я новичок в программировании на Java и с нетерпением жду ваших ответов.