Images not showing up on the screen at the right moment - Java - java

I am working on an applet, I don't have experience with this..
I want to paint two objects, insert an image and change the background color to black. If I don't change the color, everything works just fine, the problem came when I decided to change the background color as well.
What I get is a black screen without the drawings and picture. If I minimize or re-size the window, then I get everything.
Below is my code, a simplify version.
import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class JAlienHunt extends JApplet implements ActionListener {
private JButton button = new JButton();
JLabel greeting = new JLabel("Welcome to Alien Hunt Game!");
JLabel gameOverMessage = new JLabel(" ");
JPanel displayPanel = new JPanel(new GridLayout(2, 4));
private int[] alienArray = new int[8];
int countJ = 0, countM = 0;
private ImageIcon image = new ImageIcon("earth.jpg");
private int width, height;
Container con = getContentPane();
Font aFont = new Font("Gigi", Font.BOLD, 20);
public void init() {
/** Setting the Layout and adding the content. */
width = image.getIconWidth();
height = image.getIconHeight();
greeting.setFont(aFont);
greeting.setHorizontalAlignment(SwingConstants.CENTER);
con.setLayout(new BorderLayout());
con.add(greeting, BorderLayout.NORTH);
con.add(displayPanel, BorderLayout.CENTER);
/** Add Buttons to the Applet */
displayPanel.add(button);
String text = Integer.toString(i+1); // convert button # to String adding 1.
buttons.setText(text);
buttons.addActionListener(this);
}
public void actionPerformed(ActionEvent event) {
/** Shows the Alien representing the selected button and deactivate the button. */
if(event.getSource() == buttons)
button.setText("Jupiterian");
else
buttons[i].setText("Martian");
button.setEnabled(false);
con.remove(greeting);
displayPanel.remove(button);
displayPanel.setLayout(new FlowLayout());
gameOverMessage.setHorizontalAlignment(SwingConstants.CENTER);
con.add(gameOverMessage, BorderLayout.NORTH);
repaint();
}
public void paint(Graphics gr) {
super.paint(gr);
/** Condition when user loses the game. Two Jupiterians will be painted on the screen*/
Jupiterian jupit = new Jupiterian();
displayPanel.setBackground(Color.BLACK);
gameOverMessage.setFont(new Font ("Calibri", Font.BOLD, 25));
gameOverMessage.setText("The Earth has been destroyed!");
jupit.draw(gr, 250, 120);
gr.copyArea(190, 40, 465, 300, 500, 0);
gr.drawImage(image.getImage(), 400, 400, width, height, this); //+
}
}
---------------- method draw() from Jupiterian class
public void draw(Graphics g, int x, int y) {
g.setColor(Color.WHITE);
g.drawOval(x, y, 160, 160); // Body of the alien
g.drawLine(x, y + 80, x - 40, y + 170); // Left hand
g.drawLine(x - 40, y + 170, x - 40, y + 180); // Left hand fingers
g.drawLine(x - 40, y + 170, x - 55, y + 180);
Font aFont = new Font ("Chiller", Font.BOLD, 30); // Description text.
g.setFont(aFont);
g.drawString(toString(), 230, 60);
}
--- Abstract class
public abstract class Aliena {
protected String name;
protected String planet;
/** Constructor for the class. Creates the Alien object with the parameters provided */
public Aliena(String nam, int eyes, String hair, String plan){
name = nam;
planet = plan;
}
/** Method that returns a String with a complete description of the Alien. */
public String toString(){
String stringAlien = "I am " + name + " from " + planet;
return stringAlien;
}
}
Thanks in advance!

