Background Information:
This is a Java project for Undergraduate Research at my school. I will be presenting this program on Sunday 4/23/2017. I am stuck on a specific part of my program. This program is not located in any textbook and was made from scratch.
Programmed using Eclipse Neon.2 on Windows 10.
Description:
This program is an animation window using JApplet. Displayed will be a single window which uses the border layout to organize my panels. I have 5 panels (2 sliders on the east and west, 1 radio button on the south, one title on the north, and the center is animation).
The problem area is the center panel, which is where the animation window is located. I have three classes that each create an animation of 16 balls. One class creates balls bouncing vertically, another the balls bounce horizontally, and finally the balls will bounce in random directions.
I am using a radio button panel to completely change the center panel, to display each different class upon clicking. It starts in the vertical class by default. I can get each class to display individually by commenting out one class and trying it with another.
The problem:
My action listener for the radio buttons IS properly communicating with the radio button being clicked. But the class is not changing and the panel is not being updated. With the way I have it set up now, the center panel is empty.
In the end i want to have my center panel able to display any of the three animation classes by clicking a radio button.
Disclaimer:
I have not properly programmed the logic for the horizontal or random class, but the vertical class works. The sliders are not functional.
Here is the code:
package NEWbounceBallPackage;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class NEWbounceBallClass extends JApplet{
private DrawingPanelRandom ballBounce3; //Center panel, if random bounce
private DrawingPanelHorizontal ballBounce2; //Center panel, if horizontal
//bounce
private DrawingPanelVertical ballBounce; //Center panel, if vertical bounce
private JPanel title; //North
private JPanel selectionButtons; //South
private JPanel ballSize; //West
private JPanel numberOfBalls; //East
private JSlider ballSizeSlider; //Component of ballSize panel
private JSlider numberOfBallsSlider; //Componenet of
private JRadioButton vertical; //button for DrawingPanelVertical
private JRadioButton horizontal; //button for DrawingPanelHorizontal
private JRadioButton random; //button for DrawingPanelRandom
public void init()
{
resize(1150,600); //resize main window
setLayout(new BorderLayout());
buildTitlePanel(); //builds north panel
buildBallBouncePanel(); //calls buildSelectionButtonsPanel()(radio
//buttons panel)
//buildSelectionButtonsPanel(); //being called in
//buildBallBouncePanel()
buildBallSizeSlider(); //builds west panel
buildNumberOfBallsSlider(); //builds east panel
add(title, BorderLayout.NORTH); //adds north panel to
//main window
//add(ballBounce, BorderLayout.CENTER); //will be called in
//buildSelectionButtonsPanel() inside of action listener
add(selectionButtons, BorderLayout.SOUTH); //adds south panel to
//main window
add(ballSize, BorderLayout.WEST); //adds west panel to
//main window
add(numberOfBalls, BorderLayout.EAST); //adds east panel to
//main window
}
private void buildTitlePanel() //creates north panel
{
title = new JPanel();
Font titleFont = new Font("Serrif", Font.BOLD, 17);
JLabel titleText = new JLabel("Bounce Ball Window");
titleText.setFont(titleFont);
title.add(titleText);
}
private void buildBallBouncePanel() //creates center panel by calling radio
//buttons
{
buildSelectionButtonsPanel();
}
public void buildSelectionButtonsPanel() //creates south panel (called by
buildBallBouncePanel()
{
selectionButtons = new JPanel();
vertical = new JRadioButton("Vertical Bounce");
horizontal = new JRadioButton("Horizontal Bounce");
random = new JRadioButton("Random Bounce");
ButtonGroup group = new ButtonGroup(); //groups buttons allowing
//only one to be selected
group.add(vertical);
group.add(horizontal);
group.add(random);
vertical.setSelected(true); //vertical button selected by default
selectionButtons.add(vertical);
selectionButtons.add(horizontal);
selectionButtons.add(random);
//ballBounce = new DrawingPanelVertical(); //(TEST) if you want to see
//animation work, uncomment line 76 and 77,
//add(ballBounce, BorderLayout.CENTER); //(TEST) this will only show
//the vertical bounce
vertical.addActionListener(new ActionListener() //action listener for
//vertical class
{
public void actionPerformed(ActionEvent event)
{
ballBounce = new DrawingPanelVertical(); //calls vertical
//class then adds to center panel
add(ballBounce, BorderLayout.CENTER);
System.out.print("Vertical Test");
}
}
);
horizontal.addActionListener(new ActionListener() //action listener for
//horizontal class
{
public void actionPerformed(ActionEvent event)
{
ballBounce2 = new DrawingPanelHorizontal(); //calls horizontal
//class then adds to center panel
add(ballBounce2, BorderLayout.CENTER);
System.out.print("Horizontal Test");
}
}
);
random.addActionListener(new ActionListener() //action listener for
//random class
{
public void actionPerformed(ActionEvent event)
{
ballBounce3 = new DrawingPanelRandom(); //calls random class
//then adds to center panel
add(ballBounce3, BorderLayout.CENTER);
System.out.print("Random Test");
}
}
);
}
private void buildBallSizeSlider() //creates west slider panel
{
ballSize = new JPanel();
ballSize.setLayout(new BorderLayout());
ballSizeSlider = new JSlider(JSlider.VERTICAL, 1, 8, 1);
JLabel title = new JLabel("Change Size of Ball");
ballSizeSlider.setPreferredSize(new Dimension(50,500));
ballSizeSlider.setMajorTickSpacing(1);
ballSizeSlider.setMinorTickSpacing(1);
ballSizeSlider.setPaintTicks(true);
ballSizeSlider.setPaintLabels(true);
//ballSizeSlider.addChangeListener(new SliderListener());
ballSize.add(title, BorderLayout.NORTH);
ballSize.add(ballSizeSlider, BorderLayout.CENTER);
}
//private class SliderListener implements ChangeListener
//{
// public void stateChanged(ChangeEvent e)
// {
// int sliderChoice;
// sliderChoice = ballSizeSlider.getValue();
// if(sliderChoice = )
//}
//}
private void buildNumberOfBallsSlider() //creates east slider panel
{
numberOfBalls = new JPanel();
numberOfBalls.setLayout(new BorderLayout());
numberOfBallsSlider = new JSlider(JSlider.VERTICAL, 0, 16, 8);
JLabel title = new JLabel("Adjust Number of Balls");
numberOfBallsSlider.setPreferredSize(new Dimension(50,500));
numberOfBallsSlider.setMajorTickSpacing(1);
numberOfBallsSlider.setMinorTickSpacing(1);
numberOfBallsSlider.setPaintTicks(true);
numberOfBallsSlider.setPaintLabels(true);
numberOfBalls.add(title, BorderLayout.NORTH);
numberOfBalls.add(numberOfBallsSlider, BorderLayout.CENTER);
}
}
package NEWbounceBallPackage;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DrawingPanelVertical extends JPanel{
private final int X = 135; //starting position of first ball (all other ball
//starting positions are based from first ball)
private final int WIDTH = 40; //width of balls
private final int HEIGHT = 40; //height of balls
private final int TIME_DELAY = 40; //delays animation (increase to slow
//down)
private final int MOVE = 20; //dictates how quickly the ball moves during
//animation
private final int MINIMUM_Y = 50; //bottom limit of bounce
private final int MAXIMUM_Y = 400; //top limit of bounce
private int y = 400; //starting position of first ball (all other ball
//starting positions are based from first ball)
private boolean goingUp = true;
private Timer timer;
public DrawingPanelVertical()
{
setPreferredSize(new Dimension(800,500));
timer = new Timer(TIME_DELAY, new TimerListener());
timer.start();
}
public void paint(Graphics g)
{
super.paint(g);
g.drawRect(80, 0, 750, 500);
g.setColor(getBackground());
g.setColor(Color.black);
g.fillOval(X, y, WIDTH, HEIGHT);
g.setColor(Color.blue);
g.fillOval(X+50, y, WIDTH, HEIGHT);
g.setColor(Color.cyan);
g.fillOval(X+100, y, WIDTH, HEIGHT);
g.setColor(Color.darkGray);
g.fillOval(X+150, y, WIDTH, HEIGHT);
g.setColor(Color.gray);
g.fillOval(X+200, y, WIDTH, HEIGHT);
g.setColor(Color.green);
g.fillOval(X+250, y, WIDTH, HEIGHT);
g.setColor(Color.lightGray);
g.fillOval(X+300, y, WIDTH, HEIGHT);
g.setColor(Color.magenta);
g.fillOval(X+350, y, WIDTH, HEIGHT);
g.setColor(Color.orange);
g.fillOval(X+400, y, WIDTH, HEIGHT);
g.setColor(Color.pink);
g.fillOval(X+450, y, WIDTH, HEIGHT);
g.setColor(Color.red);
g.fillOval(X+500, y, WIDTH, HEIGHT);
g.setColor(Color.white);
g.fillOval(X+550, y, WIDTH, HEIGHT);
g.setColor(Color.yellow);
g.fillOval(X+600, y, WIDTH, HEIGHT);
}
private class TimerListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(goingUp)
{
if(y > MINIMUM_Y)
y = y - MOVE;
else
goingUp = false;
}
else
{
if(y < MAXIMUM_Y)
y = y + MOVE;
else
goingUp = true;
}
//resize(1300,600);
repaint();
//resize(1302,600);
}
}
}
But the class is not changing and the panel is not being updated.
Swing components by default have a size of (0, 0) so there is nothing to paint. You need to invoke the layout manager so the component can be given a size and location based on the rules of the layout manager.
So, when you add a component to a visible GUI the basic logic is:
panel.add(...);
panel.revalidate(); // invokes the layout manager
panel.repaint();
In the end i want to have my center panel able to display any of the three animation classes by clicking a radio button.
The better solution is to use a CardLayout and let the layout manager manage the visible panel. Read the section from the Swing tutorial on How to Use CardLayout for more information and working examples.
Related
I am trying to display 2 objects Tank on JPanel, the tank gets image with ImageIcon. The JPanel shows up but my Tanks do not. I cannot find where am i wrong. A friend of mine send me the code that he can display tanks but i cannot display it with my computer.
My Tank class to get image
public class Player extends Tank {
private Image img;
public Player(int x, int y){
super(x, y);
ImageIcon ii = new ImageIcon("src/TankD.gif");
img = ii.getImage();
}
public Image getImg() {
return img;
}
public String toString() {
return "This is player tank";
}
}
My class to draw image
public class DrawTanks extends JPanel{ // DRAW IMAGE
private ArrayList<Tank> list = new ArrayList<>();
private Tank a;
public DrawTanks() {
Tank t1 = new Player(100, 200);
Tank t2 = new Bot(200, 100);
a = t1;
list.add(t1);
list.add(t2);
setPreferredSize(new Dimension(100,200));
setLocation(new Point(200, 200));
}
#Override
public void paintComponent(Graphics g){
for (Tank i: list)
g.drawImage(i.getImg(), i.getX(), i.getY(), null);
}
My main class
public class Window extends JFrame{
public static void main(String[]args){
Window win = new Window();
}
public Window(){
JPanel pan = new JPanel();
DrawTanks tanks = new DrawTanks();
this.add(tanks);
this.setTitle("Tank");
this.setSize(900,900);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
}
JPanel pan = new JPanel();
DrawTanks tanks = new DrawTanks();
this.add(tanks);
Why are you creating the "pan" object?
By default a JPanel uses a FlowLayout which respects the panels size.
In your DrawTanks class you use:
setPreferredSize(new Dimension(100,200));
to randomly set the size of the panel.
But then you create the tanks:
Tank t1 = new Player(100, 200);
Tank t2 = new Bot(200, 100);
where the location of each tank is outside the preferred size of the panel. So the tanks are probably painted but they are outside the bounds of the panel so you can't see them.
The solution:
get rid of the "pan" pane and just add your DrawTanks panel directly to the frame
give your DrawTanks a reasonable preferred size so all components added to it can be painted.
I have a class that extends JFrame and I would like to add two JPanels to that JFrame: a text panel and a graphics panel. My text panel is a panel containing a label with text. My graphics panel will contain a graph (created using 2DGraphics). I'm adding the graphic panel to the left side (0,0) and the text panel to right side (1,0) using a gridbaglayout method. However, the graphic panel won't show up in the frame. I have tried numerous methods to try to get the panel to show up with no success.
import java.awt.*;
import javax.swing.*;
public class GraphicsTest extends JFrame {
private final JPanel textPanel;
private final JLabel textLabel;
public GraphicsTest() {
textPanel = new JPanel(new BorderLayout());
textLabel = new JLabel("Home label");
this.setBounds(180, 112, 1080, 675);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridBagLayout());
textPanel.add(textLabel, BorderLayout.NORTH);
addComponent(this, new GraphicPanel(), 0, 0, 1, 1, GridBagConstraints.CENTER);
addComponent(this, textPanel, 1, 0, 1, 1, GridBagConstraints.CENTER);
this.setVisible(true);
}
public class GraphicPanel extends JPanel {
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
public void paintComponents(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
// drawing lots of shapes and lines, removed for readibility
}
}
public void addComponent(JFrame frame, JComponent component, int x, int y, int width, int height, int align) {
GridBagConstraints c = new GridBagConstraints();
c.gridx = x;
c.gridy = y;
c.gridwidth = width;
c.gridheight = height;
c.weightx = 100.0;
c.weighty = 100.0;
c.insets = new Insets(5, 0, 5, 0);
c.anchor = align;
c.fill = GridBagConstraints.NONE;
frame.add(component, c);
}
public static void main(String[] args) {
GraphicsTest gui = new GraphicsTest();
}
}
Works fine for me when I use a size like (200, 200).
GridbagLayout works such that if a component can't be displayed at its preferred size, then it will be displayed at its minimum size, which would be (0, 0).
So whether (700, 700) works will depend on your screen resolution. It also works at (700, 600) for my screen.
I question if you want to use a GridBadLayout. Maybe just use a BorderLayout. The custom painting panel would go in the CENTER so it will grow/shrink as the frame size changes. The other panel would go to the LINE_END, so it will remain at a fixed size.
I'm fairly new to Java and I'm at a complete loss. I'm trying to create a simple program that draws a circle and outputs it's properties on the screen. Functionally, the program works fine, but the layout of the JPanels is off. For some reason, there is a gap between the JPanel that holds the 'Draw Me' button and the JPanel that holds the circle. Even if I resize the height of the program, the gap doesn't disappear. Likewise, the labels within the program aren't aligning to the left, they kind of sit off-center for some weird reason, removing the border doesn't seem to help. I'm stuck...
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
public class MainPanel extends JPanel {
private JPanel userHelpSubPanel;
private JPanel inputSubPanel;
private JPanel buttonSubPanel;
private JPanel drawSubPanel;
private JPanel resultsSubPanel;
private JLabel userHelpLabel;
private JLabel diameterLabel;
private JLabel circumferenceLabel;
private JLabel areaLabel;
private JButton drawButton;
private JTextField inputTextField;
private float radius;
public MainPanel() {
radius = 0;
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
userHelpSubPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
inputSubPanel = new JPanel();
inputSubPanel.setLayout(new BoxLayout(inputSubPanel, BoxLayout.Y_AXIS));
drawSubPanel = new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.draw(new Ellipse2D.Double(150, 20, radius * 2, radius * 2));
}
};
resultsSubPanel = new JPanel();
resultsSubPanel.setLayout(new BoxLayout(resultsSubPanel, BoxLayout.Y_AXIS));
buttonSubPanel = new JPanel();
userHelpLabel = new JLabel();
userHelpLabel.setText("Enter the radius of the ellipse: ");
inputTextField = new JTextField();
inputTextField.setMaximumSize(new Dimension(Integer.MAX_VALUE, inputTextField.getPreferredSize().height));
drawButton = new JButton("Draw Me");
drawButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
MainPanel.this.radius = Float.parseFloat(inputTextField.getText());
diameterLabel.setText(String.format("Diameter: %.1f", 2 * radius));
circumferenceLabel.setText(String.format("Circumference: %.1f", 2 * Math.PI * radius));
areaLabel.setText(String.format("Area: %.1f", Math.PI * Math.pow(radius, 2)));
drawSubPanel.repaint();
}
});
circumferenceLabel = new JLabel("Circumference: N/A");
diameterLabel = new JLabel("Diameter: N/A");
areaLabel = new JLabel("Area: N/A");
userHelpSubPanel.add(userHelpLabel);
inputSubPanel.add(inputTextField);
buttonSubPanel.add(drawButton);
resultsSubPanel.add(diameterLabel);
resultsSubPanel.add(circumferenceLabel);
resultsSubPanel.add(areaLabel);
add(userHelpLabel);
add(inputSubPanel);
add(buttonSubPanel);
add(drawSubPanel);
add(resultsSubPanel);
}
}
And here is what it looks like....
BoxLayout will respect the minimum and maximum sizes of a component. So if there is extra space in the frame then the panels will be given more space.
The solution is to override the getMaximumSize() method of the custom panel to return the preferred size of the panel.
Every Swing component is responsibile for determiningin its own preferred size. So this would mean you also need to override the getPreferredSize() of the panel where you do the custom painting. The preferred size would be based on the size/location of the oval that you are drawing.
A simple fix for these issues is to give your panels (relevant ones) an empty border and then reduce the specific direction that is too large:
// this example reduces the top of your circle panel.
drawSubPanel.setBorder(new EmptyBorder(-100, 0, 0, 0));
Obviously this isn't the root of the problem and isn't the most optimal but it should do the trick.
I have to design and implement an application that draws the graph of the equation of ax^2 + bx + c where the values of a b and c are set using sliders. I am editing my original post and thus am going to do my best to post an sscce. My code is below. Everything compiles and runs. My one question is why is my graph not displaying anything when the sliders are moved? Here are my 2 class files:
import java.awt.*;
import javax.swing.*;
public class QuadraticGraph
{
public static void main (String[] args)
{
JFrame frame = new JFrame ("Quadratic Grapher");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new QuadraticPanel());
frame.pack();
frame.setVisible(true);
}
}
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class QuadraticPanel extends JPanel
{
private JPanel controls, quadpanel;
private JSlider aslider, bslider, cslider;
private JLabel alabel, blabel, clabel;
//-----------------------------------------------------------------
// Sets up the sliders and their labels, aligning them along
// their left edge using a box layout.
//-----------------------------------------------------------------
public QuadraticPanel()
{
aslider = new JSlider (JSlider.HORIZONTAL, -25, 25, 0);
aslider.setMajorTickSpacing (50);
aslider.setMinorTickSpacing (10);
aslider.setPaintTicks (true);
aslider.setPaintLabels (true);
aslider.setAlignmentX (Component.LEFT_ALIGNMENT);
bslider = new JSlider (JSlider.HORIZONTAL, -25, 25, 0);
bslider.setMajorTickSpacing (50);
bslider.setMinorTickSpacing (10);
bslider.setPaintTicks (true);
bslider.setPaintLabels (true);
bslider.setAlignmentX (Component.LEFT_ALIGNMENT);
cslider = new JSlider (JSlider.HORIZONTAL, -25, 25, 0);
cslider.setMajorTickSpacing (50);
cslider.setMinorTickSpacing (10);
cslider.setPaintTicks (true);
cslider.setPaintLabels (true);
cslider.setAlignmentX (Component.LEFT_ALIGNMENT);
SliderListener listener = new SliderListener();
aslider.addChangeListener (listener);
bslider.addChangeListener (listener);
cslider.addChangeListener (listener);
alabel = new JLabel ("A: 0");
alabel.setAlignmentX (Component.LEFT_ALIGNMENT);
blabel = new JLabel ("B: 0");
blabel.setAlignmentX (Component.LEFT_ALIGNMENT);
clabel = new JLabel ("C: 0");
clabel.setAlignmentX (Component.LEFT_ALIGNMENT);
controls = new JPanel();
BoxLayout layout = new BoxLayout (controls, BoxLayout.Y_AXIS);
controls.setLayout (layout);
controls.add (alabel);
controls.add (aslider);
controls.add (Box.createRigidArea (new Dimension (0, 20)));
controls.add (blabel);
controls.add (bslider);
controls.add (Box.createRigidArea (new Dimension (0, 20)));
controls.add (clabel);
controls.add (cslider);
quadpanel = new JPanel();
quadpanel.setPreferredSize (new Dimension (500, 500));
quadpanel.setBackground (Color.white);
add (controls);
add (quadpanel);
}
//*****************************************************************
// Represents the listener for all three sliders.
//*****************************************************************
private class SliderListener implements ChangeListener
{
private double a, b, c, x, y, g, h;
//--------------------------------------------------------------
// Gets the value of each slider, then updates the labels and
// the color panel.
//--------------------------------------------------------------
public void stateChanged (ChangeEvent event)
{
a = aslider.getValue();
b = bslider.getValue();
c = cslider.getValue();
alabel.setText ("A: " + a);
blabel.setText ("B: " + b);
clabel.setText ("C: " + c);
}
public void paintComponent (Graphics page)
{
x = (-b + (Math.sqrt((b*b - ((4 * a * c))))))/ (2 * a);
y= (a*(Math.pow(x,2)))+(b*x)+(c);
int g = (int)Math.round(x);
int h = (int)Math.round(y);
page.setColor (Color.black);
page.drawOval (g, h, 1, 1);
}
}
}
i guess you're very new to java, so here's some starters help ^^
create a content Panel and set some layout to the panel;
add the sliders and a drawing-panel to your content panel;
you're doing it right, adding an change listener to the slider, but they should redraw the drawing-panel.
i'll add this snippets to make it easier for you ^_^
private JPanel drawPanel; //don't forget to create a proper one! override paint in that panel!
private int a,b,c;
public QuadraticPanel(){ //constructor
setLayout(new BoderLayout();
JSlider aSidler = new JSlider();
slider.addChangeListener(new ChangeListener(){
#Override
public void stateChanged(ChangeEvent arg0) {
a = arg0.getValue(); //setting a value
//it might even be better to calculate the value
//BEFORE you redraw
//recalcEquotiation()
drawPanel.repaint(); //and redraw the paint-panel
}
});
add(aSlider, Borderlayout.WEST); //add more sliders with better layouts or subcomponents
add(drawPanel, BorderLayout.CENTER);
}
don't forget - these are just snippets, you'll have to do some work on your own...
I'm currently working on a program which is for school. We have to make an Applet and I have opted for JApplet. For some reason, the panel which I am using to display a specific string will not show. What might be the issue here? Please point me in the right direction. Also, I looked at a few a tutorials, some suggested that I have "start", "stop" and "destory" methods and some didn't. Do any of these methods have an effect on why my JPanel won't show the graphic?
Thank you
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Shape extends JApplet {
/**
*
*/
private static final long serialVersionUID = 1L;
// making the radiobuttons for the shape choices
JRadioButton squareButton = new JRadioButton("Square",true);
JRadioButton ovalButton = new JRadioButton("Oval",false);
JRadioButton rectangleButton = new JRadioButton("Rectangle",false);
JRadioButton triangleButton = new JRadioButton("Triangle",false);
// making radiobuttons for the color choices
JRadioButton redButton = new JRadioButton("Red",true);
JRadioButton blueButton = new JRadioButton("Blue",false);
JRadioButton greenButton = new JRadioButton("Green",false);
JRadioButton yellowButton = new JRadioButton("Yellow",false);
// making buttons draw and animate
JButton drawButton = new JButton("Draw!");
JButton animateButton = new JButton("Animate!");
// making JTextFields for length and width
JTextField lengthField = new JTextField("Enter a length",15);
JTextField widthField = new JTextField("Enter a width",15);
// making JPanel, in which the radiobuttons will go01
JPanel shapePanel = new JPanel();
JPanel colorPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel textPanel = new JPanel();
drawPanel dPanel;
ButtonGroup shapeGroup = new ButtonGroup();
ButtonGroup colorGroup = new ButtonGroup();
// variables that will dictates the shape, size and color
int length = 200;
int width = 200;
Color color = Color.RED;
String shape = "square";
public void init() {
setLayout(new FlowLayout()); // setting layout for the applet
setSize(680,480);
// setting the layout for the shapePanel - gridlayout 2 rows, 2 cols and space of 5
shapePanel.setLayout(new GridLayout(2,2,5,5));
// adding a border to the shapePanel to indicate to the user what it does "titledBorder"
shapePanel.setBorder(BorderFactory.createTitledBorder("Choose a shape"));
// setting layout for the color panel - gridlayout 2 rows, 2 cols and space of 5
colorPanel.setLayout(new GridLayout(2,2,5,5));
// adding a border to the colorPanel to indicate to the user what it does "titledBorder"
colorPanel.setBorder(BorderFactory.createTitledBorder("Choose a color"));
// setting the layout for the buttonPanel - gridlayout 1 row, 2 cols and space of 5
buttonPanel.setLayout(new GridLayout(1,2,5,5));
// adding a color border
buttonPanel.setBorder(BorderFactory.createLineBorder(Color.red, 2));
// setting the layout of the textField - gridlayout 1 row, 2 cols and space of 5
textPanel.setLayout(new GridLayout(1,2,5,5));
// adding some attributes for lengthField and widthField
lengthField.setFont(new Font("Arial",Font.PLAIN,12));
lengthField.setForeground(new Color(150,150,150));
widthField.setFont(new Font("Arial",Font.PLAIN,12));
widthField.setForeground(new Color(150,150,150));
// using shapegroup to organize the JRadioButtons
shapeGroup.add(squareButton);
shapeGroup.add(ovalButton);
shapeGroup.add(rectangleButton);
shapeGroup.add(triangleButton);
// using colorgroup to organize the color radiobuttons
colorGroup.add(redButton);
colorGroup.add(blueButton);
colorGroup.add(greenButton);
colorGroup.add(yellowButton);
// add the shape buttons to the panel so they appear in a square form
shapePanel.add(squareButton);
shapePanel.add(ovalButton);
shapePanel.add(rectangleButton);
shapePanel.add(triangleButton);
// adding color buttons to the color panel
colorPanel.add(redButton);
colorPanel.add(blueButton);
colorPanel.add(greenButton);
colorPanel.add(yellowButton);
// adding jbuttons
buttonPanel.add(drawButton);
buttonPanel.add(animateButton);
// adding textfields to the textPanel
textPanel.add(lengthField);
textPanel.add(widthField);
dPanel = new drawPanel();
// adding panels to the applet
add(shapePanel);
add(colorPanel);
add(buttonPanel);
add(textPanel);
add(dPanel);
// adding focus listener to lengthField and widthField
lengthField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
lengthField.setText("");
lengthField.setForeground(Color.black);
}
public void focusLost(FocusEvent e) {}
});
widthField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
widthField.setText("");
widthField.setForeground(Color.black);
}
public void focusLost(FocusEvent e) {}
});
drawButton.addActionListener(new drawListener());
}
// when the person presses paint, this will be executed to paint the specific shape, color with the width and length
class drawListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
int mylength = 5;
int mywidth = 5;
try {
mylength = Integer.parseInt(lengthField.getText());;
mywidth = Integer.parseInt(widthField.getText());;
}catch(Exception ex) {
JOptionPane.showMessageDialog(null,""+ex,"",JOptionPane.ERROR_MESSAGE);
}
if((mylength > 200 || mylength < 5)) {
JOptionPane.showMessageDialog(null, "Please make sure the number is above 5 and less than 200",
"Invalid length message", JOptionPane.ERROR_MESSAGE);
}else if((mywidth > 200 || mywidth < 5)) {
JOptionPane.showMessageDialog(null, "Please make sure the number is above 5 and less than 200",
"Invalid width message", JOptionPane.ERROR_MESSAGE);
}else {
length = mylength;
width = mywidth;
// checking which color button is selected
if(redButton.isSelected()) {
color = Color.RED;
}else if(blueButton.isSelected()) {
color = Color.BLUE;
}else if(greenButton.isSelected()) {
color = Color.GREEN;
}else if(yellowButton.isSelected()) {
color = Color.YELLOW;
}
// checking which shape has been selected
if(rectangleButton.isSelected()) {
shape = "rectangle";
}else if(triangleButton.isSelected()) {
shape = "triangle";
}else if(ovalButton.isSelected()) {
shape = "oval";
}else if(squareButton.isSelected()) {
shape = "square";
}
//System.out.printf("%3d %3d %s %s \n",length,width,shape,color);
}
}
}
// This will be used to do the painting
class drawPanel extends JPanel {
private static final long serialVersionUID = 1L;
//Paint Method
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
g2.drawString("My awesome string", 200, 200);
}
}
}
A JPanel with no components has a default size of 0x0. Try this source:
// <applet code=Shape width=640 height=480></applet>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Shape extends JApplet {
/**
*
*/
private static final long serialVersionUID = 1L;
// making the radiobuttons for the shape choices
JRadioButton squareButton = new JRadioButton("Square",true);
JRadioButton ovalButton = new JRadioButton("Oval",false);
JRadioButton rectangleButton = new JRadioButton("Rectangle",false);
JRadioButton triangleButton = new JRadioButton("Triangle",false);
// making radiobuttons for the color choices
JRadioButton redButton = new JRadioButton("Red",true);
JRadioButton blueButton = new JRadioButton("Blue",false);
JRadioButton greenButton = new JRadioButton("Green",false);
JRadioButton yellowButton = new JRadioButton("Yellow",false);
// making buttons draw and animate
JButton drawButton = new JButton("Draw!");
JButton animateButton = new JButton("Animate!");
// making JTextFields for length and width
JTextField lengthField = new JTextField("Enter a length",15);
JTextField widthField = new JTextField("Enter a width",15);
// making JPanel, in which the radiobuttons will go01
JPanel shapePanel = new JPanel();
JPanel colorPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel textPanel = new JPanel();
drawPanel dPanel;
ButtonGroup shapeGroup = new ButtonGroup();
ButtonGroup colorGroup = new ButtonGroup();
// variables that will dictates the shape, size and color
int length = 200;
int width = 200;
Color color = Color.RED;
String shape = "square";
public void init() {
setLayout(new FlowLayout()); // setting layout for the applet
// This is set by HTML!
//setSize(680,480);
// setting the layout for the shapePanel - gridlayout 2 rows, 2 cols and space of 5
shapePanel.setLayout(new GridLayout(2,2,5,5));
// adding a border to the shapePanel to indicate to the user what it does "titledBorder"
shapePanel.setBorder(BorderFactory.createTitledBorder("Choose a shape"));
// setting layout for the color panel - gridlayout 2 rows, 2 cols and space of 5
colorPanel.setLayout(new GridLayout(2,2,5,5));
// adding a border to the colorPanel to indicate to the user what it does "titledBorder"
colorPanel.setBorder(BorderFactory.createTitledBorder("Choose a color"));
// setting the layout for the buttonPanel - gridlayout 1 row, 2 cols and space of 5
buttonPanel.setLayout(new GridLayout(1,2,5,5));
// adding a color border
buttonPanel.setBorder(BorderFactory.createLineBorder(Color.red, 2));
// setting the layout of the textField - gridlayout 1 row, 2 cols and space of 5
textPanel.setLayout(new GridLayout(1,2,5,5));
// adding some attributes for lengthField and widthField
lengthField.setFont(new Font("Arial",Font.PLAIN,12));
lengthField.setForeground(new Color(150,150,150));
widthField.setFont(new Font("Arial",Font.PLAIN,12));
widthField.setForeground(new Color(150,150,150));
// using shapegroup to organize the JRadioButtons
shapeGroup.add(squareButton);
shapeGroup.add(ovalButton);
shapeGroup.add(rectangleButton);
shapeGroup.add(triangleButton);
// using colorgroup to organize the color radiobuttons
colorGroup.add(redButton);
colorGroup.add(blueButton);
colorGroup.add(greenButton);
colorGroup.add(yellowButton);
// add the shape buttons to the panel so they appear in a square form
shapePanel.add(squareButton);
shapePanel.add(ovalButton);
shapePanel.add(rectangleButton);
shapePanel.add(triangleButton);
// adding color buttons to the color panel
colorPanel.add(redButton);
colorPanel.add(blueButton);
colorPanel.add(greenButton);
colorPanel.add(yellowButton);
// adding jbuttons
buttonPanel.add(drawButton);
buttonPanel.add(animateButton);
// adding textfields to the textPanel
textPanel.add(lengthField);
textPanel.add(widthField);
dPanel = new drawPanel();
dPanel.setPreferredSize(new Dimension(500,300));
// adding panels to the applet
add(shapePanel);
add(colorPanel);
add(buttonPanel);
add(textPanel);
add(dPanel);
// adding focus listener to lengthField and widthField
lengthField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
lengthField.setText("");
lengthField.setForeground(Color.black);
}
public void focusLost(FocusEvent e) {}
});
widthField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
widthField.setText("");
widthField.setForeground(Color.black);
}
public void focusLost(FocusEvent e) {}
});
drawButton.addActionListener(new drawListener());
}
// when the person presses paint, this will be executed to paint the specific shape, color with the width and length
class drawListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
int mylength = 5;
int mywidth = 5;
try {
mylength = Integer.parseInt(lengthField.getText());;
mywidth = Integer.parseInt(widthField.getText());;
}catch(Exception ex) {
JOptionPane.showMessageDialog(null,""+ex,"",JOptionPane.ERROR_MESSAGE);
}
if((mylength > 200 || mylength < 5)) {
JOptionPane.showMessageDialog(null, "Please make sure the number is above 5 and less than 200",
"Invalid length message", JOptionPane.ERROR_MESSAGE);
}else if((mywidth > 200 || mywidth < 5)) {
JOptionPane.showMessageDialog(null, "Please make sure the number is above 5 and less than 200",
"Invalid width message", JOptionPane.ERROR_MESSAGE);
}else {
length = mylength;
width = mywidth;
// checking which color button is selected
if(redButton.isSelected()) {
color = Color.RED;
}else if(blueButton.isSelected()) {
color = Color.BLUE;
}else if(greenButton.isSelected()) {
color = Color.GREEN;
}else if(yellowButton.isSelected()) {
color = Color.YELLOW;
}
// checking which shape has been selected
if(rectangleButton.isSelected()) {
shape = "rectangle";
}else if(triangleButton.isSelected()) {
shape = "triangle";
}else if(ovalButton.isSelected()) {
shape = "oval";
}else if(squareButton.isSelected()) {
shape = "square";
}
//System.out.printf("%3d %3d %s %s \n",length,width,shape,color);
}
}
}
// This will be used to do the painting
class drawPanel extends JPanel {
private static final long serialVersionUID = 1L;
//Paint Method
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
g2.drawString("My awesome string", 200, 200);
}
}
}