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
Related
I'm using swing Java to try to do something with java. Now I want to rotate JLabel and I did that. But unfortunelately, a part of my text in JLabel is erased (as in the image below). I have tried search but seem no one has problems as same as mine. I guess it's occured caused JLabels they overlaped.
and this is my code
serviceName[j] = new JLabel(name){
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
AffineTransform aT = g2.getTransform();
Shape oldshape = g2.getClip();
aT.rotate(Math.toRadians(300));
g2.setTransform(aT);
g2.setClip(oldshape);
super.paintComponent(g);
}
};
Can you give me the way to solved it
You should restore original transform and clip after your painting. Like this
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
AffineTransform aT = g2.getTransform();
Shape oldshape = g2.getClip();
g2.rotate(Math.toRadians(300));
super.paintComponent(g);
g2.setTransform(aT);
g2.setClip(oldshape);
}
Your JLabel subclass should also override getPreferredSize() to report the size it will be when it is rotated; otherwise the any layout manager that uses asks your component for its preferred size will use JLabel's version, which assumes the text is drawn horizontally.
Instead of attempting to rotate the component, another approach would be to create a Text Icon and add the Icon to a JLabel.
Once you have created the TextIcon you can then create a Rotated Icon to add to the label. The RotatedIcon will calculate the proper size of the Icon so therefore the size of the label will also be correct and no custom painting is required.
So the basic code would be something like:
JLabel label = new JLabel();
TextIcon textlIcon = new TextIcon(label, "Rotated Text");
label.setIcon( new RotatedIcon(textIcon, 300) );
Edit:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.table.*;
import java.io.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
OverlapLayout layout = new OverlapLayout(new Point(20, 0));
setLayout( layout );
addLabel("one");
addLabel("two");
addLabel("three or more");
addLabel("four");
}
private void addLabel(String text)
{
JLabel label = new JLabel();
TextIcon textIcon = new TextIcon(label, text);
label.setIcon( new RotatedIcon(textIcon, 300) );
label.setVerticalAlignment(JLabel.BOTTOM);
add(label);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
This example also uses the Overlap Layout so the labels can be painted over top of one another.
You may find some hints from this small program. Experiment on the values of setPrefferedSize to have more ideas. If you still can't solve the problem, please edit and add more codes in your question above.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import javax.swing.*;
public class InclinedLabels extends JFrame{
/** Creates a new instance of InclinedLabels */
public InclinedLabels() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel jPanel1 = new JPanel();
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
add(jPanel1);
JPanel jPanel2 = new JPanel();
jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel2.setPreferredSize(new Dimension(10, 100));
add(jPanel2, BorderLayout.NORTH);
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel1.setPreferredSize(new java.awt.Dimension(200, 200));
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-400)/2, (screenSize.height-352)/2, 300, 352);
String str = "The quick brown fox jumps over the lazy dog";
String[] word = str.split(" ");
JLabel[] serviceName = new JLabel[str.length()];
String name;
for (int j=0; j<word.length; j++) {
name = word[j];
serviceName[j] = new JLabel(name){
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
AffineTransform aT = g2.getTransform();
Shape oldshape = g2.getClip();
aT.rotate(Math.toRadians(300));
g2.setTransform(aT);
g2.setClip(oldshape);
super.paintComponent(g);
}
};
serviceName[j].setPreferredSize(new Dimension(50,20));
serviceName[j].setBorder(BorderFactory.createLineBorder(Color.RED));
jPanel1.add(serviceName[j]);
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new InclinedLabels().setVisible(true);
}
});
}
}
Update:
I found a much closer hint that may solve this problem. The big factor here is the component layout. The null layout allows overlapping of JLabel components so it is the most appropriate layout to be used here. Then you have to customize the location and size of the labels through the setBounds method. In the code below there is serviceName[j].setBounds(xOffset + j*20,180, 170, 15); So in every loop iteration, the x location of the label is increased by 20. The size of all labels is 170 by 15. I also placed temporary borders to the components to help in understanding the output.
import java.awt.*;
import java.awt.geom.AffineTransform;
import javax.swing.*;
public class InclinedLabels extends JFrame{
/** Creates a new instance of InclinedLabels */
public InclinedLabels() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-360)/2, (screenSize.height-352)/2, 360, 352);
JPanel jPanel1 = new JPanel();
jPanel1.setBorder(BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel1.setLayout(null); // null layout allows overlapping of components
add(jPanel1);
JPanel jPanel2 = new JPanel();
jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel2.setPreferredSize(new Dimension(10, 100));
add(jPanel2, BorderLayout.NORTH);
String str = "The quick brown fox jumpsssssssssssss123456 over the lazy dogssssssssssssss123456";
String[] word = str.split(" ");
JLabel[] serviceName = new JLabel[str.length()];
String name;
int xOffset = 30;
for (int j=0; j<word.length; j++) {
name = word[j];
serviceName[j] = new JLabel(name){
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
AffineTransform aT = g2.getTransform();
Shape oldshape = g2.getClip();
aT.rotate(Math.toRadians(300));
g2.setTransform(aT);
g2.setClip(oldshape);
super.paintComponent(g2);
}
};
serviceName[j].setBounds(xOffset + j*20,180, 170, 15); // experiment here
serviceName[j].setBorder(BorderFactory.createLineBorder(Color.RED));
jPanel1.add(serviceName[j]);
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new InclinedLabels().setVisible(true);
}
});
}
}
The limitation that I found in the code above is the width of the parent panel. In the example, the label having the text dogssssssssssssss123456 was not printed in whole. This can be overcome by increasing the width of the frame which in turn increases the width of jPanel1.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
public class Test {
public static void main(String[] args) {
// Create the first label, which will be rotated later.
Test.RotateLabel one = new Test.RotateLabel( "Rotated", 100, 100 );
one.setRotation( 270 );
JLayeredPane pane = new JLayeredPane();
pane.setLayer( one, JLayeredPane.DEFAULT_LAYER );
pane.add( one );
pane.setBorder(new javax.swing.border.LineBorder(Color.BLACK,1));
// Put the container pane in a frame and show the frame.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add( pane );
frame.setSize( 500, 500 );
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
static class RotateLabel extends JLabel {
private static final long serialVersionUID = 1L;
private int angle = 0;
public RotateLabel( String text, int x, int y ) {
super( text );
setBorder( new javax.swing.border.CompoundBorder(
new javax.swing.border.LineBorder( Color.red, 1), getBorder() ) );
int width = getPreferredSize().width;
int height = getPreferredSize().height;
setBounds(x, y, width, height);
}
#Override
public void paintComponent( Graphics g ) {
Graphics2D gx = (Graphics2D) g;
Shape old = gx.getClip();
gx.rotate(-Math.toRadians(45), getWidth() / 2, getHeight() / 2);
gx.setClip(old);
super.paintComponent(gx);
}
public void setRotation( int angle ) { this.angle = angle; }
}
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.
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());
}
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);
}
}
}
When i run my program everything works as planned except that the button i have to change the cards on the screen does not appear until it is moused over. Im assuming this is because whatever container that is holding the images is over it but i dont know how to move it into the background or even what kind of container i can use to add images to.
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.util.Random;
import java.awt.event.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class oneplayer extends JFrame {
BufferedImage image1, image2, image3, image4;
Random gen = new Random();
public void redo() {
int p1, p2, p3, p4;
p1 = gen.nextInt(13) + 1;
p2 = gen.nextInt(13) + 14;
p3 = gen.nextInt(13) + 27;
p4 = gen.nextInt(13) + 40;
try {
File input1 = new File("C:/Users/Mike/Desktop/eclipse/workspace/inClass/src/" + p1 + ".png");
File input2 = new File("C:/Users/Mike/Desktop/eclipse/workspace/inClass/src/" + p2 + ".png");
File input3 = new File("C:/Users/Mike/Desktop/eclipse/workspace/inClass/src/" + p3 + ".png");
File input4 = new File("C:/Users/Mike/Desktop/eclipse/workspace/inClass/src/" + p4 + ".png");
image1 = ImageIO.read(input1);
image2 = ImageIO.read(input2);
image3 = ImageIO.read(input3);
image4 = ImageIO.read(input4);
} catch (IOException ie) {
System.out.println("Error:"+ie.getMessage());
}
repaint();
}
public oneplayer() {
JPanel buttonPanel = new JPanel();
setLayout(new BorderLayout());
JButton refresh = new JButton("Refresh");
refresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
redo();
}
});
add(buttonPanel, BorderLayout.SOUTH);
buttonPanel.add(refresh, BorderLayout.CENTER);
redo();
}
public void paint(Graphics g) {
g.drawImage(image1, 20, 55, null);
g.drawImage(image2, 96, 55, null);
g.drawImage(image3, 172, 55, null);
g.drawImage(image4, 248, 55, null);
}
public static void main(String args[]) {
oneplayer frame = new oneplayer();
frame.setTitle("Random Cards");
frame.setSize(350, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Don't override paint() method. Instead override paintComponent() of main container.
Call super.paintComponent(g)
Don't extend JFrame but e.g. JPanel, add all you content to the panel and set the panel as a content pane of usual JFrame instance.
You'll need to call super.paint(g) inside your paint(Graphics) function to ensure that the Swing components inside the frame are properly displayed.
Haven't tested this with your sample, but I think you need to call the parent class's paint when overriding paint on your Frame in order for the Frame's components to show up. Like so:
public void paint(Graphics g) {
super.paint(g);
g.drawImage(image1, 20, 55, null);
g.drawImage(image2, 96, 55, null);
g.drawImage(image3, 172, 55, null);
g.drawImage(image4, 248, 55, null);
}