Converting strings into int - java

im new programming, im trying to get some values from jtextfield and then convert them into int to use them as a paramter to draw a polygon, but im having trouble converting the strings into int, please help me, what is the best way t do this this is my code:
this is where im getting the data from textfield
import java.awt.BorderLayout;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Transformacion extends JFrame {
Transformacion_R2 grafico= new Transformacion_R2();
public Transformacion()
{
// Use helper methods
createpuntosx();
createpuntosy();
createButton();
xa=puntoFieldx1.getText();
xb=puntoFieldx2.getText();
xc=puntoFieldx3.getText();
xd=puntoFieldx4.getText();
createPanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public void createButton()
{
graficar = new JButton("Grafica");
class PoligonoListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
JFrame frame = new JFrame(Transformacion_R2.TITLE);
frame.setContentPane(new Transformacion_R2());
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
ActionListener listener = new PoligonoListener();
graficar.addActionListener(listener);
}
public void createpuntosx()
{
puntosx = new JLabel("Puntos x: ");
final int FIELD_WIDTH = 4;
puntoFieldx1 = new JTextField(FIELD_WIDTH);
puntoFieldx2 = new JTextField(FIELD_WIDTH);
puntoFieldx3 = new JTextField(FIELD_WIDTH);
puntoFieldx4 = new JTextField(FIELD_WIDTH);
}
public void createpuntosy()
{
puntosy = new JLabel("Puntos y: ");
final int FIELD_WIDTH = 4;
puntoFieldy1 = new JTextField(FIELD_WIDTH);
puntoFieldy2 = new JTextField(FIELD_WIDTH);
puntoFieldy3 = new JTextField(FIELD_WIDTH);
puntoFieldy4 = new JTextField(FIELD_WIDTH);
}
public void createPanel()
{
JPanel northPanel = new JPanel();
northPanel.add(puntosx);
northPanel.add(puntoFieldx1);
northPanel.add(puntoFieldx2);
northPanel.add(puntoFieldx3);
northPanel.add(puntoFieldx4);
northPanel.add(puntosy);
northPanel.add(puntoFieldy1);
northPanel.add(puntoFieldy2);
northPanel.add(puntoFieldy3);
northPanel.add(puntoFieldy4);
add(northPanel,BorderLayout.NORTH);
JPanel centerPanel = new JPanel();
add(centerPanel,BorderLayout.CENTER);
JPanel southPanel = new JPanel();
southPanel.add(graficar);
add(southPanel,BorderLayout.SOUTH);
}
private JLabel puntosx;
private JTextField puntoFieldx1;
private JTextField puntoFieldx2;
private JTextField puntoFieldx3;
private JTextField puntoFieldx4;
private JLabel puntosy;
private JTextField puntoFieldy1;
private JTextField puntoFieldy2;
private JTextField puntoFieldy3;
private JTextField puntoFieldy4;
private JButton graficar;
public static String xa;
public static String xb;
public static String xc;
public static String xd;
public static String ya;
public static String yb;
public static String yc;
public static String yd;
private static final int FRAME_WIDTH = 800;
private static final int FRAME_HEIGHT = 200;
and this is where i'm converting them into string
import java.awt.*;
import java.awt.geom.AffineTransform;
import javax.swing.*;
/** Test applying affine transform on vector graphics */
#SuppressWarnings("serial")
public class Transformacion_R2 extends JPanel{
public static final int CANVAS_WIDTH = 1000;
public static final int CANVAS_HEIGHT = 1200;
public static final String TITLE = "Tranformacion Lineal R2";
//DECLARO PUNTOS DEL POLIGONO
int a=Integer.parseInt (Transformacion.xa);
int b=Integer.parseInt (Transformacion.xb);
int c=Integer.parseInt (Transformacion.xc);
int d=Integer.parseInt (Transformacion.xd);
int[] polygonXs = { a, b, c, d};
int[] polygonYs = { 80, 70, 80, 40};
Shape shape = new Polygon(polygonXs, polygonYs, polygonXs.length);
/** Constructor to set up the GUI components */
public Transformacion_R2() {
setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
}
/** Custom painting codes on this JPanel */
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.BLACK);
Graphics2D g2d = (Graphics2D)g;
AffineTransform saveTransform = g2d.getTransform();
AffineTransform identity = new AffineTransform();
g2d.setTransform(identity);
g2d.setColor(Color.GREEN);
g2d.fill(shape);
//TRANSFORMACIONES
double x = 200.0, y = -500.0;
g2d.translate(x, y);
g2d.rotate(Math.toRadians(30.0));
g2d.scale(10, 9);
g2d.setColor(Color.RED);
g2d.fill(shape);
g2d.setTransform(saveTransform);
}
/** The Entry main method */
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame(TITLE);
frame.setContentPane(new Transformacion_R2());
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
thank you for your help

Your xa is always going to be null unless the constructor of Transformacion runs.
In this code constructor and initializations for Transformacion_R2 run before constructor of Transformacion. So make sure you call the constructor of Transformacion before Transformacion_R2. To remove cyclic initalization remove Transformacion_R2 grafico= new Transformacion_R2(); from Transformacion Eg. code could be
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame(TITLE);
Transformacion trns = new Transformacion();
frame.setContentPane(new Transformacion_R2());
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

int number = Integer.parseInt(jTextField.getText());
The typical method of doing it can be found at
How to convert a String to an int in Java?
which you seem to be doing properly. What issues are you running into, more specifically?
If the jtextField is not set, you need to handle the possiblity of error.
int number;
try {
number = Integer.parseInt(jTextField.getText());
} catch(NumberFormatException e) {
number = 0; // Handle the error or give a default value
}

Related

Can I use actionListeners on JPanels?

I am trying to add and actionListener to a JPanel it's self but keep getting the error"cannot find symbol". I was just wondering if it is possible to do this as I want to be able to click on the panel and make the colour change. Any help would be appreciated.
Here is what i have so far.
import java.awt.*;
import javax.swing.*;
import javax.swing.JPanel.*;
import java.awt.Color.*;
import java.awt.event.*;
/**
* Write a description of class SimpleFrame here.
*
* #author OFJ2
* #version
*/
public class Game extends JFrame
implements ActionListener
{
private final int ROWS = 5;
private final int COLUMS = 2;
private final int GAP = 2;
private final int SIZE = ROWS * COLUMS;
private int x;
private JPanel leftPanel = new JPanel(new GridLayout(ROWS,COLUMS, GAP,GAP));
private JPanel [] gridPanel = new JPanel[SIZE];
private JPanel middlePanel = new JPanel();
private JPanel rightPanel = new JPanel();
private Color col1 = Color.GREEN;
private Color col2 = Color.YELLOW;
private Color tempColor;
public Game()
{
super("Chasing Bombs OFJ2");
setSize(200,200);
setVisible(true);
makeFrame();
}
public void makeFrame()
{
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayout());
leftPanel.setLayout(new GridLayout(ROWS, COLUMS));
//JLabel label2 = new JLabel("Pocahontas");
JButton playButton = new JButton("Play Game");
JButton exitButton = new JButton("Exit");
JButton easyButton = new JButton("Easy");
JButton mediumButton = new JButton("Medium");
JButton hardButton = new JButton("Hard");
add(leftPanel);
add(middlePanel, new FlowLayout());
add(rightPanel);
setGrid();
middlePanel.add(playButton);
middlePanel.add(exitButton);
rightPanel.add(easyButton);
rightPanel.add(mediumButton);
rightPanel.add(hardButton);
leftPanel.setBackground(Color.PINK);
middlePanel.setBackground(Color.RED);
easyButton.addActionListener(this);
mediumButton.addActionListener(this);
hardButton.addActionListener(this);
playButton.addActionListener(this);
exitButton.addActionListener(this);
}
public void setGrid()
{
for(int x = 0; x < SIZE; x++) {
gridPanel[x] = new JPanel();
gridPanel[x].setBorder(BorderFactory.createLineBorder(Color.BLACK));
leftPanel.add(gridPanel[x]);
gridPanel[x].setBackground(Color.GREEN);
gridPanel[x].addActionListener(this);
}
}
#Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == gridPanel[0]){
gridPanel[x].setBackground(Color.BLACK);
}
}
}
I have tried to find if there is any other method that is needed to do this but cant find anything. Is it possible that I will have to add a button to fill each of the panels to make this work?
Thanks!
It defaults to no addActionListener, and the code below is a reference suggestion.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
class GPanel extends JPanel {
private List<ActionListener> listenerList = new ArrayList<>();
public GPanel() {
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
var event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "GPanel");
for (var i : listenerList) {
i.actionPerformed(event);
}
}
});
}
public void addActionListener(ActionListener listener) {
listenerList.add(listener);
}
}
public class ActionListenerTest extends JFrame {
public static void main(String[] args) {
new ActionListenerTest();
}
public ActionListenerTest() {
GPanel test = new GPanel();
test.setBackground(Color.BLUE);
add(test);
test.addActionListener(e-> {
System.out.println("Click: " + e.getActionCommand());
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
}

How can I replace one JPanel with another JPanel in the same position?

I have a JFrame with about four frames. After a given action I want to replace one panel with another in the same position. My method for switching them looks like this (the this object is a class which extends JFrame):
public void switchPanel(){
mainPanel.remove(introPanel);
mainPanel.add(questionPanel);
this.repaint();
}
The original creation of the window looks like this:
mainPanel.add(titlePanel);
mainPanel.add(sidePanel);
mainPanel.add(introPanel);
You ask:
How can I replace one JPanel with another JPanel in the same position?
Very easily: use a CardLayout as this tool was built for just this situation.
If you had the following constants:
public static final String INTRO_PANEL = "intro panel";
public static final String QUESTION_PANEL = "question panel";
and added your JPanel's like so
mainPanel.setLayout(cardLayout);
mainPanel.add(introPanel, INTRO_PANEL);
mainPanel.add(questionPanel, QUESTION_PANEL);
cardLayout.show(mainPanel, INTRO_PANEL);
Then you could swap JPanels with:
cardLayout.show(mainPanel, QUESTION_PANEL);
would be all that were needed to show the swap, assuming that QUESTION_PANEL is a String constant that was used when you added the questionPanel to the mainPanel, and that the mainPanel uses the CardLayout.
For example:
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
public class SwapPanels extends JPanel {
public static final String INTRO_PANEL = "intro panel";
public static final String QUESTION_PANEL = "question panel";
private static final int PREF_W = 500;
private static final int PREF_H = 400;
private CardLayout cardLayout = new CardLayout();
private JPanel introPanel;
private JPanel questionPanel;
private Random random = new Random();
public SwapPanels() {
introPanel = createPanel("Introduction");
questionPanel = createPanel("Question");
setLayout(cardLayout);
add(introPanel, INTRO_PANEL);
add(questionPanel, QUESTION_PANEL);
int delay = 3 * 1000; // show intro for 3 seconds
new Timer(delay, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(SwapPanels.this, QUESTION_PANEL);
((Timer) e.getSource()).stop();
}
}).start();
}
private JPanel createPanel(String title) {
int rgb = random.nextInt();
Color color = new Color(rgb);
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createLineBorder(color, 60));
panel.add(new JLabel(title));
return panel;
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
SwapPanels mainPanel = new SwapPanels();
JFrame frame = new JFrame("SwapPanels");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
after the remove method you have to run the validate method that's all. The code will be like this:
public void switchPanel(){
mainPanel.remove(introPanel);
mainPanel.add(questionPanel);
mainPanel.validate();
}
I hope that helps. Salam

getText from JTextField in 1 class and place it on a label in the other

I have one class Names and it has a JTextField. I am trying to place getText from this textfield and save it in the variable nameString1. I then want the other class Game to call Names and place the string collected from ``the JTextField onto a label. For some reason it is not displaying. Please let me know if there are any rookie errors, I am only year 10.
Names
package com.aqagame.harrykitchener;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Names
{
private JLabel player1Label;
private JTextField player1Input;
private JButton nextButton;
public String nameString1;
public Names()
{
final JFrame window = new JFrame("Player 1 username");
JPanel firstPanel = new JPanel(new GridLayout(3,2));
player1Label = new JLabel("Player 1");
player1Input = new JTextField();
nextButton = new JButton("Next");
firstPanel.add(player1Label);
firstPanel.add(player1Input);
firstPanel.add(nextButton);
nextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
nameString1 = player1Input.getText();
System.out.print(nameString1);
Names2 names2Call = new Names2();
window.dispose();
}
});
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(firstPanel);
window.setSize(250, 150);
window.setLocationRelativeTo(null);
window.setVisible(true);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Names();
}
});
}
}
Game
package com.aqagame.harrykitchener;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Game
{
private JLabel player1Str, player2Str;
public Game()
{
JFrame window = new JFrame ("Main Game");
JPanel drawPanel = new JPanel(new GridLayout(3, 1))
{
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
int width = getWidth() / 4;
int height = getHeight() / 11;
for(int i = 0; i<4; i++)
{
g.drawLine(i * width, 0, i * width, 700);
}
for(int i = 0; i<4; i++)
{
g.drawLine(i * width, 0, i * width, 700);
}
}
};
Names namesCall2 = new Names();
player1Str = new JLabel(namesCall2.nameString1);
drawPanel.add(player1Str);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(drawPanel);
window.setSize(700, 600);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setResizable(false);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new Game();
}
});
}
}
The problem is that you are setting the label without getting the textfield text. The JLabel on your Game wont change by the time you click the button..
Okie I made some change in you classes What I did is that I maid an interface which will be called when your button is pressed
Here is the interface:
public interface Lawl {
public void changename(String name);
}
I then implemented this interface to the game:
public class Game implements Lawl
{
private JLabel player1Str, player2Str;
JPanel drawPanel;
Names namesCall2;
public Game()
{
JFrame window = new JFrame ("Main Game");
drawPanel = new JPanel(new GridLayout(3, 1))
{
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
int width = getWidth() / 4;
int height = getHeight() / 11;
for(int i = 0; i<4; i++)
{
g.drawLine(i * width, 0, i * width, 700);
}
for(int i = 0; i<4; i++)
{
g.drawLine(i * width, 0, i * width, 700);
}
}
};
// Names namesCall2 = new Names(this);
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
namesCall2 = new Names(Game.this);
}
});
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(drawPanel);
window.setSize(700, 600);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setResizable(false);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new Game();
}
});
}
#Override
public void changename(String name) {
System.out.println("I am clicked");
player1Str = new JLabel(name);
drawPanel.add(player1Str);
drawPanel.revalidate();
}
}
In the names class:
public class Names
{
private JLabel player1Label;
private JTextField player1Input;
private JButton nextButton;
public String nameString1;
public Names(){}
public Names(final Lawl game)
{
final JFrame window = new JFrame("Player 1 username");
JPanel firstPanel = new JPanel(new GridLayout(3,2));
player1Label = new JLabel("Player 1");
player1Input = new JTextField();
nextButton = new JButton("Next");
firstPanel.add(player1Label);
firstPanel.add(player1Input);
firstPanel.add(nextButton);
nextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
nameString1 = player1Input.getText();
System.out.print(nameString1);
game.changename(nameString1);
// Names2 names2Call = new Names2();
window.dispose();
}
});
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(firstPanel);
window.setSize(250, 150);
window.setLocationRelativeTo(null);
window.setVisible(true);
}
}
How it works??
I created an interface and implemented it to the game class then pass the reference of the interface to the Names class which will then be called when button is clicked..
when it is called game.changename(nameString1);by the button clicked it will then be called on the game class as you could see there is an method from the implemented inteface in the game class that will be called when you click the button..
If you want to chain data dont create a new Main thread to just execute a new Window.. just use the one I did in the code..
replace
public final static JTextField player1Input;
instead of
private JTextField player1Input;