Don't call displayPanel.setBackground(Color.BLACK);, gameOverMessage.setFont(new Font("Calibri", Font.BOLD, 25));, gameOverMessage.setText("The Earth has been destroyed!"); or any update any other UI component from within any paint method.
This will simply cause a repaint to rescheduled and a vicious cycle of updates will start that will consume your CPU and suck the world into a black hole of doom...
Instead, change the state of the components before you call repaint
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class JAlienHunt extends JApplet implements ActionListener {
private JButton button = new JButton();
JLabel greeting = new JLabel("Welcome to Alien Hunt Game!");
JLabel gameOverMessage = new JLabel(" ");
JPanel displayPanel = new JPanel(new GridLayout(2, 4));
private int[] alienArray = new int[8];
int countJ = 0, countM = 0;
private ImageIcon image = new ImageIcon("earth.jpg");
private int width, height;
Container con = getContentPane();
Font aFont = new Font("Gigi", Font.BOLD, 20);
public void init() {
/**
* Setting the Layout and adding the content.
*/
width = image.getIconWidth();
height = image.getIconHeight();
greeting.setFont(aFont);
greeting.setHorizontalAlignment(SwingConstants.CENTER);
con.setLayout(new BorderLayout());
con.add(greeting, BorderLayout.NORTH);
con.add(displayPanel, BorderLayout.CENTER);
/**
* Add Buttons to the Applet
*/
displayPanel.add(button);
// String text = Integer.toString(i + 1); // convert button # to String adding 1.
button.setText("!");
button.addActionListener(this);
}
public void actionPerformed(ActionEvent event) {
/**
* Shows the Alien representing the selected button and deactivate the
* button.
*/
// if (event.getSource() == buttons) {
// button.setText("Jupiterian");
// } else {
//// buttons[i].setText("Martian");
// }
button.setEnabled(false);
con.remove(greeting);
displayPanel.remove(button);
displayPanel.setLayout(new FlowLayout());
gameOverMessage.setHorizontalAlignment(SwingConstants.CENTER);
con.add(gameOverMessage, BorderLayout.NORTH);
displayPanel.setBackground(Color.BLACK);
gameOverMessage.setFont(new Font("Calibri", Font.BOLD, 25));
gameOverMessage.setText("The Earth has been destroyed!");
repaint();
}
public void paint(Graphics gr) {
super.paint(gr);
/**
* Condition when user loses the game. Two Jupiterians will be painted on
* the screen
*/
Jupiterian jupit = new Jupiterian();
// displayPanel.setBackground(Color.BLACK);
// gameOverMessage.setFont(new Font("Calibri", Font.BOLD, 25));
// gameOverMessage.setText("The Earth has been destroyed!");
jupit.draw(gr, 250, 120);
// gr.copyArea(190, 40, 465, 300, 500, 0);
gr.drawImage(image.getImage(), 400, 400, width, height, this); //+
}
public class Jupiterian {
public void draw(Graphics g, int x, int y) {
g.setColor(Color.WHITE);
g.drawOval(x, y, 160, 160); // Body of the alien
g.drawLine(x, y + 80, x - 40, y + 170); // Left hand
g.drawLine(x - 40, y + 170, x - 40, y + 180); // Left hand fingers
g.drawLine(x - 40, y + 170, x - 55, y + 180);
Font aFont = new Font("Chiller", Font.BOLD, 30); // Description text.
g.setFont(aFont);
g.drawString(toString(), 230, 60);
}
}
}

Related

How do I add an ActionListener to a specific JComponent?

