1

Okay so I am programming a GUI using java swing and I have been using some old code that I used to create a moving square, but now I have to use toggle buttons to make some shapes appear and disappear from the window. My program is supposed to have 4 different toggle buttons(have 3 at the moment) and each will have a specific purpose: Name will display my name in the center of the screen, rectangle will display a rectangle on the bottom right of the screen, and oval will display an oval on the bottom right also. I have tried to use a series of Boolean in order to dictate which shape appears, but for some reason each button will only toggle the rectangle and i dont know why. Is there something I am doing wrong that causes all the buttons to do the same thing? here is my code so far. First one is my paintPanel:

 import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class PaintPanel extends JPanel
{
    private static Color[] colors =
        { Color.RED, Color.BLACK, Color.PINK, Color.ORANGE };
    private int colorNumber = 0;

    private int shape = 0;

    private int x = 0;
    private int y = 0;

    private int width = 100;
    private int height = 100;
    private String display = " ";
    private String none = " ";

    private int dx = 2;
    private int dy = 2;

    private boolean rectangle = true;
    private boolean oval= true;
    private boolean Name = true;
    private boolean special = true;

    private String displayString = "hello";

    private boolean isStarted = true;

    /*public void update()
    {
        if (isStarted) 
        {
            x += dx;
            y += dy;
        }
        //dx ++;
        //dy ++;

        if (y + height > getHeight())
        {
            dy = -Math.abs(dy);
            shape++;
            colorNumber = (colorNumber+1)%colors.length;
        }
        else if (y < 0)
        {
            dy = Math.abs(dy);
            shape++;
            colorNumber = (colorNumber+1)%colors.length;
        }

        if (x + width > getWidth())
        {
            dx = -Math.abs(dx);
            shape++;
            colorNumber = (colorNumber+1)%colors.length;
        }
        else if (x < 0)
        {
            dx = Math.abs(dx);
            shape++;
            colorNumber = (colorNumber+1)%colors.length;
        }

    }*/
    public void input()
    {
        System.out.print("Button");
    }

    public void changeColor()
    {
        colorNumber = (colorNumber+1) % colors.length;
    }

    /*public void startStop()
    {
        //if (isStarted == true) isStarted = false;
        //else isStarted = true;

        isStarted = !isStarted;
    }
    */

    public void setDisplayText(String dt)
    {
        displayString = dt;
    }


    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        int w = getWidth();
        int h = getHeight();

        int textx = x+w/2;
        int texty = y+h/2;

            FontMetrics fm = g.getFontMetrics();
            int texth = fm.getHeight();
            int textw = fm.stringWidth(display);

            textx -= textw/2;
            texty += texth/2;
            texty -= 5; 
        if(Name == true)
        {
            g.setColor(Color.BLACK);
            g.drawString(display, textx, texty);
            Name = false;
        }
        else if(Name == false)
        {
            g.drawString(none, textx, texty);
            Name = true;
        }
        if (oval == true)
        {
            g.setColor(Color.CYAN);
            g.fillOval((5*w)/8, (5*h)/8, w/4, h/4);
            oval = false;
        }
        else if(oval == false)
        {
            g.setColor(Color.WHITE);
            g.fillOval((5*w)/8, (5*h)/8, w/4, h/4);
            oval = true;
        }
        if(rectangle == true)
        {
            g.setColor(Color.PINK);
            g.fillRect(w/2, h/2, w/2, h/2);
            rectangle = false;

        }
        else if(rectangle == false)
        {
            g.setColor(Color.WHITE);
            g.fillRect(w/2, h/2, w/2, h/2);
            rectangle = true;
        }



        /*int w = getWidth();
        int h = getHeight();
        g.setColor(colors[colorNumber]);
        if (shape % 2 == 0) //g.fillOval(x, y, width, height);
        elseg.fillRect(x,y, width, height);
        */ 
        /*
        int textx = x+width/2;
        int texty = y+height/2;

        FontMetrics fm = g.getFontMetrics();
        int texth = fm.getHeight();
        int textw = fm.stringWidth(displayString);

        textx -= textw/2;
        texty += texth/2;
        texty -= 5;     

        g.setColor(colors[(colorNumber+1)%colors.length]);
        g.drawString(displayString, textx, texty);
        */
    }

}

