I'm having trouble with my buttons. I know they're working because I've tested them out by exiting the problem through System.exit. Here is what my output looks like:
http://imgur.com/Ks7mIFa
When I click the close button, the handle on the switch should redraw to the other side and the close button should change to open. When I click the open button, it should do the opposite. However, the buttons aren't doing anything. What am I doing wrong?
public class ProgrammingAssignment2 {
public static void main(String[] args) {
boolean ison = false;
// Objects
Circuit circuitObject = new Circuit();
Controller controllerObject = new Controller();
Draw drawObject = new Draw();
AllListeners listenerObject = new AllListeners();
drawObject.window();
circuitObject.buttons(drawObject, ison);
controllerObject.openFile("Programming Assignment 2 Data.txt", drawObject);
}
}
Class circuit just creates the buttons
import javax.swing.JButton;
public class Circuit {
public void buttons(Draw drawObject, boolean ison) {
AllListeners listenerObject = new AllListeners();
if (ison == true) {
JButton openButton = new JButton("Close");
openButton.addActionListener(listenerObject);
openButton.setBounds(200, 100, 50, 20);
drawObject.add(openButton);
} else if (ison == false) {
JButton closeButton = new JButton("Open");
closeButton.addActionListener(listenerObject);
closeButton.setBounds(50, 100, 50, 20);
drawObject.add(closeButton);
}
}
}
Draw class does most of the work. It creates all the graphics and reads in a text file that has the titles of each object(like switch and lightbulb).
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JFrame;
import java.awt.Graphics;
public class Draw extends JFrame {
private String[] line = new String[5];
private int counter = 0;
private boolean ison;
public void window() {
setSize(500, 500);
setTitle("Programming Assignment 2");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void readFile(String filename) {
counter = 1;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
for (int i = 0; i < 4; i++) {
line[i] = br.readLine();
}
} catch (FileNotFoundException e) {
String error = "File was not found";
System.out.println(error.toString());
System.out.println("or could not be opened.");
} catch (IOException e) {
System.out.println("Error reading from file.");
} finally {
try {
br.close();
} catch (IOException e) {
System.out.println("Error closing file.");
}
}
}
public void paint(Graphics g) {
Circuit circuitObject = new Circuit();
super.paint(g);
if (ison == true) {
turnon(g);
circuitObject.buttons(this, ison);
} else {
turnoff(g);
}
}
public void setisOn() {
ison = true;
}
public void setisOff() {
ison = false;
}
public void turnoff(Graphics g) {
// Title
g.drawString(line[0], 150, 40);
//Switch
g.drawString(line[2], 130, 190);
g.drawRect(100, 150, 100, 20);
g.drawOval(115, 155, 10, 10);
g.drawOval(175, 155, 10, 10);
g.drawArc(140, 140, 20, 20, 180, -180);
//off switch
g.drawLine(160, 150, 182, 133);
g.drawLine(157, 142, 173, 128);
g.drawLine(173, 128, 182, 133);
//Power Supply
g.drawString(line[1], 50, 420);
g.drawRect(50, 320, 50, 80);
g.drawLine(50, 320, 70, 290);
g.drawLine(100, 320, 120, 290);
g.drawLine(70, 290, 120, 290);
g.drawLine(120, 370, 120, 290);
g.drawLine(120, 370, 100, 400);
//plus
g.drawLine(94, 310, 100, 310);
g.drawLine(97, 307, 97, 313);
// minus
g.drawLine(100, 300, 107, 300);
// pliers
g.drawRect(70, 305, 5, 10);
g.drawRect(90, 288, 5, 10);
//lightbulb
g.drawString(line[3], 400, 250);
g.drawRect(400, 200, 20, 20);
g.drawOval(395, 170, 30, 30);
// pliers
g.drawRect(400, 220, 5, 10);
g.drawRect(415, 220, 5, 10);
// plus wire to switch
g.drawLine(72, 305, 120, 160);
//bulb to switch
g.drawLine(180, 160, 400, 230);
//bulb to minus
g.drawLine(90, 290, 420, 230);
}
public void turnon(Graphics g) {
// Title
g.drawString(line[0], 150, 40);
//Switch
g.drawString(line[2], 130, 190);
g.drawRect(100, 150, 100, 20);
g.drawOval(115, 155, 10, 10);
g.drawOval(175, 155, 10, 10);
g.drawArc(140, 140, 20, 20, 180, -180);
//on switch
g.drawLine(140, 150, 122, 133);
g.drawLine(143, 142, 129, 128);
g.drawLine(122, 133, 129, 128);
//Power Supply
g.drawString(line[1], 50, 420);
g.drawRect(50, 320, 50, 80);
g.drawLine(50, 320, 70, 290);
g.drawLine(100, 320, 120, 290);
g.drawLine(70, 290, 120, 290);
g.drawLine(120, 370, 120, 290);
g.drawLine(120, 370, 100, 400);
//plus
g.drawLine(94, 310, 100, 310);
g.drawLine(97, 307, 97, 313);
// minus
g.drawLine(100, 300, 107, 300);
// pliers
g.drawRect(70, 305, 5, 10);
g.drawRect(90, 288, 5, 10);
//lightbulb
g.drawString(line[3], 400, 250);
g.drawRect(400, 200, 20, 20);
g.drawOval(395, 170, 30, 30);
// pliers
g.drawRect(400, 220, 5, 10);
g.drawRect(415, 220, 5, 10);
// plus wire to switch
g.drawLine(72, 305, 120, 160);
//bulb to switch
g.drawLine(180, 160, 400, 230);
//bulb to minus
g.drawLine(90, 290, 420, 230);
}
}
Controller doesn't do much right.
public class Controller {
public void openFile(String filename, Draw drawObject) {
drawObject.readFile(filename);
}
}
And this is the actionlisterner class
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AllListeners implements ActionListener {
public void actionPerformed(ActionEvent e) {
Circuit circuitObject = new Circuit();
Draw drawObject = new Draw();
String buttonString = e.getActionCommand();
if (buttonString.equals("Close")) {
drawObject.setisOn();
drawObject.repaint();
} else if (buttonString.equals("Open")) {
drawObject.setisOff();
drawObject.repaint();
} else {
System.out.println("Unexpected error.");
}
}
}
You've got lots of major problems with this code including:
Drawing directly within a JFrame's paint method, something fraught with problems as you risk messing up the JFrame's own complicated painting.
Placing program logic within a painting method, a method you don't have full control over when or if it fires, and one that you shouldn't slow down
Placing component creation code within a painting method.
Trying to add multiple JButtons willy nilly rather than changing the state of an existing component.
Creating multiple Circuit objects.
Trying to use absolute positioning via setBounds(...) to place a component in a container that uses BorderLayout.
I suggest that you
Start over and scrap this code.
Draw only in a JPanel's paintComponent method, just as the tutorials will tell you to do.
Create your buttons once and only once and add them to your GUI.
Get all program logic out of the painting (here paintComponent) method, and all object state changing outside of that method as they are for painting and painting only.
Instead the logic should belong to the controller, and which should be notified of the button push.
So consider having the button push notify the control what was pushed,
the control changes the state of the program (changes variables)
and then it calls repaint so that the paintComponent method can use those variables to change its drawing.
Also, avoid using setBounds and null layouts if at all possible, and instead use layout managers/borders/nested JPanels to help you place your components.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
i'm currently adding functionality and completing a Hang-Man game my programing teacher made.
The following error message: Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: index 0, length 0 with the index changing for everyindex in a String builder. is appearing everytime i input a letter that is correctly guessed in the game.
I have tried for a while to fix it but i have yet to be able to.
package hangManSo;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Arrays;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class HangManSO extends JPanel implements ActionListener, MouseListener {
private int error;
JButton button;
JTextField field;
JFrame frame;
JLabel rättord;
HangManSO(JButton button, JTextField field, JFrame frame, JLabel rättord) {
this.button = button;
this.field = field;
this.frame = frame;
this.rättord = rättord;
this.addMouseListener(this);
}
static String [] ord = {"rome"};
static Random r = new Random();
static int randomNumber=r.nextInt(ord.length);
static String d = ord[randomNumber];
StringBuilder builder = new StringBuilder(d.length());
StringBuilder builderDisplay = new StringBuilder();
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
String guessedletter = field.getText();
if (source.equals(button)) {
if (!d.contains(guessedletter)) {
error++;
frame.repaint();
}
if (d.contains(guessedletter)) {
char [] randomWord = d.toCharArray();
char CharGuessedLetter = guessedletter.charAt(0);
//gets the index of the guessed letter in the randomword
builder.append(randomWord);
int index = builder.indexOf(String.valueOf(CharGuessedLetter));
//is supposed to set the correctly guessed letter in the correct index
builderDisplay.setCharAt(index, CharGuessedLetter);
rättord.setText(builderDisplay.toString());
}
field.setText("");
}
}
public void paintComponent(Graphics g ) {
super.paintComponent(g);
if (error == 1)
g.drawLine(10, 270, 500, 270);
if (error == 2) {
g.drawLine(10, 270, 500, 270);
g.drawLine(200, 30, 200, 270);
}
if (error == 3) {
g.drawLine(10, 270, 500, 270);
g.drawLine(200, 30, 200, 270);
g.drawLine(200, 30, 350, 30);
}
if (error == 4) {
g.drawLine(10, 270, 500, 270);
g.drawLine(200, 30, 200, 270);
g.drawLine(200, 30, 350, 30);
g.drawLine(200, 30, 350, 30);
g.drawLine(250, 30, 200, 75);
}
if (error == 5) {
g.drawLine(10, 270, 500, 270);
g.drawLine(200, 30, 200, 270);
g.drawLine(200, 30, 350, 30);
g.drawLine(200, 30, 350, 30);
g.drawLine(250, 30, 200, 75);
g.drawLine(350, 30, 350,100);
}
if (error == 6) {
g.drawLine(10, 270, 500, 270);
g.drawLine(200, 30, 200, 270);
g.drawLine(200, 30, 350, 30);
g.drawLine(200, 30, 350, 30);
g.drawLine(250, 30, 200, 75);
g.drawLine(350, 30, 350,100);
g.drawOval(330, 100, 40, 40);
}
if (error == 7) {
g.drawLine(10, 270, 500, 270);
g.drawLine(200, 30, 200, 270);
g.drawLine(200, 30, 350, 30);
g.drawLine(200, 30, 350, 30);
g.drawLine(250, 30, 200, 75);
g.drawLine(350, 30, 350,100);
g.drawOval(330, 100, 40, 40);
g.drawLine(350, 140, 350,200);
}
if (error == 8) {
g.drawLine(10, 270, 500, 270);
g.drawLine(200, 30, 200, 270);
g.drawLine(200, 30, 350, 30);
g.drawLine(200, 30, 350, 30);
g.drawLine(250, 30, 200, 75);
g.drawLine(350, 30, 350,100);
g.drawOval(330, 100, 40, 40);
g.drawLine(350, 140, 350,200);
g.drawLine(350, 200,390, 240);
}
if (error == 9) {
g.drawLine(10, 270, 500, 270);
g.drawLine(200, 30, 200, 270);
g.drawLine(200, 30, 350, 30);
g.drawLine(200, 30, 350, 30);
g.drawLine(250, 30, 200, 75);
g.drawLine(350, 30, 350,100);
g.drawOval(330, 100, 40, 40);
g.drawLine(350, 140, 350,200);
g.drawLine(350, 200,390, 240);
g.drawLine(350, 200, 310, 240);
}
if (error == 9) {
g.drawLine(10, 270, 500, 270);
g.drawLine(200, 30, 200, 270);
g.drawLine(200, 30, 350, 30);
g.drawLine(200, 30, 350, 30);
g.drawLine(250, 30, 200, 75);
g.drawLine(350, 30, 350,100);
g.drawOval(330, 100, 40, 40);
g.drawLine(350, 140, 350,200);
g.drawLine(350, 200,390, 240);
g.drawLine(350, 200, 310, 240);
}
if (error == 10) {
g.drawLine(10, 270, 500, 270);
g.drawLine(200, 30, 200, 270);
g.drawLine(200, 30, 350, 30);
g.drawLine(200, 30, 350, 30);
g.drawLine(250, 30, 200, 75);
g.drawLine(350, 30, 350,100);
g.drawOval(330, 100, 40, 40);
g.drawLine(350, 140, 350,200);
g.drawLine(350, 200,390, 240);
g.drawLine(350, 200, 310, 240);
g.drawLine(350, 170, 400, 150);
}
if (error == 11) {
g.drawLine(10, 270, 500, 270);
g.drawLine(200, 30, 200, 270);
g.drawLine(200, 30, 350, 30);
g.drawLine(200, 30, 350, 30);
g.drawLine(250, 30, 200, 75);
g.drawLine(350, 30, 350,100);
g.drawOval(330, 100, 40, 40);
g.drawLine(350, 140, 350,200);
g.drawLine(350, 200,390, 240);
g.drawLine(350, 200, 310, 240);
g.drawLine(350, 170, 400, 150);
g.drawLine(350, 170, 300, 150);
}
if(error > 11) {
g.setFont(new Font("Calibri", Font.BOLD, 26));
g.drawString("GAME OVER", 225, 150);
}
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("HangMan");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel rubrikOrd = new JLabel("rätt gissade ord");
rubrikOrd.setOpaque(false);
rubrikOrd.setBackground(Color.GREEN);
rubrikOrd.setBounds(10, 10, 100, 20);
JLabel rättord = new JLabel();
rättord.setOpaque(true);
rättord.setBackground(Color.GREEN);
rättord.setBounds(10, 35, 100, 20);
JTextField field = new JTextField();
field.setVisible(true);
JButton b = new JButton("ok");
b.setBounds(370, 300, 100, 30);
frame.add(b);
field.setSize(300, 30);
field.setLocation(60, 300);
field.setVisible(true);
frame.add(field);
frame.add(rättord);
frame.add(rubrikOrd);
frame.setBackground(Color.white);
frame.setSize(600, 400);
HangManSO object = new HangManSO(b, field, frame, rättord);
b.addActionListener(object);
field.addActionListener(object);
frame.add(object);
frame.setVisible(true);
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getX() + " " + e.getY());
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
The code is needlessly complex and that is making it hard for you to see the issue.
Your actual issue starts on this line where you assign the entire correct word d to randomWord:
char [] randomWord = d.toCharArray();
//randomWord now equals `{r,o,m,e}`
You then use the entire correct word and append it to your builder string:
//builder equals a blank string of 4 characters " "
builder.append(randomWord);
//builder now equals a string with 4 blank characters followed by some " rome"
System.out.print(builder.toString());
So now when you try to get the index of your letter for example if you guessed 'm' it will return a large index:
//the builder string now " rome"
int index = builder.indexOf(String.valueOf(CharGuessedLetter));
//So `m` will be found at the 6th index of " rome"
System.out.print("index = " + index);
So when you use the next line with an index of 6 it will be out of bounds because the builderDisplay String is only 4 characters long for the word rome:
builderDisplay.setCharAt(index, CharGuessedLetter);
So what can you do to fix this? I won't give you an exact answer, but You should start by thinking about the above code, and where it goes wrong (append), and how you can return the correct character index (using the d string)
Final hint, the following line would get a correct character index of a character, note how we use the d string, not the builder string:
int index = d.indexOf(String.valueOf(CharGuessedLetter));
Edit:
Following on from comments. You also need to fill the string builder with blanks to avoid this issue:
//Create the hangman object
HangManSO object = new HangManSO(b, field, frame, rättord);
//Now populate the string builder with empty characters "_" or you could use a space " "
for (int i = 0; i < object.d.length(); i++) {
object.builderDisplay.append('_');
}
Note also that you should check for duplicate characters in your word:
//check against every letter of the word to make sure that it gets duplicate characters
for (int i = 0; i < d.length(); i++) {
if (d.charAt(i) == charGuessedLetter){
builderDisplay.setCharAt(i, charGuessedLetter);
System.out.println("Match found");
}
}
rättord.setText(builderDisplay.toString());
I am trying to start the program with jcheckbox hat selected and rectangle visible then the Rectangle disappears when the checkbox is unselected and repainted as checkbox is selected again. When I run the program and check the box another check box appears or left of the frame.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
public class Head extends JPanel {
JCheckBox hat;
public Head() {
hat = new JCheckBox("Hat");
hat.setSelected(true);
hat.addItemListener(new CheckSelection());
add(hat);
}
class CheckSelection implements ItemListener {
public void itemStateChanged(ItemEvent ie) {
repaint();
}
}
public void paintComponent(Graphics g) {
setForeground(Color.RED);
g.drawOval(110, 100, 100, 100);
g.drawOval(130, 120, 20, 15);
g.drawOval(170, 120, 20, 15);
g.drawLine(160, 130, 160, 160);
g.drawOval(140, 170, 40, 15);
if (hat.isSelected()) {
g.drawRect(100, 90, 120, 10);
}
}
public static void main(String[] args) {
Head head = new Head();
JFrame f = new JFrame();
f.add(head);
f.setSize(400, 400);
//f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
You've broken the paint chain by not calling the paintComponent's super method
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
setForeground(Color.RED);
g.drawOval(110, 100, 100, 100);
g.drawOval(130, 120, 20, 15);
g.drawOval(170, 120, 20, 15);
g.drawLine(160, 130, 160, 160);
g.drawOval(140, 170, 40, 15);
if (hat.isSelected()) {
g.drawRect(100, 90, 120, 10);
} else {
setForeground(Color.RED);
g.drawOval(110, 100, 100, 100);
g.drawOval(130, 120, 20, 15);
g.drawOval(170, 120, 20, 15);
g.drawLine(160, 130, 160, 160);
g.drawOval(140, 170, 40, 15);
}
}
The Graphics context is a shared resource between components, one of the jobs of paintComponent is to prepare the Graphics for painting, typically by filling it with the background color of the component. So failing to call super.paintComponent means that what ever was previously painted to the Graphics context will still be there
See Painting in AWT and Swing and Performing Custom Painting for more details about how painting works in Swing
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
This Friday I need to hand in my Java project – I've only been programming for about two weeks now – and I really want to add a PNG file to my JPanel. Below you find my code, the name of the image is java.png, I put it in the same folder as my src files. I just can't find a good tutorial on how to do this. Please help me!
Note: the image should be inserted in the booOpAfbeam structure almost at the bottom of the code, and also sorry for this unorganized message, I have no clue how to post my code decently.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.ImageObserver;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.Image;
import java.awt.Dimension;
import javax.swing.*;
public class Project extends JPanel {
private JLabel invoerLabel, invoerKleur, invoerKleur2, invoerBril, invoerBril2;
private JTextField invoerAantal, invoerK, invoerB;
private int intAantal;
private String strKleur="";
private String strBril="";
private JButton knop, knopBril, btnOpAf, btnOpAfbeam;
private Boolean booOpAf = false, booOpAfbeam = false;
private Image image1;
public Project(){
setLayout(null);
invoerLabel = new JLabel("Voer aantal stoelen in: ");
invoerAantal = new JTextField (10);
invoerKleur = new JLabel("Voer kleur stoel in: ");
invoerKleur2 = new JLabel("(blauw, rood, groen, paars, roos, zwart, geel, oranje)");
invoerK = new JTextField (10);
invoerBril = new JLabel("Voer kleur bril in: ");
invoerBril2 = new JLabel("(blauw, rood, groen, paars, roos, zwart, geel, oranje)");
invoerB = new JTextField (10);
knopBril = new JButton ("ok");
knop = new JButton("ok");
btnOpAf = new JButton ("Wijs/Wijs niet");
btnOpAfbeam = new JButton ("aan/uit");
knop.addActionListener (new InvoervakHandler());
knopBril.addActionListener(new InvoervakHandler2());
btnOpAf.addActionListener(new aanuit());
btnOpAfbeam.addActionListener(new beam());
invoerLabel.setBounds(1000, 10, 150, 20);
invoerAantal.setBounds(1150, 10, 60, 20);
invoerKleur.setBounds(1000, 70, 120, 20);
invoerKleur2.setBounds(985, 90, 300, 20);
invoerK.setBounds(1150, 70, 60, 20);
knop.setBounds(1155, 120, 50, 20);
invoerBril.setBounds(1000, 170, 150, 20);
invoerBril2.setBounds(985, 195, 300, 20);
invoerB.setBounds(1150, 170, 60, 20);
knopBril.setBounds(1155, 220, 50, 20);
btnOpAf.setBounds(1000,275,115,20);
btnOpAfbeam.setBounds(365, 26, 75, 20);
add(invoerLabel);
add(invoerAantal);
add(invoerKleur);
add(invoerKleur2);
add(invoerK);
add(invoerBril);
add(invoerBril2);
add(invoerB);
add(knop);
add(knopBril);
add(btnOpAf);
add(btnOpAfbeam);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
ImageIcon i = new ImageIcon("java.png");
image1 = i.getImage();
g.drawImage(image1, 0, 0, null);
ImageIcon("java.png");
//labels//
invoerBril2.setForeground(new Color(0,173,173));
invoerKleur2.setForeground(new Color(0,173,173));
invoerLabel.setForeground(new Color(227,227,227));
invoerKleur.setForeground(new Color(227,227,227));
invoerBril.setForeground(new Color(227,227,227));
//vloer
g.setColor(new Color(102,77,51));
g.fillRect(0, 375, 1000, 200);
//muur
g.setColor(new Color(99,136,176));
g.fillRect(0, 0, 1000, 400);
//achtergrond kleur balk//
g.setColor(new Color(0,102,53));
g.fillRect(980, 0, 386, 766);
//beamer
g.setColor(new Color(122,122,122));
g.fillRect(355,20,100,30);
g.fillRect(397,0,15,40);
g.setColor(Color.BLACK);
g.fillRect(355, 20, 100, 3);
g.fillRect(355, 50, 100, 3);
g.fillRect(352, 20, 3, 33);
g.fillRect(452, 20, 3, 33);
g.fillRect(410, 0, 3, 20);
g.fillRect(395, 0, 3, 20);
//bord
g.setColor(new Color(98,121,74));
g.fillRect(250, 100,300 , 200);
g.setColor(Color.BLACK);
g.fillRect(250, 300,300 , 10);
g.fillRect(250, 100,300 , 10);
g.fillRect(250, 100,10 , 200);
g.fillRect(550, 100,10 , 210);
//boekenkast horizontale balken
g.setColor(Color.BLACK);
g.fillRect(50, 160, 30, 250);
g.fillRect(200, 160, 30, 250);
//boekenkast verticale balken
g.fillRect(50, 160, 150, 20);
g.fillRect(50, 220, 150, 20);
g.fillRect(50, 280, 150, 20);
g.fillRect(50, 340, 150, 20);
//boekenkast boeken rij 1
g.setColor(new Color(204,0,0));
g.fillRect(80, 180, 20, 40);
g.setColor(new Color(0,204,102));
g.fillRect(110, 180, 20, 40);
g.setColor(new Color(204,102,0));
g.fillRect(140, 180, 20, 40);
g.setColor(new Color(204,204,0));
g.fillRect(170, 180, 20, 40);
//boekenkast boeken rij 2
g.setColor(new Color(0,204,102));
g.fillRect(80, 240, 20, 40);
g.setColor(new Color(204,0,0));
g.fillRect(110, 240, 20, 40);
g.setColor(new Color(204,102,0));
g.fillRect(140, 240, 20, 40);
g.setColor(new Color(204,204,0));
g.fillRect(170, 240, 20, 40);
//boekenkast boeken rij 3
g.setColor(new Color(204,0,0));
g.fillRect(80, 300, 20, 40);
g.setColor(new Color(204,102,0));
g.fillRect(110, 300, 20, 40);
g.setColor(new Color(204,204,0));
g.fillRect(140, 300, 20, 40);
g.setColor(new Color(0,204,102));
g.fillRect(170, 300, 20, 40);
//boeklabels
g.setColor(new Color(224,224,224));
g.fillRect(85,190,10,20);
g.fillRect(115,190,10,20);
g.fillRect(145,190,10,20);
g.fillRect(175,190,10,20);
g.fillRect(85,250,10,20);
g.fillRect(115,250,10,20);
g.fillRect(145,250,10,20);
g.fillRect(175,250,10,20);
g.fillRect(85,310,10,20);
g.fillRect(115,310,10,20);
g.fillRect(145,310,10,20);
g.fillRect(175,310,10,20);
//hoofd//
g.setColor(new Color(255,237,184));
g.fillOval(615,170,150,150);
g.setColor(new Color(255,255,255));
g.fillOval(645,220,25,25);
g.fillOval(715,220,25,25);
g.setColor(new Color(0,0,0));
g.fillOval(655,230,10,10);
g.fillOval(725,230,10,10);
g.drawArc(675,240,40,40,0,-180);
g.drawArc(635,250,115,50,0,-180);
//lichaam
g.setColor(new Color(153,153,0));
g.fillRect(650, 300, 100, 125);
g.setColor(Color.BLACK);
g.fillRect(650, 430, 25, 60);
g.fillRect(730, 430, 25, 60);
g.fillRect(650, 420, 100, 15);
g.setColor(Color.BLUE);
g.fillOval(632, 470, 45, 25);
g.fillOval(725, 470, 45, 25);
// bureau
g.setColor(new Color(184, 184, 184));
g.fillRect(540, 410, 325, 20);
g.fillRect(540, 430, 20, 60);
g.fillRect(845, 430, 20, 60);
//vingers
g.setColor(new Color(255,237,184));
g.fillOval(785, 375, 10, 25);
g.fillOval(775, 375, 10, 25);
g.fillOval(765, 375, 10, 25);
g.fillOval(755, 375, 10, 25);
//pc
g.setColor(Color.BLACK);
g.fillRect(650, 280, 175, 100);
g.fillRect(676, 400, 125, 10);
g.fillRect(730, 375, 15, 30);
//
g.setColor(new Color(184, 184, 184));
g.fillRect(660, 320, 20, 5);
g.fillRect(660, 340, 20, 5);
g.fillRect(795, 320, 20, 5);
g.fillRect(795, 340, 20, 5);
//apple
g.fillOval(725, 320, 20, 20);
g.fillOval(732, 310, 5, 10);
g.setColor(Color.BLACK);
g.fillOval(735, 325, 10, 10);
if(strBril.equals("blauw")) {
g.setColor(Color.BLUE);
}
if(strBril.equals("rood")) {
g.setColor(Color.RED);
}
if(strBril.equals("groen")) {
g.setColor(Color.GREEN);
}
if(strBril.equals("paars")) {
g.setColor(new Color(204,51,255));
}
if(strBril.equals("roos")) {
g.setColor(new Color(255,51,204));
}
if(strBril.equals("zwart")) {
g.setColor(Color.BLACK);
}
if(strBril.equals("geel")) {
g.setColor(Color.YELLOW);
}
if(strBril.equals("oranje")) {
g.setColor(Color.ORANGE);
}{
//bril//
//linkerglas
g.fillRect(600,200,80,5);
g.fillRect(600,200,5,50);
g.fillRect(600,250,80,5);
g.fillRect(680,200,5,55);
//tussenbeentje//
g.fillRect(680,225,20,10);
//rechterglas
g.fillRect(700,200,80,5);
g.fillRect(700,200,5,50);
g.fillRect(700,250,80,5);
g.fillRect(780,200,5,55);
}
int teller1;
if(strKleur.equals("blauw")) {
g.setColor(Color.BLUE);
}
if(strKleur.equals("rood")) {
g.setColor(Color.RED);
}
if(strKleur.equals("groen")) {
g.setColor(Color.GREEN);
}
if(strKleur.equals("paars")) {
g.setColor(new Color(204,51,255));
}
if(strKleur.equals("roos")) {
g.setColor(new Color(255,51,204));
}
if(strKleur.equals("zwart")) {
g.setColor(Color.BLACK);
}
if(strKleur.equals("geel")) {
g.setColor(Color.YELLOW);
}
if(strKleur.equals("oranje")) {
g.setColor(Color.ORANGE);
}
int Ra = 20;
int Rb = 20;
int Rc = 40;
int Rd = 20;
for (teller1=1; teller1 <= intAantal; teller1++) {
g.fillRect(Ra,450,10,50);
g.fillRect(Rb,500,50,10);
g.fillRect(Rc,500,10,30);
g.fillRect(Rd,530,50,10);
Ra = Ra + 70;
Rb = Rb + 70;
Rc = Rc + 70;
Rd = Rd + 70;
}
if (booOpAf) {
if (!booOpAf) {
g.setColor(new Color(153,153,0));
g.fillRect(625, 300, 30, 100);
} else {
//arm
g.setColor(new Color(153,153,0));
g.fillRect(550, 315, 100, 25);
//linkerarm vingers
g.setColor(new Color(255,237,184));
g.fillOval(530, 310, 30, 30);
g.fillOval(515, 310, 25, 10);
g.fillOval(515, 320, 25, 10);
g.fillOval(515, 330, 25, 10);
g.fillOval(545, 300, 10, 25);
}
}
if (booOpAfbeam) {
if (!booOpAfbeam) {
} else {
g.drawImage(image1, 500, 100, null);
}
}
}
private void ImageIcon(String string) {
// TODO Auto-generated method stub
}
class InvoervakHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String strAantal = invoerAantal.getText();
intAantal = Integer.parseInt(strAantal);
strKleur= invoerK.getText();
repaint();
}
}
class InvoervakHandler2 implements ActionListener {
public void actionPerformed(ActionEvent f){
strBril= invoerB.getText();
repaint();
}
}
public class aanuit implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
if (booOpAf == true) {
booOpAf = false;
} else {
booOpAf = true;
}
repaint();
}
}
public class beam implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
if (booOpAfbeam == true) {
booOpAfbeam = false;
} else {
booOpAfbeam = true;
}
repaint();
}
}
}
I cant verify your complete code. so better ensure that u have imported the image to the project(else u wont get the image if the image is not in the location specified). and also check if the image is in the src, u need to specify "/" and the image name. to locate the image.
I suggest the best way is to create a label,the right click and take the property of the image and select the image which u wants to display. rest of the codes netbeans will take care of.
Sorry if i made any mistake.
Try this:
Add another panel and then upload image on that panel.
lblImage = new javax.swing.JLabel();
lblImage.setIcon(new javax.swing.ImageIcon("E:..path...png));
I don't know why but nothing is appearing?
I suppose to have a applet of a house.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.*;
public class color extends JApplet
{
public void init()
{
addMouseListener(new MyMouseListener());
getContentPane().setBackground(Color.white);
}
public class MyMouseListener implements MouseListener
{
public void mouseClicked(MouseEvent e)
{
int x = e.getX();
int y = e.getY();
boolean closeDoors = true;
if(x>330 && x<280 && y>20 && y<20)
{
closeDoors = false;
repaint();
}
}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
}
public void paint ( Graphics g, boolean closeDoors)
{
super.paint (g);
do
{
g.drawLine (35, 50, 570, 50);
g.drawLine (35, 50, 250, 0);
g.drawLine (250, 0, 570, 50);
g.drawRect (50, 50, 500, 350);
g.fillRect (100, 75, 80, 80);
g.fillRect (400, 75, 80, 80);
g.fillRect (240, 200, 125, 200);
}
while (closeDoors = true);
if (closeDoors = false);
{
g.drawLine (35, 50, 570, 50);
g.drawLine (35, 50, 250, 0);
g.drawLine (250, 0, 570, 50);
g.drawLine (180, 120, 100, 120);
g.drawLine (400, 120, 480, 120);
g.drawLine (140, 75, 140, 160);
g.drawLine (450, 75, 450, 160);
g.drawRect (50, 50, 500, 350);
g.drawRect (100, 75, 80, 80);
g.drawRect (400, 75, 80, 80);
g.drawRect (240, 200, 125, 200);
g.drawOval (330,280, 20, 20);
}
}
}
You are probably looping inside the paint method. It seems like an infinite loop there.
do
{
g.drawLine (35, 50, 570, 50);
g.drawLine (35, 50, 250, 0);
g.drawLine (250, 0, 570, 50);
g.drawRect (50, 50, 500, 350);
g.fillRect (100, 75, 80, 80);
g.fillRect (400, 75, 80, 80);
g.fillRect (240, 200, 125, 200);
} while (closeDoors = true);
I would replace this with:
if (closeDoors = true)
{
g.drawLine (35, 50, 570, 50);
g.drawLine (35, 50, 250, 0);
g.drawLine (250, 0, 570, 50);
g.drawRect (50, 50, 500, 350);
g.fillRect (100, 75, 80, 80);
g.fillRect (400, 75, 80, 80);
g.fillRect (240, 200, 125, 200);
}
I'll try to help get you on the right track :-)
You may already know this, but if your not using an IDE, I recommend using appletviewer to develop your applets instead of with a browser. Just food for thought :-)
First of all, Toader Mihai Claudiu's suggestion is correct. Change
do
{
g.drawLine (35, 50, 570, 50);
g.drawLine (35, 50, 250, 0);
g.drawLine (250, 0, 570, 50);
g.drawRect (50, 50, 500, 350);
g.fillRect (100, 75, 80, 80);
g.fillRect (400, 75, 80, 80);
g.fillRect (240, 200, 125, 200);
}
while (closeDoors = true);
if (closeDoors = false);
{
into
if (closeDoors)
{
g.drawLine (35, 50, 570, 50);
g.drawLine (35, 50, 250, 0);
g.drawLine (250, 0, 570, 50);
g.drawRect (50, 50, 500, 350);
g.fillRect (100, 75, 80, 80);
g.fillRect (400, 75, 80, 80);
g.fillRect (240, 200, 125, 200);
}
else
{
Otherwise, you're going to be painting as long as closeDoors is true. You just need to paint once. Java will ask you to paint again when it has to (for instance, when you call repaint()).
Also, set closeDoors as a member variable. In other words, have:
public class color extends JApplet
{
public boolean closeDoors = false;
And when you switch the value of closeDoors in the click listener, you can simplify it as:
int x = e.getX();
int y = e.getY();
if(x>330 && x<280 && y>20 && y<20)
{
closeDoors = !closeDoors;
repaint();
}
That will, when you click in your specific area, invert the value of closeDoors. In other words, if closeDoors is true, it will be set to false, and vice versa.
Note, your code if(x>330 && x<280 && y>20 && y<20) probably won't work at all, since y cannot be greater than 20 and less than 20 at the same time, ever. I'll let you play with that to figure out what works :-).
Hope this helps.
Just a minor detail, but you should probably call your class Color instead of color to follow Java's standard naming convention, or call it something else if you don't want to clash with java.awt.Color.
Generally, in Swing you should never override the paint() method but instead paintComponent. (I'm not sure about JApplet, though - I would paint instead on a JPanel inside the applet, not the applet itself.)
And no endless loop in your paint-method - it should return quickly, not work eternally, as the Toader already said.
But this is not your problem, seemingly, as you wrote in a comment:
I get Applet not initializing
Add such (important!) information to the question (it has an edit link for a reason, you know).
Your browser should have a Java console somewhere, use it, and look whether there is some error message. Copy this (including the stacktrace, if any) to your question. This could enable us helping you.
(If you are using OpenJDK with the icedTea-Plugin on Linux, look at ~/.icedteaplugin/java.stderr and ~/.icedteaplugin/java.stdout instead, they didn't yet implement the Java console.)
One more problem. You are overloading not actually overriding paint (or paintComponent). Add #Override and the compiler will tell you of your mistake:
#Override public void paint(Graphics g, boolean closeDoors) { // wont compile
Seems like you need a course in debugging. At the very least put some System.err.printlns in and check the Java Console.