I'm trying to make an ActionListener for a specific JComponent, but in my code, there are two JComponents which have ActionListeners.
Here's my code:
/**
* This is a Java Swing program that lets you play Minesweeper! Make sure to play it in fullscreen or else it's not going to work.
* #author Joshua Diocares
* #version JDK14.0
* #since Still in development!
*/
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
/**
* A class that shows the xy coordinates near the mouse cursor.
*/
class AlsXYMouseLabelComponent extends JComponent {
public int x;
public int y;
/**
* Uses the xy coordinates to update the mouse cursor label.
*/
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
String coordinates = x + ", " + y; // Get the cordinates of the mouse
g.setColor(Color.red);
g.drawString(coordinates, x, y); // Display the coordinates of the mouse
}
}
public class Minesweeper implements ActionListener {
private static JComboBox < String > gameModeDropdown;
private static JComboBox < String > difficultyDropdown;
public static void main(String[] args) {
JPanel panel = new JPanel();
JFrame frame = new JFrame();
frame = new JFrame();
frame.setSize(1365, 767);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Tic Tac Toe");
frame.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
frame.setVisible(true);
frame.add(panel);
panel.setLayout(null);
AlsXYMouseLabelComponent alsXYMouseLabel = new AlsXYMouseLabelComponent();
/**
* Add the component to the DRAG_LAYER of the layered pane (JLayeredPane)
*/
JLayeredPane layeredPane = frame.getRootPane().getLayeredPane();
layeredPane.add(alsXYMouseLabel, JLayeredPane.DRAG_LAYER);
alsXYMouseLabel.setBounds(0, 0, frame.getWidth(), frame.getHeight());
/**
* Add a mouse motion listener, and update the crosshair mouse cursor with the xy coordinates as the user moves the mouse
*/
frame.addMouseMotionListener(new MouseMotionAdapter() {
/**
* Detects when the mouse moved and what the mouse's coordinates are.
* #param event the event that happens when the mouse is moving.
*/
#Override
public void mouseMoved(MouseEvent event) {
alsXYMouseLabel.x = event.getX();
alsXYMouseLabel.y = event.getY();
alsXYMouseLabel.repaint();
}
});
JLabel title = new JLabel("Minesweeper");
title.setBounds(500, 100, 550, 60);
title.setFont(new Font("Verdana", Font.PLAIN, 50));
panel.add(title);
JLabel gameModePrompt = new JLabel("Game Mode: ");
gameModePrompt.setBounds(280, 335, 300, 25);
gameModePrompt.setFont(new Font("Verdana", Font.PLAIN, 20));
panel.add(gameModePrompt);
String[] gameModes = {
"Normal"
};
JComboBox < String > gameModeDropdown = new JComboBox < String > (gameModes);
gameModeDropdown.setBounds(415, 335, 290, 25);
gameModeDropdown.setFont(new Font("Verdana", Font.PLAIN, 20));
gameModeDropdown.addActionListener(new Minesweeper());
panel.add(gameModeDropdown);
JLabel difficultyPrompt = new JLabel("Difficulty: ");
difficultyPrompt.setBounds(800, 335, 240, 25);
difficultyPrompt.setFont(new Font("Verdana", Font.PLAIN, 20));
panel.add(difficultyPrompt);
String[] difficulties = {
"Medium"
};
JComboBox < String > difficultyDropdown = new JComboBox < String > (difficulties);
difficultyDropdown.setBounds(910, 335, 120, 25);
difficultyDropdown.setFont(new Font("Verdana", Font.PLAIN, 20));
panel.add(difficultyDropdown);
JButton playButton = new JButton("Play");
playButton.setBounds(530, 480, 220, 25);
playButton.setFont(new Font("Verdana", Font.PLAIN, 20));
playButton.addActionListener(new Minesweeper());
panel.add(playButton);
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
Any suggestions would be really helpful
I cleaned up your code. I added a PlayListener class as the ActionListener to your Play button. You don't need an ActionListener for either dropdown. You can get the selected dropdown values when you need them in the PlayListener class.
I added a call to the SwingUtilities invokeLater method. This method ensures that your Swing components are created and executed on the Event Dispatch Thread.
I rearranged your JFrame method calls. I don't know if you noticed, but you made the JFrame visible before you created the components. You have to create all the components before you display your JFrame.
Using a null layout and absolute positioning are discouraged. Swing GUIs have to run on different operating systems with different screen monitor pixel sizes. Your GUI barely fit on my monitor. I left your absolute positioning code alone, but in the future, you should learn to use Swing layout managers.
I made the AlsXYMouseLabelComponent class an inline class. You can have as many inline classes as you want. Generally, though, each class should be in a separate file. I made the classes inline to show you how inline classes are defined, and also so I can paste a runnable example file.
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Minesweeper implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Minesweeper());
}
private JComboBox<String> gameModeDropdown;
private JComboBox<String> difficultyDropdown;
#Override
public void run() {
JPanel panel = new JPanel();
JFrame frame = new JFrame("Minesweeper");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
panel.setLayout(null);
AlsXYMouseLabelComponent alsXYMouseLabel =
new AlsXYMouseLabelComponent();
/**
* Add the component to the DRAG_LAYER of the layered pane (JLayeredPane)
*/
JLayeredPane layeredPane = frame.getRootPane().getLayeredPane();
layeredPane.add(alsXYMouseLabel, JLayeredPane.DRAG_LAYER);
alsXYMouseLabel.setBounds(0, 0, frame.getWidth(), frame.getHeight());
/**
* Add a mouse motion listener, and update the crosshair mouse cursor with the
* xy coordinates as the user moves the mouse
*/
frame.addMouseMotionListener(new MouseMotionAdapter() {
/**
* Detects when the mouse moved and what the mouse's coordinates are.
*
* #param event the event that happens when the mouse is moving.
*/
#Override
public void mouseMoved(MouseEvent event) {
alsXYMouseLabel.x = event.getX();
alsXYMouseLabel.y = event.getY();
alsXYMouseLabel.repaint();
}
});
JLabel title = new JLabel("Minesweeper");
title.setBounds(500, 100, 550, 60);
title.setFont(new Font("Verdana", Font.PLAIN, 50));
panel.add(title);
JLabel gameModePrompt = new JLabel("Game Mode: ");
gameModePrompt.setBounds(280, 335, 300, 25);
gameModePrompt.setFont(new Font("Verdana", Font.PLAIN, 20));
panel.add(gameModePrompt);
String[] gameModes = { "Normal" };
gameModeDropdown = new JComboBox<String>(gameModes);
gameModeDropdown.setBounds(415, 335, 290, 25);
gameModeDropdown.setFont(new Font("Verdana", Font.PLAIN, 20));
panel.add(gameModeDropdown);
JLabel difficultyPrompt = new JLabel("Difficulty: ");
difficultyPrompt.setBounds(800, 335, 240, 25);
difficultyPrompt.setFont(new Font("Verdana", Font.PLAIN, 20));
panel.add(difficultyPrompt);
String[] difficulties = { "Easy", "Medium", "Hard" };
difficultyDropdown = new JComboBox<String>(difficulties);
difficultyDropdown.setSelectedIndex(1);
difficultyDropdown.setBounds(910, 335, 120, 25);
difficultyDropdown.setFont(new Font("Verdana", Font.PLAIN, 20));
panel.add(difficultyDropdown);
JButton playButton = new JButton("Play");
playButton.setBounds(530, 480, 220, 25);
playButton.setFont(new Font("Verdana", Font.PLAIN, 20));
playButton.addActionListener(new PlayListener());
panel.add(playButton);
frame.add(panel);
frame.setSize(1365, 767);
frame.setVisible(true);
}
public class PlayListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
}
}
/**
* A class that shows the xy coordinates near the mouse cursor.
*/
public class AlsXYMouseLabelComponent extends JComponent {
private static final long serialVersionUID = 1L;
public int x;
public int y;
/**
* Uses the xy coordinates to update the mouse cursor label.
*/
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
String coordinates = x + ", " + y; // Get the cordinates of the mouse
g.setColor(Color.red);
g.drawString(coordinates, x, y); // Display the coordinates of the mouse
}
}
}

