Im making a fully graphical battleship game that will eventually allow 2 players to play over a network, but im having trouble figuring out how to assign coordinates to each square on the grid, and how to let the players select where they want to place a ship. Ive made ships as .PNG's all being the corresponding length in pixels to match the 100x100 squares. (ie) carrier would take 5 squares. Lastly, can i make a small popup window that asks where the want to place a ship for each turn? The code i have is pretty small for now, Its just starting but i need a bit of help getting it going. Any help is appreciated.
package Battleshiponline;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Board extends JPanel implements ActionListener {
private Timer timer;
public Board() {
//addKeyListener(new TAdapter());
setFocusable(true);
setBackground(Color.BLUE);
setDoubleBuffered(true);
timer = new Timer(5, this);
timer.start();
String[] rowA = new String[] {"A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"};
String[] rowB = new String[] {"B1","B2","B3","B4","B5","B6","B7","B8","B9","B10"};
String[] rowC = new String[] {"C1","C2","C3","C4","C5","C6","C7","C8","C9","C10"};
String[] rowD = new String[] {"D1","D2","D3","D4","D5","D6","D7","D8","D9","D10"};
String[] rowE = new String[] {"E1","E2","E3","E4","E5","E6","E7","E8","E9","E10"};
String[] rowF = new String[] {"F1","F2","F3","F4","F5","F6","F7","F8","F9","F10"};
String[] rowG = new String[] {"G1","G2","G3","G4","G5","G6","G7","G8","G9","G10"};
String[] rowH = new String[] {"H1","H2","H3","H4","H5","H6","H7","H8","H9","H10"};
String[] rowI = new String[] {"I1","I2","I3","I4","I5","I6","I7","I8","I9","I10"};
String[] rowJ = new String[] {"J1","J2","J3","J4","J5","J6","J7","J8","J9","J10"};
}
boolean inGame;
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
//vert lines(1-10)
g2d.drawLine(100, 1000, 100, 0);
g2d.drawLine(200, 1000, 200, 0);
g2d.drawLine(300, 1000, 300, 0);
g2d.drawLine(400, 1000, 400, 0);
g2d.drawLine(500, 1000, 500, 0);
g2d.drawLine(600, 1000, 600, 0);
g2d.drawLine(700, 1000, 700, 0);
g2d.drawLine(800, 1000, 800, 0);
g2d.drawLine(900, 1000, 900, 0);
g2d.drawLine(1000, 1000, 1000, 0);
// horizontal lines(A-J)
g2d.drawLine(0, 100, 1100,100);
g2d.drawLine(0, 200, 1100, 200);
g2d.drawLine(0, 300, 1100, 300);
g2d.drawLine(0, 400, 1100, 400);
g2d.drawLine(0, 500, 1100, 500);
g2d.drawLine(0, 600, 1100, 600);
g2d.drawLine(0, 700, 1100, 700);
g2d.drawLine(0, 800, 1100, 800);
g2d.drawLine(0, 900, 1100, 900);
Toolkit.getDefaultToolkit().sync();
}
public void actionPerformed(ActionEvent e) {
repaint();
}
/* private class TAdapter extends KeyAdapter {
public void keyReleased(KeyEvent e) {
.keyReleased(e);
}
public void keyPressed(KeyEvent e) {
.keyPressed(e);
}
*/
Firstly, I would advise against making your grid squares 100x100 pixels, as that would result in a grid that is 1000 x 1000, which is too tall for many screens. For your gid, consider using a GridLayout which each cell a JButton. Here is a demo to see how it may look:
public class GridTest extends JPanel implements ActionListener {
public static void main(String[] args) {
JFrame frame = new JFrame("Grid Test");
frame.add(new GridTest());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void init() {
GridLayout layout = new GridLayout(10, 10);
setLayout(layout);
for (char row = 'A'; row <= 'J'; row++) {
for (int col = 1; col <= 10; col++) {
JButton button = new JButton("" + row + col);
button.setMargin(new Insets(0, 0, 0, 0));
button.setPreferredSize(new Dimension(50, 50));
button.addActionListener(this);
add(button);
}
}
}
public GridTest() {
init();
}
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(this, String.format("You pressed %s!", e.getActionCommand()),
"You Pressed a Button", JOptionPane.INFORMATION_MESSAGE);
((JButton) e.getSource()).setEnabled(false);
}
}
I would recommend looking up Swing and looking to all the components to get an understanding of what each can do. Oracle's Tutorial is a good place to start
Related
I'm trying to make my own Java GUI project. I want to make the line's colors change when mouse pressed, but this doesn't work. I used 'for'loop and array for Colors but this doesn't run. So I'd like to ask you help me to solve it! Also, I wonder why loop needs for drawing lines on panel.
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GraphicEx extends JFrame {
private MyPanel panel = new MyPanel();
public GraphicEx(){
setTitle("Java Mondrian");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(panel);
setSize(400,220);
setVisible(true);
}
class MyPanel extends JPanel{
private Vector <Point> vStart = new Vector <Point>();
private Vector <Point> vEnd = new Vector <Point>();
Color [] c = {Color.BLUE, Color.RED, Color.YELLOW, Color.BLACK};
private int a;
MyPanel(){
setBackground(Color.WHITE);
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
Point startP = e.getPoint();
vStart.add(startP);
for(int i=0; i<c.length; i++) {
if (i== (c.length-1)){
i=0;
}
a = i;
}
}
I made this for Color Change, But this not work.
#Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
Point endP = e.getPoint();
vEnd.add(endP);
repaint();
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//component Color & Size
g.setColor(Color.BLACK);
g.drawRect(10,10,50,50);
g.setColor(Color.BLUE);
g.fillRect(60, 60, 100, 100);
g.setColor(Color.RED);
g.fillRect(50,50,20,20);
g.setColor(Color.YELLOW);
g.fillRect(130,50,50,50);
g.setColor(Color.RED);
g.drawRect(170,10,50,50);
g.setColor(Color.BLACK);
g.fillRect(210,50,80,50);
g.setColor(Color.YELLOW);
g.drawRect(260,30,40,170);
g.setColor(Color.RED);
g.fillRect(240,130,170,40);
g.setColor(new Color(0,0,0));
g.setFont(new Font("Arial",Font.ITALIC, 30));
g.drawString("Mondrian.2020", 100, 174);
g.setColor(new Color(0,210,200));
g.setFont(new Font("Arial",Font.BOLD,20));
g.drawString("Draw your own Picture", 70, 100);
g.setColor(new Color(0,0,0));
g.drawLine(20,20,350,20);
g.drawLine(35,0,35,180);
g.drawLine(20,160,350,160);
g.drawLine(330, 0, 330, 190);
int [] x = {80, 40, 80, 120};
int [] y = {40, 120, 200, 120};
g.drawPolygon(x,y,4);
g.setColor(Color.BLUE);
g.fillArc(290, 10, 50, 50, 90, 360);
for(int i=0; i<vStart.size();i++) {
Point s = vStart.elementAt(i);
Point e = vEnd.elementAt(i);
g.setColor(c[a]);
g.drawLine((int)s.getX(), (int)s.getY(), (int)e.getX(), (int)e.getY());
}
}
}
I cannot understand this part too! why I should use loop to draw lines?
public static void main(String[] args) {
new GraphicEx();
}
}
As there's only a limited supply of colors, and each line should have it's own, the modulo operator seems fitting:
//Make sure both vectors have that index!
for(int i=0; i< Math.min(vStart.size(), vEnd.size()); i++) {
Point s = vStart.elementAt(i);
Point e = vEnd.elementAt(i);
g.setColor(c[i % c.length]); //Use a calculated color using modulo length
g.drawLine((int)s.getX(), (int)s.getY(), (int)e.getX(), (int)e.getY());
}
Also it's not good to access elements that are not there (yet). Painting could happen at any time - so there might be start items with no end items.
If this works, you could get rid of the whole calculation of a as well.
I have such code, where I need to create some buttoms for customizing the square. It works, but after rolling up the frame the text field moves all over the frame and I don't know why. I mean when I execute the programm for first it's located in the right position that I mentioned using method setBounds(), but then it's located above the square. So how can I fix it?
import java.awt.*;
import java.awt.event.*;
import java.text.AttributedString;
import javax.swing.*;
import java.awt.font.TextAttribute;
public class Square extends JFrame implements ActionListener {
Button butt1 = new Button("Fill with yellow");
Button butt2 = new Button("Fill with red");
Button butt3 = new Button("Add label");
Button butt4 = new Button("");
Pan contentPane = new Pan();
public Square() {
super("Square");
this.setBounds(200, 100, 670, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().add(contentPane);
contentPane.setBounds(0, 0, 670, 275);
contentPane.setBackground(Color.BLACK);
add(butt1);
butt1.setBounds(25, 300, 190, 25);
butt1.addActionListener(this);
add(butt2);
butt2.setBounds(235, 300, 190, 25);
butt2.addActionListener(this);
butt3.setBounds(440, 300, 190, 25);
butt3.addActionListener(this);
add(butt3);
add(butt4);
}
#Override
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o == butt1) {
contentPane.draw(1);
}
else if (o == butt2) {
contentPane.draw(2);
}
else if (o == butt3) {
contentPane.draw(3);
}
}
public static void main(String[] args) {
Square w = new Square();
w.setVisible(true);
}
}
class Pan extends JPanel {
Graphics g;
Graphics2D g2;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GRAY);
g.drawRect(240, 70, 150, 150);
}
public void draw(int i) {
g = getGraphics();
super.paintComponent(g);
g2 = (Graphics2D) g.create();
switch(i) {
case 1: g2.setColor(Color.yellow);
g2.fillRect(240, 70, 150, 150);
break;
case 2: g2.setColor(Color.red);
g2.fillRect(240, 70, 150, 150);
break;
case 3:
g.setColor(Color.GRAY);
g.drawRect(240, 70, 150, 150);
JTextField text = new JTextField(25);
this.add(text);
Button add = new Button("Add");
add.setBounds(400, 230, 120, 25);
this.add(add);
text.setBounds(240, 230, 150, 25);
Font font = new Font("Veranda", Font.BOLD|Font.ITALIC, 24);
class AddButton extends JPanel implements ActionListener {
#Override
public void actionPerformed(ActionEvent ev) {
AttributedString label = new AttributedString(text.getText());
label.addAttribute(TextAttribute.FONT, font);
label.addAttribute(TextAttribute.FOREGROUND, Color.PINK);
g2.drawString(label.getIterator(), 240, 50);
}
}
AddButton listener = new AddButton();
add.addActionListener(listener);
break;
}
}
}
Okay lots of core issues and misunderstandings.
Swing uses layout managers. This is probably one of the first things you're butting heads again. Layout managers make decisions about how best to position components based on their individual algorithms.
Start by taking a look at Laying Out Components Within a Container for more details and make good use of them. GUIs are complex and dynamic things, with many factors going in to determining how components should be sized and positioned.
Painting. Another problem new developers have is understanding that they don't control the paint system. Swing uses a passive rendering system, which means it will paint when it feels its required.
You can provide hints when a new paint pass should be done by calling repaint, but it's up to the system to decide what and when something should be painted.
g = getGraphics(); is a bad idea on many levels. Apart from been able to return null, it's nothing more then a snapshot of the last paint pass and will be discarded when a new paint pass occurs.
Calling super.paintComponent(g); outside of a paint pass is also a bad idea. In fact, there should rarely ever be a need to call any of the paint methods directly.
This is NOT how custom painting should be done. Start by having a look at Performing Custom Painting and Painting in AWT and Swing for how painting works and how you should work with it
Also, mixing heavy weight (AWT) and light weight (Swing) components together is generally a bad idea should be avoid as much as possible.
Example...
So, I "hacked" you example into something a "little" more reasonable
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.font.TextAttribute;
import java.text.AttributedString;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Square extends JFrame implements ActionListener {
JButton butt1 = new JButton("Fill with yellow");
JButton butt2 = new JButton("Fill with red");
JButton butt3 = new JButton("Add label");
JButton butt4 = new JButton("");
Pan contentPane = new Pan();
public Square() {
super("Square");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().add(contentPane);
contentPane.setBackground(Color.BLACK);
JPanel actions = new JPanel();
actions.setBorder(new EmptyBorder(10, 10, 10, 10));
actions.add(butt1);
butt1.addActionListener(this);
actions.add(butt2);
butt2.addActionListener(this);
butt3.addActionListener(this);
actions.add(butt3);
// actions.add(butt4);
add(actions, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o == butt1) {
contentPane.draw(1);
} else if (o == butt2) {
contentPane.draw(2);
} else if (o == butt3) {
contentPane.draw(3);
}
}
public static void main(String[] args) {
Square w = new Square();
w.setVisible(true);
}
}
class Pan extends JPanel {
private int state = -1;
private String text = null;
public Pan() {
Font font = new Font("Veranda", Font.BOLD | Font.ITALIC, 24);
setFont(font);
setLayout(new GridBagLayout());
setBorder(new EmptyBorder(10, 10, 10, 10));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(670, 275);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(Color.GRAY);
g2.drawRect(240, 70, 150, 150);
switch (state) {
case 1:
g2.setColor(Color.yellow);
g2.fillRect(240, 70, 150, 150);
break;
case 2:
g2.setColor(Color.red);
g2.fillRect(240, 70, 150, 150);
break;
case 3:
g.setColor(Color.GRAY);
g.drawRect(240, 70, 150, 150);
break;
}
if (text != null) {
AttributedString label = new AttributedString(text);
label.addAttribute(TextAttribute.FONT, getFont());
label.addAttribute(TextAttribute.FOREGROUND, Color.PINK);
g2.drawString(label.getIterator(), 240, 50);
}
}
public void draw(int i) {
switch (i) {
case 3:
JTextField textField = new JTextField(25);
JButton add = new JButton("Add");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 1;
gbc.anchor = GridBagConstraints.SOUTH;
this.add(textField, gbc);
gbc.gridx++;
this.add(add, gbc);
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
text = textField.getText();
remove(textField);
remove(add);
revalidate();
repaint();
}
});
revalidate();
repaint();
break;
}
state = i;
repaint();
}
}
Your code is full of, what is commonly known as, "magic numbers". These are values whose meaning is unknown.
Run the code and try resizing the window and you will see what I mean. Instead, you should be relying on "known" values, like getWidth and getHeight to make better determinations about how you should render the output
I am trying to display a bunch of ImagePanels in a JScrollPane. The problem with this application is that every time a new row of panels enters the viewport the whole window freezes for a small amount of time. Once scrolled through to the end though, the window will not lag again.
What is the cause of this lagging and how can I prevent it from happening in the first place?
My guess is the panels don't get painted until they are scrolled to. So I tried to call repaint on them after adding them to the background but that didn't work :(
MainClass.java:
import javax.swing.SwingUtilities;
public class MainClass {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MainFrame frame = new MainFrame();
}
});
}
}
MainFrame.java:
import java.awt.*;
import javax.swing.*;
public class MainFrame extends JFrame {
private static final long serialVersionUID = -254980289568295701L;
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState(JFrame.MAXIMIZED_BOTH);
JPanel background = new JPanel();
JScrollPane scrollPane = new JScrollPane(background,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
ImagePanel ipanel;
background.setPreferredSize(new Dimension(this.getWidth(),
this.getHeight() + 3000));
scrollPane.setOpaque(false);
scrollPane.getViewport().setOpaque(false);
scrollPane.getVerticalScrollBar().setUnitIncrement(20);
add(scrollPane);
for (int i = 0; i < 40; i++) {
ipanel = new ImagePanel();
ipanel.setPreferredSize(new Dimension(300, 400));
ipanel.setSize(new Dimension(300, 400));
background.add(ipanel);
}
setVisible(true);
}
}
ImagePanel.java:
import java.awt.*;
import javax.swing.JPanel;
import java.awt.image.BufferedImage;
public class ImagePanel extends JPanel {
private static final long serialVersionUID = 1997246878999790104L;
private Image image;
private int width;
private int height;
public ImagePanel() {
width = 300;
height = 400;
BufferedImage bufferedImage = new BufferedImage(2000, 2000, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bufferedImage.createGraphics();
g2d.setColor(Color.white);
g2d.fillRect(0, 0, 2000, 2000);
g2d.setColor(Color.black);
g2d.fillOval(0, 0, 2000, 2000);
g2d.setColor(Color.yellow);
g2d.fillOval(1500, 300, 400, 400);
g2d.fillOval(1200, 600, 400, 400);
g2d.fillOval(900, 900, 400, 400);
g2d.fillOval(600, 1200, 400, 400);
g2d.fillOval(300, 1500, 400, 400);
g2d.dispose();
image = bufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
I changed your code to us a JLabel to display the image.
It takes longer to load, but the scrolling worked fine:
import java.awt.*;
import javax.swing.*;
import java.awt.image.BufferedImage;
//public class ImagePanel extends JPanel {
public class ImagePanel extends JLabel {
private static final long serialVersionUID = 1997246878999790104L;
private Image image;
private int width;
private int height;
public ImagePanel() {
width = 300;
height = 400;
BufferedImage bufferedImage = new BufferedImage(2000, 2000, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bufferedImage.createGraphics();
g2d.setColor(Color.white);
g2d.fillRect(0, 0, 2000, 2000);
g2d.setColor(Color.black);
g2d.fillOval(0, 0, 2000, 2000);
g2d.setColor(Color.yellow);
g2d.fillOval(1500, 300, 400, 400);
g2d.fillOval(1200, 600, 400, 400);
g2d.fillOval(900, 900, 400, 400);
g2d.fillOval(600, 1200, 400, 400);
g2d.fillOval(300, 1500, 400, 400);
g2d.dispose();
image = bufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
setIcon( new ImageIcon(image) );
}
// #Override
protected void xxxpaintComponent(Graphics g) {
super.paintComponent(g);
// g.drawImage(image, 0, 0, this);
g.drawImage(image, 0, 0, null);
}
}
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.
I've come across an issue when messing around with shapes.
I created a simple program with a slider with which you manipulate the size of an arc. The problem is that when I run it, the arc isn't painted to the screen. However, when I change the value of the slider, everything starts working perfectly. Any thoughts on what this might be caused by? Here's the code:
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import java.awt.*;
import java.awt.geom.*;
#SuppressWarnings("serial")
public class GraphicsTest2 extends JFrame implements ChangeListener { // START OF GraphicsTest2
private JPanel sliderPanel, thePanel;
private JSlider slider;
private DrawStuff draw;
public static void main(String[] args) { // START OF main
new GraphicsTest2();
} // END OF main
public GraphicsTest2() { // START OF CONSTRUCTOR
super("Graphics test 2");
this.setSize(500, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thePanel = new JPanel();
thePanel.setLayout(new BorderLayout(10, 10));
slider = new JSlider(JSlider.HORIZONTAL, 1, 360, 120);
slider.addChangeListener(this);
sliderPanel = new JPanel();
sliderPanel.add(slider, BorderLayout.CENTER);
draw = new DrawStuff();
thePanel.add(sliderPanel, BorderLayout.SOUTH);
thePanel.add(draw, BorderLayout.CENTER);
this.add(thePanel, BorderLayout.CENTER);
this.pack();
this.validate();
this.setVisible(true);
} // END OF CONSTRUCTOR
public void stateChanged(ChangeEvent e) { // START OF stateChanged
if(e.getSource() == slider) {
int size = slider.getValue();
draw.arc = new Arc2D.Double(draw.getWidth() / 2 - 50, draw.getHeight() / 2 - 50, 100, 100, 0, size, Arc2D.PIE);
this.repaint();
}
} // END OF stateChanged
private class DrawStuff extends JComponent { // START OF DrawStuff
Shape arc;
public void paintComponent(Graphics g) { // START OF paintComponent
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.GREEN);
g2.fill(arc);
} // END OF paintComponent
public DrawStuff() {
this.setPreferredSize(new Dimension(100, 140));
arc = new Arc2D.Double(this.getWidth() / 2 - 50, this.getHeight() / 2 - 50, 100, 100, 0, 120, Arc2D.PIE);
}
} // END OF DrawStuff
} // END OF GraphicsTest2
When you create your arc in the constructor of DrawStuff here:
arc = new Arc2D.Double(this.getWidth() / 2 - 50, this.getHeight() / 2 - 50, 100, 100, 0, 120, Arc2D.PIE);
this.getWidth() and this.getHeight() will give a result of 0 because the components are not sized yet. A simple fix would be to use the fixed size like this:
arc = new Arc2D.Double(210 / 2 - 50, 140 / 2 - 50, 100, 100, 0, 120, Arc2D.PIE);