Whatever is commented out is because it will be implemented later for a special button. And here is my main class:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GuiTest extends JFrame 
    implements ActionListener
{
    private Timer frameTimer;
    private JToggleButton Name;
    private JToggleButton oval;
    private JToggleButton rectangle;
    //private JTextField theText;
    private PaintPanel paintPanel;

    public GuiTest()
    {
        setTitle("Servando Hernandez");
        setSize(500,500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel topPanel = new JPanel();
        topPanel.setLayout(new GridLayout(1,4));

        Name = new JToggleButton("Name");
        Name.addActionListener(this);

        oval = new JToggleButton("Oval");
        oval.addActionListener(this);

        rectangle = new JToggleButton("Rectangle");
        rectangle.addActionListener(this);

        //theText = new JTextField("HI");
        //theText.addActionListener(this);


        topPanel.add(Name);
        topPanel.add(oval);
        topPanel.add(rectangle);
        //topPanel.add(theText);

        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());
        contentPane.add(topPanel, BorderLayout.SOUTH);

        paintPanel = new PaintPanel();
        contentPane.add(paintPanel, BorderLayout.CENTER);

        //frameTimer = new Timer(50, this);
        //frameTimer.start();
    }

    public void actionPerformed(ActionEvent e)
    {
        //System.out.println("Action performed");
        if (e.getSource() == oval)      
        {
            paintPanel.input();
        }
        /*else if (e.getSource() == frameTimer)
        {
            paintPanel.update();
        }*/
         if (e.getSource() == rectangle)
        {
            paintPanel.input();
        }
         if (e.getSource() == oval)
        {
            //System.out.println("start/stop");
            paintPanel.input();
        }
         if (e.getSource() == Name)
        {
            paintPanel.input();
            String text = e.getActionCommand();
            paintPanel.setDisplayText("Servando Hernandez");
            //System.out.println(text);
        }

        repaint();
    }

    public static void main(String[] args)
    {
        GuiTest gui = new GuiTest();
        gui.setVisible(true);

    }
}
Servanh
  • 45
  • 8

2 Answers2

3

Whatever is commented out is because it will be implemented later for a special button.

Well, don't include the code in the question. The code is irrelevant to the question and we don't want to waste time reading it or guessing why it is there?

private boolean Name = true;

Why is the variable name capitalized? None of the other variables start with a capital (which is correct). Be consistent!!!

    if(Name == true)
    {
        g.setColor(Color.BLACK);
        g.drawString(display, textx, texty);
        Name = false;
    }
    else if(Name == false)
    {
        g.drawString(none, textx, texty);
        Name = true;
    }

You are making the if statement to complex. If a boolean variable isn't true then it is false. Just use:

    if(name == true)
    //if(name) // even simpler, you don't need the "== true"
    {
        g.setColor(Color.BLACK);
        g.drawString(display, textx, texty);
    }
    else 
    {
        g.drawString(none, textx, texty);
    }

I don't understand your ActionListener code. It doesn't matter what button you click you always execute paintPanel.input().

See edit below for example of what the code should be.

Tidy up the code using these suggestions. If you still need more help then post a proper SSCCE that demonstrates the problem.

Edit:

You need to add properties to your PaintPanel class. For example:

public void setOval(Boolean oval)
{
    this.oval = oval;
    repaint();
}

Now in the ActionListener your code would be:

if (e.getSource() == oval)
{
    paintPanel.setOval( oval.isSelected();
}
camickr
  • 321,443
  • 19
  • 166
  • 288
  • Thank you, I have been pretty reckless with my code since this is my first time messing with GUI. But I am confused, In the correction you state oval == true, but what will that do? I mean the toggle button cannot be used as Boolean. – Servanh Apr 30 '15 at 22:47
  • @Servanh, That is a typo, I mean to say `oval = true`. However, taking a second look even that is wrong. Take a look at the edit to my answer. – camickr May 01 '15 at 00:45
  • I understand now. That will help me a lot. Thank you very much for edit. – Servanh May 01 '15 at 01:17
2

There is lots of confusing things in your code. For starters, you are toggling on/off the state of all your shapes every time your paintComponent() runs. You should be handling the state from your actionPerformed() method. For example:

if (e.getSource() == rectangle) {
   // paintPanel.input();  // what's this doing anyways?
    paintPanel.setShowRectangle(rectangle.isSelected());
}

At any rate, your other shapes aren't showing for various reasons...

Your display is an blank string. Try this and see:

g.drawString("Test", textx, texty);

You position is drawing it off the panel. I changed it (5 to 1) just to make it appear, but you'll probably want it somewhere else:

g.fillOval((1 * w) / 8, (1 * h) / 8, w / 4, h / 4);
martinez314
  • 12,162
  • 5
  • 36
  • 63