Centering a String on a custom component

So I have a custom JComponent (An almost completed button, if you will). Here is the source code to the class:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LukeButton extends JComponent implements MouseListener{
//ArrayList of listeners
private final ArrayList<ActionListener> listeners = new ArrayList<ActionListener>();
Shape rec = new RoundRectangle2D.Float(10, 10, 110, 60, 50, 75);
BasicStroke border = new BasicStroke(5);
SpringLayout layout = new SpringLayout();
private String text;
public LukeButton(String text){
this.text = text;
this.setLayout(layout);
this.addMouseListener(this);
}
//Adds a listeners to the list
public void addActionListener(ActionListener e){
listeners.add(e);
}
//Called when button is provoked
public void fireActionListeners(){
if(!listeners.isEmpty()){
ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "LukeButton");
for(ActionListener l: listeners){
l.actionPerformed(evt);
}
}
}
//Listens for click on my component
public void mousePressed(MouseEvent e){
if(rec.contains(e.getPoint())){
rec = new RoundRectangle2D.Float(10, 10, 100, 55, 50, 75);
repaint();
fireActionListeners();
}
}
public void mouseReleased(MouseEvent e){
if(rec.contains(e.getPoint())){
rec = new RoundRectangle2D.Float(10, 10, 110, 60, 50, 75);
repaint();
}
}
//When mouse enters, make border bigger
public void mouseEntered(MouseEvent e){
border = new BasicStroke(8);
repaint();
}
//When mouse leaves, make border smaller
public void mouseExited(MouseEvent e){
border = new BasicStroke(5);
repaint();
}
public Dimension getPreferredSize(){
return new Dimension(130, 80);
}
//Draws my button
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.BLACK);
g2.setStroke(border);
g2.draw(rec);
g2.setColor(new Color(0, 204, 204));
g2.fill(rec);
g2.setColor(Color.BLACK);
g2.drawString(text, 47, 45);
}
//Methods that must be over written.
public void mouseClicked(MouseEvent e){
}
}
My problem is that I do not know how to center the text variable (More or less what the variable consists of) based on the size of the String. The beggining of the String is always in a fixed point. For example if the text variable is equal to something short, the string is going to be far on the left. But if the string is too long, it goes far off the right side of the component. Does anyone know how to center my text variable so it changes it's position based on the size of the string(or a different/better solution of coarse)? Thanks for taking your time to read :)
You can get the Rectangle required to paint the text by using:
FontMetrics fm = g2d.getFontMetrics();
Rectangle2D rect = fm.getStringBounds(text, g2d);
Then to center the text you would get the x/y positions using something like:
int x = (getSize().width - rect.width) / 2;
int y = ((getSize().height - rect.height / 2) + rect.height;

Displaying size in JTextbox based on size of dynamic circle

I'm trying to create a Java program that draws a circle, sliders can resize the circle, 3 other sliders control RGB settings. The problem is that i cannot get the stats (diameter, area and circumference) to display in the JTextBox. Please help its driving me mad!!!
Thanks!
CircleModifier.java
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
#SuppressWarnings("serial")
public class CircleModifier extends JFrame implements ChangeListener {
public DrawingPanel drawingPanel;
public InfoPanel infoPanel;
public JPanel sizePanel;
private JPanel sliderPanel;
private JSlider sizeSlider, redColorSlider, greenColorSlider,
blueColorSlider;
private JLabel sizeLabel, redLabel, greenLabel, blueLabel;
public CircleModifier() {
super("Circle Modifier Application");
setLayout(new BorderLayout());
drawingPanel = new DrawingPanel();
add(drawingPanel, BorderLayout.CENTER);
sliderPanel = new JPanel();
add(sliderPanel, BorderLayout.EAST);
sliderPanel.setBackground(Color.WHITE);
infoPanel = new InfoPanel();
add(infoPanel, BorderLayout.SOUTH);
sliderPanel.setLayout(new GridLayout(2, 4, 0, 1));
sizeLabel = new JLabel("-Size-");
sizeLabel.setForeground(Color.BLACK);
setSizeSlider(new JSlider(JSlider.VERTICAL, 0, 350, 10));
getSizeSlider().setMajorTickSpacing(50);
getSizeSlider().setMinorTickSpacing(25);
getSizeSlider().setPaintTicks(true);
getSizeSlider().setPaintLabels(true);
getSizeSlider().setBackground(Color.WHITE);
getSizeSlider().addChangeListener(this);
redColorSlider = new JSlider(JSlider.VERTICAL, 0, 255, 0);
redColorSlider.setMajorTickSpacing(20);
redColorSlider.setMinorTickSpacing(5);
redColorSlider.setPaintTicks(true);
redColorSlider.setPaintLabels(true);
redColorSlider.setBackground(Color.WHITE);
redColorSlider.addChangeListener(this);
redLabel = new JLabel("-Red-");
redLabel.setForeground(Color.RED);
greenColorSlider = new JSlider(JSlider.VERTICAL, 0, 255, 0);
greenColorSlider.setMajorTickSpacing(20);
greenColorSlider.setMinorTickSpacing(5);
greenColorSlider.setPaintTicks(true);
greenColorSlider.setPaintLabels(true);
greenColorSlider.setBackground(Color.WHITE);
greenColorSlider.addChangeListener(this);
greenLabel = new JLabel("-Green-");
greenLabel.setForeground(Color.GREEN);
blueColorSlider = new JSlider(JSlider.VERTICAL, 0, 255, 0);
blueColorSlider.setMajorTickSpacing(20);
blueColorSlider.setMinorTickSpacing(5);
blueColorSlider.setPaintTicks(true);
blueColorSlider.setPaintLabels(true);
blueColorSlider.setBackground(Color.WHITE);
blueColorSlider.addChangeListener(this);
blueLabel = new JLabel("-Blue-");
blueLabel.setForeground(Color.BLUE);
sliderPanel.add(sizeLabel);
sliderPanel.add(redLabel);
sliderPanel.add(greenLabel);
sliderPanel.add(blueLabel);
sliderPanel.add(getSizeSlider());
sliderPanel.add(redColorSlider);
sliderPanel.add(greenColorSlider);
sliderPanel.add(blueColorSlider);
setSize(800, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void stateChanged(ChangeEvent e) {
int size = getSizeSlider().getValue();
drawingPanel.setDiameter(size);
sizeLabel.setText("-Size-");
int red = redColorSlider.getValue();
int green = greenColorSlider.getValue();
int blue = blueColorSlider.getValue();
drawingPanel.setNewCircleColor(red, green, blue);
redLabel.setText("-Red-");
greenLabel.setText("-Green-");
blueLabel.setText("-Blue-");
}
public static void main(String[] args) {
new CircleModifier();
}
public JSlider getSizeSlider() {
return sizeSlider;
}
public void setSizeSlider(JSlider sizeSlider) {
this.sizeSlider = sizeSlider;
}
}
InfoPane.java
import javax.swing.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import java.awt.*;
import java.awt.event.*;
import java.awt.*;
#SuppressWarnings("serial")
public class InfoPanel extends JPanel {
JTextArea textarea;
JLabel label;
private JTextArea display;
public InfoPanel() {
setLayout(new FlowLayout());
label = new JLabel("Information");
add(label);
display = new JTextArea(5, 30);
display.setText("The Radius is: " + "\nThe Diameter is: "
+ "Dynamic diameter to display here!" + "\nThe Area is: "
+ "\nThe Circumference is: ");
add(display);
}
}
DrawingPanel.java
import javax.swing.*;
import java.awt.*;
#SuppressWarnings("serial")
public class DrawingPanel extends JPanel {
public static String size;
int diameter = 1;
int red = 255, green = 255, blue = 255;
Color newCircleColor = new Color(red, green, blue);
public void paintComponent(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(newCircleColor);
g.fillOval(10, 10, diameter, diameter);
}
public void setDiameter(int newSize) {
diameter = newSize;
repaint();
}
public void setNewCircleColor(int red, int green, int blue) {
newCircleColor = new Color(red, green, blue);
repaint();
}
}
Give InfoPanel a public method,
public void textareaSetText(String text) {
textarea.setText(text);
}
And inside of this, set the text of the JTextArea variable.
Then call this method from within CircleModifier's stateChanged(...) method. If you want to append text, you could also give InfoPanel a similar textareaAppendText(String text) method.

setBounds method isn't working properly?

Well the title explains it, basically the setBounds(int x, int y, int width, int height) method isn't working like I want it too as nothing is being displayed. The point of this code is to get the text from some text fields then close that window and and convert them to JLabel objects to be displayed on the screen but it doesn't do that. Here are some code fragments:
public class Create implements ActionListener {
private JTextArea t1, t2, t3;
private String s1 = t1.getText();
private String s2 = t2.getText();
private String s3 = t3.getText();
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
dispose();
setVisible(false);
t1 = new JTextArea(7, 17);
t2 = new JTextArea(7, 17);
t3 = new JTextArea(7, 17);
JFrame frame2 = new JFrame();
frame2.add(new Test(s1,s2,s3));
frame2.setTitle("Title");
frame2.setSize(700,500);
frame2.setResizable(true);
frame2.setLocationRelativeTo(null);
frame2.setVisible(true);
}
}
}
New class Test:
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
#SuppressWarnings("serial")
public class Test extends JPanel implements ActionListener {
private int w = 250, velx = 2, x = 330;
Timer tm = new Timer(50,this);
public Test(String s1, String s2, String s3) {
setText(s1, s2, s3);
}
public void setText(String s1, String s2, String s3) {
JLabel label1 = new JLabel(s1);
label1.setBounds(100, 100, 500, 500);
JLabel label2 = new JLabel(s2);
label2.setBounds(75, 20, 100, 20);
JLabel label3 = new JLabel(s3);
label3.setBounds(100, 20, 100, 20);
}
}
*****String won't draw on top of rectangle*****
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString("something", 300, 50);
g.drawString("something", 50, 100);
g.drawString("something", 50, 150);
}
public void paint(Graphics g){
tm.setInitialDelay(10000);
super.paint(g);
Graphics2D graph2 = (Graphics2D)g;
Shape Rect1 = new Rectangle2D.Float(330, 30, 250, 390);
graph2.setColor(Color.CYAN);
graph2.fill(Rect1);
Shape Rect2 = new Rectangle2D.Float(x, 30, w, 390);
graph2.setColor(Color.RED);
graph2.fill(Rect2);
tm.start();
}
You actually need to add those label to your JPanel , So that they can get Displayed
public void setText(String s1, String s2, String s3) {
JLabel label1 = new JLabel(s1);
label1.setBounds(100, 100, 500, 500);
JLabel label2 = new JLabel(s2);
label2.setBounds(75, 20, 100, 20);
JLabel label3 = new JLabel(s3);
label3.setBounds(100, 20, 100, 20);
add(label1);// Add the label to your current JPanel
add(label2);
add(label3);
}
When you need absolute positioning , you need to explicitly set the Layout to Null
JPanel#setLayout(null)
Update
How to draw Rectangle on JLabel .
override the paintComponent method of the JLabel. It should first call super.paintComponent, so you get whatever the JLabel contains, then add your own drawing code after that.
#override
public void paintComponent(Graphics g){
super.paintComponent(g)
Rectangle r = new Rectangle(xPos,yPos,width,height);
g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());
}

