Related
So, if I try to move the shape, it actually moves, but there is no motion animation. In order for the moved shape to be drawn, the application window must be minimized or maximized.
Here is the PentaminoShape class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
public class PentominoShape extends JFrame implements MouseListener, MouseMotionListener {
JPanel shapePane;
Container contentPane;
private Polygon currPolygon;
private int x, y;
ArrayList<Polygon> polygons = new ArrayList<Polygon>();
JFrame frame;
public PentominoShape(JFrame frame){
this.frame = frame;
initShape();
}
private void initShape() {
Polygon fig1 = new Polygon(new int[]{10, 50, 50, 10}, new int[]{10, 10, 200, 200}, 4);
Polygon fig2 = new Polygon(new int[]{130, 210, 210, 170, 170, 130, 130, 90, 90, 130}, new int[]{80, 80, 120, 120, 200, 200, 160, 160, 120, 120}, 10);
Polygon fig3 = new Polygon(new int[]{290, 330, 330, 250, 250, 290}, new int[]{50, 50, 200, 200, 160, 160}, 6);
Polygon fig4 = new Polygon(new int[]{10, 90, 90, 50, 50, 10}, new int[]{280, 280, 400, 400, 360, 360}, 6);
Polygon fig5 = new Polygon(new int[]{170, 210, 210, 170, 170, 130, 130, 170}, new int[]{240, 240, 360, 360, 400, 400, 320, 320}, 8);
Polygon fig6 = new Polygon(new int[]{250, 370, 370, 330, 330, 290, 290, 250}, new int[]{280, 280, 320, 320, 400, 400, 320, 320}, 8);
Polygon fig7 = new Polygon(new int[]{10, 50, 50, 90, 90, 130, 130, 10}, new int[]{480, 480, 520, 520, 480, 480, 560, 560}, 8);
Polygon fig8 = new Polygon(new int[]{170, 250, 250, 290, 290, 170}, new int[]{520, 520, 440, 440, 560, 560}, 6);
Polygon fig9 = new Polygon(new int[]{330, 370, 370, 410, 410, 450, 450, 410, 410, 330}, new int[]{520, 520, 480, 480, 440, 440, 520, 520, 560, 560}, 10);
Polygon fig10 = new Polygon(new int[]{10, 50, 50, 90, 90, 130, 130, 90, 90, 50, 50, 10}, new int[]{680, 680, 640, 640, 680, 680, 720, 720, 760, 760, 720, 720}, 12);
Polygon fig11 = new Polygon(new int[]{170, 210, 210, 250, 250, 210, 210, 170}, new int[]{640, 640, 600, 600, 760, 760, 680, 680}, 8);
Polygon fig12 = new Polygon(new int[]{330, 410, 410, 370, 370, 290, 290, 330}, new int[]{640, 640, 680, 680, 760, 760, 720, 720}, 8);
polygons.add(fig1);
polygons.add(fig2);
polygons.add(fig3);
polygons.add(fig4);
polygons.add(fig5);
polygons.add(fig6);
polygons.add(fig7);
polygons.add(fig8);
polygons.add(fig9);
polygons.add(fig10);
polygons.add(fig11);
polygons.add(fig12);
Color[] c = new Color[12];
c[0] = new Color(25, 165, 25);
c[1] = new Color(255, 165, 25);
c[2] = new Color(255, 50, 50);
c[3] = new Color(150, 45, 90);
c[4] = new Color(25, 165, 150);
c[5] = new Color(25, 165, 255);
c[6] = new Color(255, 40, 190);
c[7] = new Color(180, 90, 60);
c[8] = new Color(90, 80, 70);
c[9] = new Color(70, 80, 90);
c[10] = new Color(150, 30, 20);
c[11] = new Color(80, 80, 80);
shapePane = new JPanel(){
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(c[0]); g2.fill(fig1);
g2.setColor(c[1]); g2.fill(fig2);
g2.setColor(c[2]); g2.fill(fig3);
g2.setColor(c[3]); g2.fill(fig4);
g2.setColor(c[4]); g2.fill(fig5);
g2.setColor(c[5]); g2.fill(fig6);
g2.setColor(c[6]); g2.fill(fig7);
g2.setColor(c[7]); g2.fill(fig8);
g2.setColor(c[8]); g2.fill(fig9);
g2.setColor(c[9]); g2.fill(fig10);
g2.setColor(c[10]); g2.fill(fig11);
g2.setColor(c[11]); g2.fill(fig12);
}
};
/*contentPane = this.getContentPane();
contentPane.add(shapePane);
this.pack();*/
frame.add(shapePane);
shapePane.addMouseListener(this);
shapePane.addMouseMotionListener(this);
/*shapePane.addMouseListener(this);
shapePane.addMouseMotionListener(this);*/
}
public void mousePressed(MouseEvent e) {
for(Polygon polygon: polygons) {
if (polygon.contains(e.getPoint())) {
System.out.println("Pressed");
currPolygon = polygon;
x = e.getX();
y = e.getY();
}
}
}
public void mouseDragged(MouseEvent e) {
try {
if (currPolygon.contains(x, y)) {
System.out.println("Dragged");
int dx = e.getX() - x;
int dy = e.getY() - y;
currPolygon.translate(dx, dy);
x += dx;
y += dy;
repaint();
}
}catch (NullPointerException ex){
}
}
public void mouseReleased(MouseEvent e){
currPolygon = null;
}
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseMoved(MouseEvent e){}
}
And the main Pentamino class:
import javax.swing.*;
public class Pentomino extends JFrame {
JFrame frame;
PentominoShape shape;
PentominoPanel panel;
public Pentomino(){
initUI();
}
private void initUI(){
frame = new JFrame("Пентамино");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(1500, 900);
setResizable(false);
shape = new PentominoShape(frame);
panel = new PentominoPanel(frame);
/*frame.add(shape);
frame.add(panel);*/
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
Pentomino game = new Pentomino();
}
}
I'm new to Java and I don't understand how to solve this problem. Tried searching the internet for a similar problem but couldn't find anything.
Your bug is here:
public void mouseDragged(MouseEvent e) {
try {
if (currPolygon.contains(x, y)) {
System.out.println("Dragged");
int dx = e.getX() - x;
int dy = e.getY() - y;
currPolygon.translate(dx, dy);
x += dx;
y += dy;
repaint(); // ***** here ****
}
}catch (NullPointerException ex){
}
}
You're calling repaint() on the enclosing class, a JFrame, one that is never displayed, and this will have not have the effect desired.
In fact, ask yourself, why this...
public class PentominoShape extends JFrame // ...
Why is PentominoShape extending JFrame at all, when it isn't behaving as a JFrame, when it shouldn't be behaving as a JFrame?
Instead, call repaint on the JPanel that holds the shapes, the shapePane JPanel, and yes, get rid of catching the NullPointerException. That should never be in your code:
public void mouseDragged(MouseEvent e) {
if (currPolygon == null) {
return;
}
if (currPolygon.contains(x, y)) {
System.out.println("Dragged");
int dx = e.getX() - x;
int dy = e.getY() - y;
currPolygon.translate(dx, dy);
x += dx;
y += dy;
shapePane.repaint(); // now we're repainting the correct JPanel!
}
}
Side note: I'd clean things up a bit including
Not having any class extend JFrame if possible
Create my own polygon type of class:
public class PentominoShape2 {
private Polygon polygon;
private Color color;
public PentominoShape2(Polygon polygon, Color color) {
this.polygon = polygon;
this.color = color;
}
public void draw(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(color);
g2.fill(polygon);
}
public Polygon getPolygon() {
return polygon;
}
public Color getColor() {
return color;
}
public boolean contains(Point p) {
return polygon.contains(p);
}
}
and then in the drawing JPanel
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (PentominoShape2 poly : polys) {
poly.draw(g);
}
}
same for the mouse listener
I am making a GUI that has Graphics2D objects drawn on a JPanel within a JFrame. When I resize the window the Graphics2D objects reduce into a tiny rectangle. How can I set the drawing to resize with the JFrame when the user resizes the window?
I have tried using gridlayout, flowlayout, borderlayout, and settled on gridbaglayout. This helps with the resizing of btnPanel and the JButton but not for the Graphics2D objects.
Here is my self contained example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class DrawPanelMain extends JPanel {
/*
* Variables used to set the value of preferred height and width
*/
public static final double version = 0.0;
JPanel btnPanel = new JPanel();
JPanel switchPanel = new JPanel();
DrawEllipses drawEllipses = new DrawEllipses(POINT_LIST);
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
initializePointList();
createAndShowGui();
}
});
}
public static java.util.List<Point> POINT_LIST = new ArrayList<>();
/*
* This loop will initialize POINT_LIST with the set of points for drawing the ellipses.
* The for each loop initializes points for the top row and the second for loop draws the
* right triangle.
*/
public static void initializePointList() {
int ellipsePointsYCoordinate[] = {140, 200, 260, 320, 380, 440, 500, 560, 620};
int ellipsePointsXCoordinate[] = {140, 200, 260, 320, 380, 440, 500, 560, 620, 680};
int xx = 80;
for (int aXt : ellipsePointsXCoordinate) {
POINT_LIST.add(new Point(aXt, xx));
}
for (int i = 0; i < ellipsePointsYCoordinate.length; i++) {
for (int j = i; j < ellipsePointsYCoordinate.length; j++) {
POINT_LIST.add(new Point(ellipsePointsXCoordinate[i], ellipsePointsYCoordinate[j]));
}
}
}
public DrawPanelMain() {
switchPanel.setBorder(BorderFactory.createLoweredSoftBevelBorder());
switchPanel.setBackground(Color.DARK_GRAY);
switchPanel.add(drawEllipses);
switchPanel.revalidate();
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// first column
c.gridx = 0;
add(switchPanel, c);
// second column
c.gridx = 1;
add(switchPanel, c);
// first row
c.gridy = 0;
// second row
c. gridy = 1;
add(btnPanel, c);
btnPanel.add(new JButton(new AddSwitchAction("Add Switch Panel")));
}
public static void createAndShowGui() {
JFrame frame = new JFrame("RF Connection Panel " + version);
frame.setLayout(new BorderLayout());
frame.add(new DrawPanelMain());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(false);
//frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
/*
* AddSwitchAction will add a new pane to the tabbedPane when the add switch button is clicked
*/
private class AddSwitchAction extends AbstractAction {
public AddSwitchAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
String title = "Switch ";
DrawEllipses tabComponent = new DrawEllipses(POINT_LIST);
switchPanel.add(title, tabComponent);
}
}
}
#SuppressWarnings("serial")
class DrawEllipses extends JPanel {
private final int PREF_W = 750; //Window width
private final int PREF_H = 750; //Window height
private final int OVAL_WIDTH = 30;
private static final Color INACTIVE_COLOR = Color.RED;
private static final Color ACTIVE_COLOR = Color.green;
private java.util.List<Point> points;
private java.util.List<Ellipse2D> ellipses = new ArrayList<>();
private Map<Ellipse2D, Color> ellipseColorMap = new HashMap<>();
/*
* This method is used to populate "ellipses" with the initialized ellipse2D dimensions
*/
public DrawEllipses(java.util.List<Point> points) {
this.points = points;
for (Point p : points) {
int x = p.x - OVAL_WIDTH / 2;
int y = p.y - OVAL_WIDTH / 2;
int w = OVAL_WIDTH;
int h = OVAL_WIDTH;
Ellipse2D ellipse = new Ellipse2D.Double(x, y, w, h);
ellipses.add(ellipse);
ellipseColorMap.put(ellipse, INACTIVE_COLOR);
}
MyMouseAdapter mListener = new MyMouseAdapter();
addMouseListener(mListener);
addMouseMotionListener(mListener);
}
/*
* paintComponent is used to paint the ellipses
*/
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for (Ellipse2D ellipse : ellipses) {
g2.setColor(ellipseColorMap.get(ellipse));
g2.fill(ellipse);
g2.setColor(Color.BLACK);
g2.setStroke(new BasicStroke(2));
g2.draw(ellipse);
}
/*
* Set the font characteristics, color, and draw the row labels.
*/
g.setFont(new Font("TimesRoman", Font.BOLD, 18));
g.setColor(Color.BLACK);
//Along the top row
g.drawString("External Port", 10, 50);
g.drawString("1", 135, 50);
g.drawString("2", 195, 50);
g.drawString("3", 255, 50);
g.drawString("4", 315, 50);
g.drawString("5", 375, 50);
g.drawString("6", 435, 50);
g.drawString("7", 495, 50);
g.drawString("8", 555, 50);
g.drawString("9", 615, 50);
g.drawString("10", 672, 50);
//Along the Y-axis
g.drawString("Radio 2", 40, 145);
g.drawString("3", 90, 205);
g.drawString("4", 90, 265);
g.drawString("5", 90, 325);
g.drawString("6", 90, 385);
g.drawString("7", 90, 445);
g.drawString("8", 90, 505);
g.drawString("9", 90, 565);
g.drawString("10", 90, 625);
//Along the X-Axis
g.drawString("1", 135, 670);
g.drawString("2", 195, 670);
g.drawString("3", 255, 670);
g.drawString("4", 315, 670);
g.drawString("5", 375, 670);
g.drawString("6", 435, 670);
g.drawString("7", 495, 670);
g.drawString("8", 555, 670);
g.drawString("9", 615, 670);
//Draws a 3DRect around the top row of ellipse2D objects
g2.setColor(Color.lightGray);
g2.draw3DRect(120, 60, 580, 40, true);
g2.draw3DRect(121, 61, 578, 38, true);
g2.draw3DRect(122, 62, 576, 36, true);
}
/*
* MouseAdapter is extended for mousePressed Event that detects if the x, y coordinates
* of a drawn ellipse are clicked. If the color is INACTIVE it is changed to ACTIVE and
* vice versa.
*/
private class MyMouseAdapter extends MouseAdapter {
#Override
/*
* When mousePressed event occurs, the color is toggled between ACTIVE and INACTIVE
*/
public void mousePressed(MouseEvent e) {
Color c;
for (Ellipse2D ellipse : ellipses) {
if (ellipse.contains(e.getPoint())) {
c = (ellipseColorMap.get(ellipse) == INACTIVE_COLOR) ? ACTIVE_COLOR : INACTIVE_COLOR;
ellipseColorMap.put(ellipse, c);
}
}
repaint();
}
}
/*
* This method will set the dimensions of the JFrame equal to the preferred H x W
*/
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
/*
* Used for button click action to change all ellipses to ACTIVE_COLOR
*/
public void activateAll(){
for (Ellipse2D ellipse : ellipses){
ellipseColorMap.put(ellipse, ACTIVE_COLOR);
}
repaint();
}
/*
* Used for button click action to change all ellipses to INACTIVE_COLOR
*/
public void deactivateAll(){
for (Ellipse2D ellipse : ellipses){
ellipseColorMap.put(ellipse, INACTIVE_COLOR);
}
repaint();
}
}
This method will set the dimensions of the JFrame equal to the preferred H x W
No it set the preferred size of the panel. The size of the frame will be the preferred size of all the components added to it plus the frame decorations (title bar, borders).
When I resize the window the Graphics2D objects reduce into a tiny rectangle.
The GridBagLayout respects the preferred size of the component. When there is not enough space to display the component it will shrink to its "minimum size".
You probably need to override the getMinimumSize() method to equal the preferred size. Then in this case the component should just be truncated if space is not available.
If you want you actually painting to shrink then you need to build the logic into your painting code so that the painting is done relative to the space available on the panel.
Try adding your 2D object to a JLabel as BufferedImage of ImageIcon. You can do this by:
JLabel label2 = new JLabel(new ImageIcon(//Location of your Image);
Or I think you can also add Graphics2D objects directly creating them inside label bu I'm not sure about that
So, I am going to have more of these panels but I don't know how to make these panels switch when the user will press a button like start or next.
//IngestionOfDigestion.java teaches the user about the digestive system through interactive components
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class IngestionOfDigestion extends JFrame {
public static void main(String[] args) {
IngestionOfDigestion i = new IngestionOfDigestion();
}
public IngestionOfDigestion() {//frame header
//make the frame
super("Ingestion Of Digestion");
setSize(1900, 1100);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocation(10, 50);
setResizable(true);
layout t = new layout();
add(t);
setContentPane(t);
setVisible(true);
}
}
class layout extends JPanel {
public Mouth m;
public CardLayout cardlay = new CardLayout();
Title title = new Title();
public layout() {
m = new Mouth();
cardlay.show();
setLayout(cardlay);
add(m, "Mouth");
add(title, "Title");
}
}
class Title extends JPanel implements ActionListener {//make title panel
private JButton c;//jbutton to start the game
private boolean startpressed;//button pressed variable
//JPanel card2;
//JPanel card3;
public Title() {//title method header
//cardstack = new JPanel(cardlay);
c = new JButton("Press to start playing");//make jbutton saying start the game
c.addActionListener(this);
add(c);
startpressed = false;
}
public void paintComponent(Graphics g) { //paint component
super.paintComponent(g);//super.paintComponent
Font title = new Font("Serif", Font.BOLD, 90);//make font
g.setFont(title);
g.drawString("Ingestion Of Digestion", 160, 100);//draw the title
if (startpressed == true) {//if buttonpressed is true
repaint();
}
}
public void actionPerformed(ActionEvent e) {//ActionPerformed
if (e.getSource() == c) {
startpressed = true;//change boolean
cardlay.next();
repaint();
}
}
}
//if button is pressed
//end title panel
class Mouth extends JPanel implements ActionListener, ChangeListener {
private JButton chew;//make chew button
private JButton next;//next button
private JSlider saliva;//make saliva slider
private boolean nextpressed;//nextbuttonpressed variable
private boolean chewpressed;//buttonpressed variable
Mouth() {//mouth method
chew = new JButton("Press to chew the food");
chew.addActionListener(this);
add(chew);
chewpressed = false;
JSlider saliva = new JSlider(JSlider.HORIZONTAL, 0, 100, 0);
add(saliva);
next = new JButton("Press to go to the next step of digestion");
next.addActionListener(this);
add(next);
nextpressed = false;
}
public void paintComponent(Graphics g) {//paint component
super.paintComponent(g);//super.paintComponent
//draw the head
Color skin = new Color(255, 204, 133);
g.setColor(skin);
g.fillArc(810, 1000, 550, 550, 0, 180);
g.fillRect(1085, 600, 150, 550);
g.fillRect(700, 250, 535, 380);
int[] w = {700, 700, 660};
int[] t = {340, 420, 420};
g.fillPolygon(w, t, 3);
Color hair = new Color(100, 60, 0);
g.setColor(hair);
g.fillArc(700, 175, 535, 150, 0, 180);
g.setColor(Color.WHITE);
g.fillOval(730, 275, 45, 45);
g.setColor(Color.BLACK);
g.fillOval(752, 297, 15, 15);
g.setColor(Color.RED);
g.fillRect(700, 480, 285, 75);
g.fillRect(985, 497, 145, 45);
g.fillRect(1130, 497, 30, 590);
g.setColor(Color.WHITE);
g.fillRect(702, 480, 15, 20);
g.fillRect(719, 480, 15, 20);
g.fillRect(736, 480, 15, 20);
g.fillRect(753, 480, 24, 20);
g.fillRect(779, 480, 24, 20);
g.fillRect(805, 480, 24, 20);
g.fillRect(702, 535, 15, 20);
g.fillRect(719, 535, 15, 20);
g.fillRect(736, 535, 15, 20);
g.fillRect(753, 535, 24, 20);
g.fillRect(779, 535, 24, 20);
g.fillRect(805, 535, 24, 20);
if (chewpressed == true) {
Color skint = new Color(255, 204, 133);
g.setColor(skint);
g.fillArc(810, 1000, 550, 550, 0, 180);
g.fillRect(1085, 600, 150, 550);
g.fillRect(700, 250, 285, 380);
int[] wt = {700, 700, 660};
int[] tw = {340, 420, 420};
g.fillPolygon(w, t, 3);
Color hairt = new Color(100, 60, 0);
g.setColor(hairt);
g.fillArc(700, 175, 535, 150, 0, 180);
g.setColor(Color.WHITE);
g.fillOval(730, 275, 45, 45);
g.setColor(Color.BLACK);
g.fillOval(752, 297, 15, 15);
g.setColor(Color.RED);
g.fillRect(700, 480, 285, 42);
g.fillRect(985, 497, 145, 35);
g.fillRect(1130, 497, 30, 590);
g.setColor(Color.WHITE);
g.fillRect(702, 480, 15, 20);
g.fillRect(719, 480, 15, 20);
g.fillRect(736, 480, 15, 20);
g.fillRect(753, 480, 24, 20);
g.fillRect(779, 480, 24, 20);
g.fillRect(805, 480, 24, 20);
g.fillRect(702, 502, 15, 20);
g.fillRect(719, 502, 15, 20);
g.fillRect(736, 502, 15, 20);
g.fillRect(753, 502, 24, 20);
g.fillRect(779, 502, 24, 20);
g.fillRect(805, 502, 24, 20);
repaint();
}
}
public void actionPerformed(ActionEvent e) {//ActionPerformed
if (chew.getText().equals("Press to chew the food")) {//if "press my belly" pressed,
chewpressed = true;//change boolean
repaint();
if (next.getText().equals("Press to go to the next step of digestion")) {
nextpressed = true;
}
repaint();
}
}
public void stateChanged(ChangeEvent e) {
int location1 = saliva.getValue();
}
}
//draw the info
//if buttonpressed is true
//show head with teeth clenched
//else if slidermoved is true
//show saliva moving in mouth
//else if nextbuttonpressed is true
//go to next panel
//ActionPerformed
//if button is pressed
//buttonpressed is true
//else if slider is moved
//slidermoved is true
//else if next button is pressed
//nextbuttonpressed is true
import java.awt.event.ActionEvent; //this is my button class
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import java.awt.Dimension;
public class Buttons extends JFrame{
private JPanel panel1, panel2;
private JButton button1, button2, button3;
private JMenuBar menuBar;
public Buttons()
{
createPanel();
addPanel();
}
private void createPanel()
{
setLocationRelativeTo(null);
panel1 = new JPanel();
panel1.setBackground(Color.cyan);
button1 = new JButton("Start");
button1.addActionListener(new addButtonListener());
button1.setBounds(50, 90, 190, 30);
button2 = new JButton("Instructions");
button2.setBounds(70, 130, 160, 30);
panel2 = new JPanel();
//button3 = new JButton("Test");
//panel2.setBackground(Color.orange);
//button3.setBounds(50, 50, 90, 30);
}
private void addPanel()
{
panel1.add(button1);
panel1.add(button2);
panel2.add(button3);
add(panel1);
}
class addButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
getContentPane().removeAll();
getContentPane().add(panel2);
repaint();
printAll(getGraphics());
}
}
public static void main(String[]args)
{
JMenuItem exitAction = new JMenuItem("Exit");
JMenuBar menuBar = new JMenuBar();
JMenu save = new JMenu("Save");
JMenu file = new JMenu("File");
JMenu credit = new JMenu("Credit");
file.add(exitAction);
menuBar.add(file);
menuBar.add(save);
menuBar.add(credit);
exitAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
Buttons frame = new Buttons();
frame.setTitle("Bikini Bottom Marathon");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,500);
frame.setVisible(true);
frame.setJMenuBar(menuBar);
}
}
import javax.swing.*;
//this is my graphics class to create a board. the images are imported from saved
pictures in my class file. I'm trying to add the output from this code (the board)
onto the buttons class
import java.applet.*;
import java.awt.*;
import javax.imageio.*;
import java.net.*;
import java.io.*;
import java.awt.image.*;
import java.applet.*;
public class compscigame extends Applet
{
public void paint (Graphics page)
{
Image pineapple = getImage(getCodeBase(), "pineapple.jpg");
page.drawImage (pineapple, 50, 500, 50, 50, this);
Image raygun = getImage(getCodeBase(), "Raygun.jpg");
page.drawImage (raygun, 300, 350, 50, 50, this);
Image karen = getImage(getCodeBase(), "Karen.jpg");
page.drawImage(karen, 100, 50, 50, 50, this);
Image karensmad = getImage(getCodeBase(), "karensmad.jpg");
page.drawImage(karensmad, 150, 400, 50, 50, this);
Image rocketboots = getImage(getCodeBase(), "rocketboots.jpg");
page.drawImage(rocketboots, 200, 300, 50, 50, this);
Image emptybeaker = getImage(getCodeBase(), "emptybeaker.jpg");
page.drawImage(emptybeaker, 350, 150, 50, 50, this);
Image happykaren = getImage(getCodeBase(), "happykaren.jpg");
page.drawImage(happykaren, 100, 50, 50, 50, this);
Image raygunnotshooting = getImage(getCodeBase(), "raygunnotshooting.jpg");
page.drawImage (raygunnotshooting, 450, 200, 50, 50, this);
Image notfirerocket = getImage(getCodeBase(), "notfirerocket.jpg");
page.drawImage (notfirerocket, 450, 450, 50, 50, this);
Image firerocket = getImage(getCodeBase(), "firerocket.jpg");
page.drawImage (firerocket, 500, 200, 50, 50, this);
Image fullbeaker = getImage(getCodeBase(), "fullbeaker.jpg");
page.drawImage (fullbeaker, 250, 250, 50, 50, this);
Image boots = getImage(getCodeBase(), "boots.jpg");
page.drawImage (boots, 300, 500, 50, 50, this);
Image krustykrab = getImage(getCodeBase(), "krustykrab.jpg");
page.drawImage(krustykrab, 50, 50, 50, 50, this);
Board board = new Board(page, new Color (255,0,100));
setBackground(Color.YELLOW);
}
class Board
{
private Graphics g;
private Color col;
private Square [][] squares;
public Board (Graphics g, Color col)
{
this.col = col;
this.g = g;
Color temp;
squares = new Square[10][10];
for (int i = 1; i <= 10; i++)
{
for (int j = 1; j <= 10; j++)
{
int num;
if (i + j % 2 == 0)
temp = col;
else
temp = new Color(255, 0 , 255);
Square t;
t = new Square (g, temp, i, j);
if (j % 2 != 0)
{
num = 10 - i + 1 + 10 * (j - 1);
}
else
{
num = i + 10 * (j - 1);
}
t.setVal(num);
t.drawSquare();
squares[i - 1][j - 1] = t;
}
}
}
}
class Square
{
private Color col;
private int x;
private int y;
private Graphics g;
private int val;
public Square (Graphics g, Color col, int x, int y)
{
this.col = col;
this.g = g;
this.x = x;
this.y = y;
val = 0;
}
public void setVal(int num)
{
val = num;
}
public void drawSquare()
{
g.setColor(col);
g.drawRect(50 + (10 - x) * 50, 50 + (10 - y) * 50, 50, 50);
String str = "" + val;
g.drawString(str, 50 + (10 - x) * 50 + 5, 50 + (10 - y) * 50 + 10);
}
}
I just want the board to be in another panel. As you can see I used ActionListener to create the action my buttons will do. When you click Start it takes you to the button that says "test." I want the graphic from the Board to show on this second panel, (panel2)
}
Make a custom inner class that extends JPanel and then override the onPaintComponent method. Draw the Board there. Create a new BoardPanel instead of a JPanel.
Put your paint code in a seperate class (JPanel)
public void paint (Graphics page)
{
...
}
There is no need for the applet to have a dependency on any of this code.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to make a little racing game for fun. So far I have two rectangles that successfully move and I have a map setup for them to race through.
My map is also made up of rectangles. Now previously I made a mistake by not giving my two racers a specific objectified name. So they're just two locations that move. Now what i'm trying to do is, to make the rectangle walls actually be walls so they don't just go through them. I've heard I can cover up my mistakes if I make the walls like arrays(not sure how) so they don't go through them. Is this correct? Is there any other way to do this?
Here is how it looks like so far:
Thank you and here is my code.
First class is the info for frames and black rectangle.
Second class is the info for the blue rectangles and the walls.
First Class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class MyGame extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
int x = 0, y = 0, velx =0, vely =0, g = 0;
private Color color;
public MyGame() {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1300, 750);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(x, y, 50, 30);
}
#Override
public void actionPerformed(ActionEvent e) {
if (x < 0) //stops us from going backwards past x = 0
{
velx = 0;
x = 0;
}
if (y < 0) //stops us from going to the sky
{
vely = 0;
y = 0;
}
if (y > 725) // stops us from going through the ground
{
vely = 0;
y = 725;
}
if (x > 1250) // stops us from going through the wall
{
velx = 0;
x = 1250;
}
x += velx;
y += vely;
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
{
if (code == KeyEvent.VK_DOWN) {
vely = 2; // removing velx = 0 allows us to go vertically and horizontlly at the same time
velx = 0;
}
if (code == KeyEvent.VK_UP) {
vely = -2; // same goes for here
velx = 0;
}
if (code == KeyEvent.VK_LEFT) {
vely = 0;
velx = -2;
}
{
if (code == KeyEvent.VK_RIGHT) {
vely = 0;
velx = 2;
}
}
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
public static void main (String arge[]){
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new Incoming());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Second Class:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Incoming extends MyGame {
private Color color;
int x = 0, y = 0;
int velx = 0, vely = 0;
public Incoming() {
color = Color.BLUE;
Rectangle rect = new Rectangle();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(x, y, 50, 30);
g.setColor(Color.blue);
g.drawRect(0, 100, 80, 30);
g.drawRect(80, 100, 80, 30);
g.drawRect(160, 100, 80, 30);
g.drawRect(240, 100, 80, 30);
g.drawRect(320, 100, 80, 30);
g.drawRect(400, 100, 80, 30);
g.drawRect(480, 100, 80, 30);
g.drawRect(560, 100, 80, 30);
g.drawRect(640, 100, 80, 30);
g.drawRect(720, 100, 80, 30);
g.drawRect(800, 100, 80, 30);
g.drawRect(880, 100, 80, 30);
g.drawRect(960, 100, 80, 30);
g.drawRect(1040, 100, 80, 30);
g.drawRect(1040, 250, 80, 30);
g.drawRect(1120, 250, 80, 30);
g.drawRect(1200, 250, 80, 30);
g.drawRect(960, 250, 80, 30);
g.drawRect(880, 250, 80, 30);
g.drawRect(800, 250, 80, 30);
g.drawRect(720, 250, 80, 30);
g.drawRect(640, 250, 80, 30);
g.drawRect(560, 250, 80, 30);
g.drawRect(480, 250, 80, 30);
g.drawRect(400, 250, 80, 30);
g.drawRect(320, 250, 80, 30);
g.drawRect(240, 250, 80, 30);
g.drawRect(160, 250, 80, 30);
g.drawRect(1040, 400, 80, 30);
g.drawRect(960, 400, 80, 30);
g.drawRect(880, 400, 80, 30);
g.drawRect(800, 400, 80, 30);
g.drawRect(720, 400, 80, 30);
g.drawRect(640, 400, 80, 30);
g.drawRect(560, 400, 80, 30);
g.drawRect(480, 400, 80, 30);
g.drawRect(400, 400, 80, 30);
g.drawRect(320, 400, 80, 30);
g.drawRect(240, 400, 80, 30);
g.drawRect(160, 400, 80, 30);
g.drawRect(80, 400, 80, 30);
g.drawRect(0, 400, 80, 30);
g.drawRect(1040, 550, 80, 30);
g.drawRect(1120, 550, 80, 30);
g.drawRect(1200, 550, 80, 30);
g.drawRect(960, 550, 80, 30);
g.drawRect(880, 550, 80, 30);
g.drawRect(800, 550, 80, 30);
g.drawRect(720, 550, 80, 30);
g.drawRect(640, 550, 80, 30);
g.drawRect(560, 550, 80, 30);
g.drawRect(480, 550, 80, 30);
g.drawRect(400, 550, 80, 30);
g.drawRect(320, 550, 80, 30);
g.drawRect(240, 550, 80, 30);
g.drawRect(160, 550, 80, 30);
g.drawRect(1040, 550, 80, 30);
g.drawRect(960, 550, 80, 30);
g.drawRect(880, 550, 80, 30);
g.drawRect(800, 550, 80, 30);
g.drawRect(720, 550, 80, 30);
g.drawRect(640, 550, 80, 30);
g.drawRect(560, 550, 80, 30);
g.drawRect(480, 550, 80, 30);
g.drawRect(400, 550, 80, 30);
g.drawRect(320, 550, 80, 30);
g.drawRect(240, 550, 80, 30);
g.drawRect(160, 550, 80, 30);
}
#Override
public void actionPerformed(ActionEvent e) {
super.actionPerformed(e);
if (x < 0) //stops us from going backwards past x = 0
{
velx = 0;
x = 0;
}
if (y < 0) //stops us from going to the sky
{
vely = 0;
y = 0;
}
if (y > 725) // stops us from going through the ground
{
vely = 0;
y = 725;
}
if (x > 1250) // stops us from going through the wall
{
velx = 0;
x = 1250;
}
if (y < 0.1)
{
y = 50;
}
x += velx;
y += vely;
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
int code = e.getKeyCode();
{
if (code == KeyEvent.VK_S) {
vely = 2; // removing velx = 0 allows us to go vertically and horizontlly at the same time
velx = 0;
}
if (code == KeyEvent.VK_W) {
vely = -2; // same goes for here
velx = 0;
}
if (code == KeyEvent.VK_A) {
vely = 0;
velx = -2;
}
{
if (code == KeyEvent.VK_D) {
vely = 0;
velx = 2;
}
}
}
}
#Override
public void keyReleased(KeyEvent e) {
super.keyReleased(e);
}
}
How would I list rectangles?
See the DrawOnCompnent example from Custom Painting Approaches. It shows you how to paint from an ArrayList.