actionPerformed skip a step

I want everytime i click on the button "bouton" to execute the function
boutonPane.Panel2(h, ....) which is supposed to display h circles. So i want 2 then 3 then 4, then 5... circles.
The problem is that it is not displaying the step with number 4. I see the function is called in the console but on the screen it does really 2, (press button) 3, (press button) 5, (press button)9. I dont see 4. I dont see 6,7,8.. Could you tell me what is the problem please? Here is the code:
public class Window extends JFrame implements ActionListener {
int lg = 1000; int lrg = 700;
int h = 2;
Panel b = new Panel();
private JButton btn = new JButton("Start");
JButton bouton = new JButton();
private JPanel container = new JPanel();
public Window(){
this.setTitle("Animation");
this.setSize(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
container.setBackground(Color.white);
container.setLayout(new BorderLayout());
JPanel top = new JPanel();
btn.addActionListener(this);
top.add(btn);
container.add(top);
this.setContentPane(container);
this.setVisible(true);
}
public void Window2()
{
System.out.println("windows2");
this.setTitle("ADHD");
this.setSize(lg, lrg);
this.setLocationRelativeTo(null);
bouton.addActionListener(this);
if(h<11)
{
Panel boutonPane = new Panel();
boutonPane.Panel2(h, Color.BLUE ,lg, lrg, this.getGraphics());
System.out.println("draw"+h);
boutonPane.add(bouton);
this.add(boutonPane);
this.setContentPane(boutonPane);
this.revalidate();
this.repaint();
}
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if((JButton)e.getSource()==btn)
{
System.out.println("pressed0");
Window2();
}
if((JButton)e.getSource()==bouton)
{
h++;
System.out.println("pressed"+h);
Window2();
}
}
}
Here is a the Panel class:
public class Panel extends JPanel
{
int m;
int i=1;
int a=0, b=0, tremp=0;
Color cc;
int lgi, lrgi;
int [] ta;
int [] tb;
Graphics gi;
int u=0;
Panel()
{
}
public void Panel2(int n, Color c, int lg, int lrg, Graphics g){
m=n;
cc=c;
gi=g;
lgi=lg;
lrgi=lrg;
ta = new int [n]; ta[0]=0;
tb = new int [n]; tb[0]=0;
}
public void paintComponent( final Graphics gr){
gr.setColor(Color.red);
for(int it=0; it<m;it++)
{
ta[it]=100*it;
tb[it]=100*it;
gr.fillOval(ta[it],tb[it], 150, 150);
}
}
}
"But would you have an idea of another, correct, way to do what I want please?"
You should only have one panel for the circles. There's absolutely no need to keep creating new panel.
Use a List for Ellipse2D objects. Just loop through them in the paintComponent method.
When you want to add a new circle, just add a new Ellipse2D object to the List and call repaint()
Here's an example.
NOTE Accept Gijs Overvliet's answer, as his was the one that answered your problem. I just wanted to share some insight.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class EllipseList extends JPanel {
private static final int D_W = 700;
private static final int D_H = 500;
private static final int CIRCLE_SIZE = 50;
private List<Ellipse2D> circles;
private double x = 0;
private double y = 0;
private CirclePanel circlePanel = new CirclePanel();
public EllipseList() {
circles = new ArrayList<>();
JButton jbtAdd = createButton();
JFrame frame = new JFrame();
frame.add(jbtAdd, BorderLayout.NORTH);
frame.add(circlePanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JButton createButton() {
JButton button = new JButton("Add");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
circles.add(new Ellipse2D.Double(x, y, CIRCLE_SIZE, CIRCLE_SIZE));
x += CIRCLE_SIZE * 0.75;
y += CIRCLE_SIZE * 0.75;
circlePanel.repaint();
}
});
return button;
}
public class CirclePanel extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(Color.RED);
for (Ellipse2D circle : circles) {
g2.fill(circle);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(D_W, D_H);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new EllipseList();
}
});
}
}
Try this:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Window extends JFrame implements ActionListener
{
int lg = 1000;
int lrg = 700;
int h = 2;
Panel b = new Panel();
private JButton btn = new JButton("Start");
JButton bouton = new JButton();
private JPanel container = new JPanel();
Panel boutonPane = new Panel();
public Window()
{
this.setTitle("Animation");
this.setSize(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
container.setBackground(Color.white);
container.setLayout(new BorderLayout());
JPanel top = new JPanel();
btn.addActionListener(this);
top.add(btn);
container.add(top);
this.setContentPane(container);
this.setVisible(true);
}
public void Window2()
{
System.out.println("windows2");
this.setTitle("ADHD");
this.setSize(lg, lrg);
this.setLocationRelativeTo(null);
bouton.addActionListener(this);
if (h < 11)
{
boutonPane.Panel2(h, Color.BLUE, lg, lrg, this.getGraphics());
System.out.println("draw" + h);
boutonPane.add(bouton);
this.add(boutonPane);
this.setContentPane(boutonPane);
updateWindow2();
}
this.setVisible(true);
}
public void updateWindow2()
{
boutonPane.Panel2(h, Color.BLUE, lg, lrg, this.getGraphics());
this.revalidate();
this.repaint();
}
public void actionPerformed(ActionEvent e)
{
if ((JButton) e.getSource() == btn)
{
System.out.println("pressed0");
Window2();
}
if ((JButton) e.getSource() == bouton)
{
h++;
System.out.println("pressed" + h);
updateWindow2();
}
}
public static void main(String[] args)
{
Test t = new Test();
}
}
What you did wrong was adding a new BoutonPane every time you clicked the button. The next time you clicked the button, you didn't click ONE button, but TWO buttons, adding two more boutonPanes, and two more buttons. This multiplies very quickly.
What I did was the following:
make boutonPane a class member variable
call window2() only once
create a method updateWindow2() for updating the circles. Call that method from window2() and actionPerformed().

Component removing images when added

I am currently having a problem with JFrame and Images. This program uses an Applet then adds it to a JFrame in a different class, so it can be ran as either an Applet or an Application. Currently, the frame holds only a handful of images, and no components. I recently attempted to add a JTextField using absolute positioning (LayoutManger is null) and it works fine, except all the images are removed, leaving me with just a JTextField. Why is this happening? How can I fix it? My code is posted below. Thanks!
The Main Class (Creates the Applet and Images):
package net.xenix.src;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JComponent;
import javax.swing.Timer;
public class XenixMain extends JApplet implements ActionListener
{
private static final long serialVersionUID = 1L;
private static int pixelSize = 2;
public static Dimension size = new Dimension(1600, 900);
public static Dimension pixel = new Dimension(size.width / pixelSize, size.height / pixelSize);
public static String name = "Xenix";
public static final int WIDTH = 1600;
public static final int HEIGHT = 900;
//Finding player Windows name
static String username = System.getProperty("user.name");
public static int secondsCount = 0;
//Shortcut to image directory
public static String imagePath = "C:\\Users\\" + username + "\\Desktop\\Xenix Dev\\Xenix\\resources\\graphics\\";
private static PaintSurface canvas;
public static ImageIcon XenixBackgroundIcon = new ImageIcon(imagePath + "XenixBackground.png");
public static Image XenixBackground = XenixBackgroundIcon.getImage();
public static ImageIcon XenixLogoIcon = new ImageIcon(imagePath + "XenixLogo.png");
public static Image XenixLogo = XenixLogoIcon.getImage();
public static ImageIcon HeartContainerFullIcon = new ImageIcon(imagePath + "HeartContainerFull.png");
public static Image HeartContainerFull = HeartContainerFullIcon.getImage();
public static ImageIcon HeartContainer9Icon = new ImageIcon(imagePath + "HeartContainer9.png");
public static Image HeartContainer9 = HeartContainer9Icon.getImage();
public static ImageIcon HeartContainer8Icon = new ImageIcon(imagePath + "HeartContainer8.png");
public static Image HeartContainer8 = HeartContainer8Icon.getImage();
public static ImageIcon HeartContainer7Icon = new ImageIcon(imagePath + "HeartContainer7.png");
public static Image HeartContainer7 = HeartContainer7Icon.getImage();
public static ImageIcon HeartContainer6Icon = new ImageIcon(imagePath + "HeartContainer6.png");
public static Image HeartContainer6 = HeartContainer6Icon.getImage();
public static ImageIcon HeartContainer5Icon = new ImageIcon(imagePath + "HeartContainer5.png");
public static Image HeartContainer5 = HeartContainer5Icon.getImage();
public static ImageIcon HeartContainer4Icon = new ImageIcon(imagePath + "HeartContainer4.png");
public static Image HeartContainer4 = HeartContainer4Icon.getImage();
public static ImageIcon HeartContainer3Icon = new ImageIcon(imagePath + "HeartContainer3.png");
public static Image HeartContainer3 = HeartContainer3Icon.getImage();
public static ImageIcon HeartContainer2Icon = new ImageIcon(imagePath + "HeartContainer2.png");
public static Image HeartContainer2 = HeartContainer2Icon.getImage();
public static ImageIcon HeartContainer1Icon = new ImageIcon(imagePath + "HeartContainer1.png");
public static Image HeartContainer1 = HeartContainer1Icon.getImage();
public static ImageIcon HeartContainerDepletedIcon = new ImageIcon(imagePath + "HeartContainerDepleted.png");
public static Image HeartContainerDepleted = HeartContainerDepletedIcon.getImage();
public static ImageIcon HealthTextIcon = new ImageIcon(imagePath + "HealthText.png");
public static Image HealthText = HealthTextIcon.getImage();
public static ImageIcon ForwardSlashIcon = new ImageIcon(imagePath + "ForwardSlash.png");
public static Image ForwardSlash = ForwardSlashIcon.getImage();
public Timer timer = new Timer(1000, this);
public void start()
{
timer.setInitialDelay(0);
timer.start();
}
public void stop()
{
timer.stop();
}
public void actionPerformed(ActionEvent e)
{
secondsCount++;
System.out.println(secondsCount);
}
public void init()
{
this.setSize(WIDTH, HEIGHT);
canvas = new PaintSurface();
this.add(canvas, BorderLayout.CENTER);
ScheduledThreadPoolExecutor executor =
new ScheduledThreadPoolExecutor(3);
executor.scheduleAtFixedRate(
new AnimationThread(this),
0L, 20L, TimeUnit.MILLISECONDS);
}
}
class AnimationThread implements Runnable
{
JApplet c;
public AnimationThread(JApplet c)
{
this.c = c;
}
public void run()
{
c.repaint();
}
}
class PaintSurface extends JComponent
{
private static final long serialVersionUID = 1L;
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Shape screenDisplay = new Rectangle2D.Float(
450, 175, 700, 500);
g2.setColor(Color.DARK_GRAY);
g2.fill(screenDisplay);
/*
* START TITLE SCREEN CREATION
*/
if(XenixMain.secondsCount > 0)
{
g.drawImage(XenixMain.XenixLogo, 500, 500, this);
}
g.drawImage(XenixMain.XenixBackground, 0, 0, this);
/*
* END TITLE SCREEN CREATION
*/
}
}
JFrame Class (Creates JFrame and adds the Applet):
package net.xenix.src ;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class XenixApplicationWindow extends JFrame
{
private static final long serialVersionUID = 1L;
static XenixMain xenix = new XenixMain();
static ImageIcon xenixIcon = new ImageIcon(XenixMain.imagePath + "XenixIcon.png");
public static void main(String[] args)
{
new XenixApplicationWindow();
}
public XenixApplicationWindow()
{
JFrame frame = new JFrame();
JTextField userInput = new JTextField(15);
JPanel panel1 = new JPanel(null);
frame.add(xenix);
frame.setSize(1600, 900);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setResizable(true);
frame.setIconImage(xenixIcon.getImage());
userInput.setBounds(0, 0, 120, 10);
panel1.add(userInput);
frame.add(panel1);
frame.setContentPane(panel1);
frame.setLocationRelativeTo(null);
frame.setTitle("Xenix");
xenix.init();
xenix.start();
frame.setVisible(true);
}
}
Have a look at this example and see if this helps a bit. For some information on the said topic, please see this link. Let me know, if still thingies are unclear.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class BackgroundExample {
private JTextField tField;
private JButton button;
private CustomPanel contentPane;
private void displayGUI() {
JFrame frame = new JFrame("Background Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new CustomPanel();
contentPane.setLayout(new GridBagLayout());
JPanel componentPanel = new JPanel();
componentPanel.setOpaque(false);
tField = new JTextField("Nothing to display yet...", 20);
button = new JButton("Click me not!");
componentPanel.add(tField);
componentPanel.add(button);
contentPane.add(componentPanel);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new BackgroundExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class CustomPanel extends JPanel {
private BufferedImage bImage;
public CustomPanel() {
try {
bImage = ImageIO.read(new URL("http://i.imgur.com/fHiBMwI.jpg"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return (bImage != null ? new Dimension(
bImage.getWidth(), bImage.getHeight()) : new Dimension(400, 400));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bImage, 0, 0, this);
}
}

Categories