Drawing Graphics (g) into jpanel

Im trying to draw some bars that have random intergers into the java applet bellow but the overrides have an error im new to java i tried to makr the two areas in code the draw method is at the very bottom the other is the 2nd panel area
What im aiming for
sizes x,y not coordinates
-total size = 200,250
-location gui =200,50
-image = 140,150
-precip = 100,20
-temp = 20,100
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.util.*;
public class Final2 extends JFrame
{
//Panels
JPanel locationGui = new JPanel ();
JPanel temp = new JPanel ();
JPanel percip = new JPanel ();
JPanel image = new JPanel ();
//Location gui components
JButton Enter, Exit;
JTextField location;
JLabel city;
JRadioButton time;
JComboBox Seasons;
//bar # genertor
Random rand = new Random ();
int P = rand.nextInt (100) + 1; //Random Precipitation
int H = rand.nextInt (50) + 1; //Random Heat
public Final2 ()
{
init ();
}
public void init ()
{
Font font = new Font ("impact", Font.PLAIN, 20);
//________________________________________________new panel____________________
locationGui.setBackground (Color.RED);
JLabel guiLabel = new JLabel ("");
guiLabel.setFont (font);
Enter = new JButton ("Enter");
Exit = new JButton ("exit");
city = new JLabel ("What city?");
location = new JTextField (20); //location entry field
Seasons = new JComboBox ();
Seasons.addItem ("Summer");
Seasons.addItem ("Fall");
Seasons.addItem ("Winter");
Seasons.addItem ("Spring");
time = new JRadioButton ("check if night?");
locationGui.add (city);
locationGui.add (location);
locationGui.add (Seasons);
locationGui.add (time);
locationGui.add (guiLabel);
//________________________________________________new panel____________________
temp.setBackground (Color.BLUE);
temp.setLayout (new GridBagLayout ());
JLabel tempLabel = new JLabel ("Temp");
tempLabel.setFont (font);
temp.add (tempLabel);
//________________________________________________new panel____________________
percip.setBackground (Color.GREEN);
JLabel pLabel = new DrawingPanel (); //where it should be
percip.add (pLabel);
//________________________________________________new panel____________________
image.setBackground (Color.ORANGE);
image.setLayout (new GridBagLayout ());
JLabel imageLabel = new JLabel ("Image");
imageLabel.setFont (font);
image.add (imageLabel);
Container contentPane = getContentPane ();
contentPane.setLayout (new BorderLayout ());
contentPane.add (locationGui, BorderLayout.NORTH);
contentPane.add (temp, BorderLayout.EAST);
contentPane.add (percip, BorderLayout.SOUTH);
contentPane.add (image, BorderLayout.CENTER);
setContentPane (contentPane);
setDefaultCloseOperation (EXIT_ON_CLOSE);
setSize (400, 400);
setLocationRelativeTo (null);
setVisible (true);
}
public static void main (String[] args)
{
SwingUtilities.invokeLater (new Runnable ()
{
public void run ()
{
new Final2 ();
}
}
);
}
private class DrawingPanel extends javax.swing.JPanel {//area i have issues with atm
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
drawPercip(g);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 400);
}
}
public void drawPercip (Graphics g)
{
//Precipitation Bar
g.setColor (Color.black);
g.drawRect (40, 170, 100, 20); //outline of bar
g.setColor (Color.blue);
g.fillRect (40 + 1, 170 + 4, P, 14); //indicator bar (+4 puts space beetween outline bar)
}
public void drawTemp (Graphics g)
{
//Temparature Bar
g.setColor (Color.red);
g.fillRect (170 + 4, 50, 14, 100); //Covers in
g.setColor (Color.black);
g.drawRect (170, 50, 20, 100); //outline of bar
g.setColor (Color.white);
g.fillRect (170 + 4, 50 + 1, 16, 100 - H); //indicator bar (+4 puts space beetween outline bar)
}
}
my current Errors (4) are happening in this block of code at the #override the only message provided are "illegal token" and "unexpected symbols ignored" idk why it doesn't give more information
private class DrawingPanel extends javax.swing.JPanel {//area i have issues with atm
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
drawPercip(g);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 400);
}
First I seen no applet,
Second, DrawingPanel is not a JLabel
JLabel pLabel = new DrawingPanel(); //where it should be
Change the pLable type to JComponent or JPanel or DrawingPanel depending on what you want to be able to access out of each class.
Third, you should not rely on magic numbers
public void drawPercip(Graphics g) {
//Precipitation Bar
g.setColor(Color.black);
g.drawRect(40, 170, 100, 20); //outline of bar
g.setColor(Color.blue);
g.fillRect(40 + 1, 170 + 4, P, 14); //indicator bar (+4 puts space beetween outline bar)
}
public void drawTemp(Graphics g) {
//Temparature Bar
g.setColor(Color.red);
g.fillRect(170 + 4, 50, 14, 100); //Covers in
g.setColor(Color.black);
g.drawRect(170, 50, 20, 100); //outline of bar
g.setColor(Color.white);
g.fillRect(170 + 4, 50 + 1, 16, 100 - H); //indicator bar (+4 puts space beetween outline bar)
}
There is no guarantee that the height and width of the panel is what you think it might be. Make use of the getWidth and getHeight methods
Fourth, if you intend to have more the one DrawingPanel, you should make
int P = rand.nextInt(100) + 1; //Random Precipitation
int H = rand.nextInt(50) + 1; //Random Heat
Part of the DrawingPanel.
You should also make the time to read through Code Conventions for the Java Programming Language

Categories