i'm making a tiny program where you have 3 timers and when you press start it gives a progress bar until time is over, but JFrame decided to do this after I pressed start:
Here is my code:
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
static int getTime(JFrame frame){
String ts = JOptionPane.showInputDialog(frame, "Set time: ", "time", 1);
return Integer.parseInt(ts);
}
public static class globalVars{
public static int time1 = 5;
public static int time2 = 5;
public static int time3 = 5;
}
static void startTimer(JFrame frame) {
int time = globalVars.time1+globalVars.time2+globalVars.time3;
int timeF = Math.toIntExact(System.currentTimeMillis() / 1000l);
JProgressBar bar = new JProgressBar(0, time);
frame.add(bar);
frame.pack();
int i=0;
while (System.currentTimeMillis()!=timeF+time* 60L){
bar.setValue((timeF+time*60-Math.toIntExact(System.currentTimeMillis() / 1000l))/60);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Timer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
//-----------------------------------------------------------//
Icon icon1 = new ImageIcon("placeholder.png");
String button1Text = "Button1, ";
JButton button1 = new JButton(String.format("%s%dmin", button1Text, globalVars.time1));
button1.setIcon(icon1);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
globalVars.time1=getTime(frame);
button1.setText(String.format("%s%dmin", button1Text, globalVars.time1));
}
});
frame.add(button1);
//-----------------------------------------------------------//
Icon icon2 = new ImageIcon("placeholder.png");
String button2Text = "Button2, ";
JButton button2 = new JButton(String.format("%s%dmin", button2Text, globalVars.time2));
button2.setIcon(icon2);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
globalVars.time2=getTime(frame);
button2.setText(String.format("%s%dmin", button2Text, globalVars.time2));
}
});
frame.add(button2);
//-----------------------------------------------------------//
Icon icon3 = new ImageIcon("placeholder.png");
String button3Text = "Button3, ";
JButton button3 = new JButton(String.format("%s%dmin", button3Text, globalVars.time3));
button3.setIcon(icon3);
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
globalVars.time3=getTime(frame);
button3.setText(String.format("%s%dmin", button3Text, globalVars.time3));
}
});
frame.add(button3);
//-----------------------------------------------------------//
JButton buttonStart = new JButton("Start");
buttonStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonStart.removeActionListener(this);
startTimer(frame);
}
});
frame.add(buttonStart);
//-----------------------------------------------------------//
frame.pack();
frame.setSize(400, 200);
frame.setVisible(true);
}
}
I know it is a very inefficient way of doing things and I will improve it but now I'm more worried about the black screen. Tnx!
Related
i'm relatively new to programming and i'm trying to get the JLabel to update, unfortunately every time I reset the text it doesn't update on the JFrame. Is there something i'm doing wrong? The h.run(); segment in the actionlistener simply decrements an integer in another thread. The h.gethealth then returns that value.
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
public class Main {
JFrame healthcounter = new JFrame();
JLabel number = new JLabel();
public void startHealthFrame(int health){
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
System.out.println("health: "+health);
if(health==500) {
healthcounter.setLocation((int) dim.getWidth() - 300, 0);
healthcounter.setUndecorated(true);
healthcounter.setOpacity(1);
healthcounter.setSize(300,100);
number.setFont(new Font("Arial", Font.BOLD,50));
number.setText("Health: "+Integer.toString(health));
healthcounter.getContentPane().add(number);
healthcounter.setVisible(true);
}else {
number.setText("Health: "+Integer.toString(health));
}
}
public static void main(String args[]){
Main m = new Main();
Health h = new Health();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
JFrame q1 = new JFrame();
JFrame q2 = new JFrame();
JFrame q4 = new JFrame();
JFrame q3 = new JFrame();
m.startHealthFrame(500);
q1.setUndecorated(true);
q2.setUndecorated(true);
q3.setUndecorated(true);
q4.setUndecorated(true);
JButton button1 = new JButton();
JButton button2 = new JButton();
JButton button3 = new JButton();
JButton button4 = new JButton();
button1.setBorder(null);
button2.setBorder(null);
button3.setBorder(null);
button4.setBorder(null);
try {
Image topleft = ImageIO.read(Main.class.getResource("/resources/upperleft.png"));
Image topright = ImageIO.read(Main.class.getResource("/resources/upperright.png"));
Image bottomleft = ImageIO.read(Main.class.getResource("/resources/bottomleft.png"));
Image bottomright = ImageIO.read(Main.class.getResource("/resources/bottomright.png"));
button1.setIcon(new ImageIcon(topleft));
button2.setIcon(new ImageIcon(topright));
button3.setIcon(new ImageIcon(bottomleft));
button4.setIcon(new ImageIcon(bottomright));
} catch (IOException e) {
e.printStackTrace();
}
q1.add(button1);
q2.add(button2);
q4.add(button4);
q3.add(button3);
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
h.run();
Main m = new Main();
m.startHealthFrame(h.gethealth());
}
});
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
h.run();
Main m = new Main();
m.startHealthFrame(h.gethealth());
}
});
button3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
h.run();
Main m = new Main();
m.startHealthFrame(h.gethealth());
}
});
button4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
h.run();
Main m = new Main();
m.startHealthFrame(h.gethealth());
}
});
q1.setSize(250,250);
q2.setSize(250,250);
q3.setSize(250,250);
q4.setSize(250,250);
q1.setDefaultCloseOperation(q1.EXIT_ON_CLOSE);
q2.setDefaultCloseOperation(q2.EXIT_ON_CLOSE);
q3.setDefaultCloseOperation(q3.EXIT_ON_CLOSE);
q4.setDefaultCloseOperation(q4.EXIT_ON_CLOSE);
q1.setLocation((dim.width/2-q1.getSize().width/2)-125, (dim.height/2-q1.getSize().height/2)-125);
q2.setLocation(q1.getX()+q1.getWidth()-8,q1.getY());
q3.setLocation(q1.getX(),q1.getY()+q1.getHeight()-8);
q4.setLocation(q1.getX()+q1.getWidth()-8,q1.getY()+q1.getHeight()-8);
q1.setVisible(true);
q2.setVisible(true);
q4.setVisible(true);
q3.setVisible(true);
try
{
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(Main.class.getResource("/resources/megalovania.wav")));
clip.start();
clip.loop(clip.LOOP_CONTINUOUSLY);
}
catch (Exception exc)
{
exc.printStackTrace(System.out);
}
Time time = new Time(q1,q2,q3,q4);
time.start();
}
}
I have a problem with using JSpinner. When I change spinerkp all variables (kp,sp,lk,ct) are changing value, and when I change any other JSpinner nothing happen. I don't know what is wrong with this. Anybody know what is wrong with this?
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class PorownanieLokat
{
private JFrame frame;
private JLabel naglowek;
private JLabel status;
private JPanel panel;
public int kp;
public int lk;
public int ct;
public int sp;
public PorownanieLokat()
{
przygotujGUI();
}
public static void main(String args[])
{
PorownanieLokat porownanieLokat = new PorownanieLokat();
porownanieLokat.Lokata();
}
private void przygotujGUI() {
frame = new JFrame("SWING");
frame.setSize(new Dimension(400, 400));
frame.setLayout(new GridLayout(4, 1));
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
naglowek = new JLabel("", JLabel.CENTER);
status = new JLabel("", JLabel.CENTER);
status.setSize(350, 100);
panel = new JPanel();
panel.setLayout(new FlowLayout());
frame.add(naglowek);
frame.add(status);
frame.add(panel);
frame.setVisible(true);
}
public void Lokata()
{
Obliczenia obliczenia = new Obliczenia();
naglowek.setText("Wypełnij wszystkie pola aby obliczyć kapitał końcowy!");
JButton x = new JButton( "Oblicz!");
x.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
status.setText("Kapitał końcowy to: "+obliczenia.Licz(kp,sp,lk,ct));
}
});
SpinnerModel spinnerModel1 = new SpinnerNumberModel(1,0,10000,1);
JSpinner spinerkp = new JSpinner(spinnerModel1);
spinerkp.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e1) {
kp =(int) ((JSpinner)e1.getSource()).getValue();
System.out.println(kp);
}
});
SpinnerModel spinnerModel2 = new SpinnerNumberModel(1,0,100,1);
JSpinner spinersp = new JSpinner(spinnerModel2);
spinerkp.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e2) {
sp= (int) ((JSpinner)e2.getSource()).getValue();
System.out.println(sp);
}
});
SpinnerModel spinnerModel3 = new SpinnerNumberModel(1,1,12,1);
JSpinner spinerlk = new JSpinner(spinnerModel3);
spinerkp.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e3) {
lk=(int) ((JSpinner)e3.getSource()).getValue();
System.out.println(lk);
}
});
SpinnerModel spinnerModel4 = new SpinnerNumberModel(1,0,50,1);
JSpinner spinerct = new JSpinner(spinnerModel4);
spinerkp.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e4) {
ct= (int) ((JSpinner)e4.getSource()).getValue();
System.out.println(ct);
}
});
panel.add(spinerkp);
panel.add(spinersp);
panel.add(spinerlk);
panel.add(spinerct);
panel.add(x);
frame.setVisible(true);
}
}
Your code creates four JSpinner instances, and four ChangeListener's, but adds each ChangeListener to spinerkp (rather than adding them to their corresponding JSpinner).
JSpinner spinerkp...
spinnerkp.addChangeListener(./..)
JSpinner spinersp...
spinnersp.addChangeListener(./..)//add the change listener to the appropriate JSpinner
...
I'm still having issues with updating the JLabel using a timer. I can't seem to figure out what I am missing. the global second variable stays at zero so I am guessing the timers working but not updating the GUI window?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Globals
{
public static int seconds = 0;
}
class main
{
public static void main(String Args[])
{
//text timeline = new text();
JFrame testing = new JFrame();
frame textdes = new frame();
testing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testing.setSize(1000,1000);
testing.setVisible(true);
Countdown timer = new Countdown();
Timer countdown = new Timer(5000, timer);
countdown.start();
JLabel countdowntext = new JLabel();
countdowntext.setText("Now its :" + Globals.seconds);
testing.add(countdowntext);
testing.add(textdes);
}
}
class frame extends JFrame
{
class Countdown implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Globals.seconds++;
}
}
}
You're setting the text of the label only once in the program. Then the timer changes the value of a variable, but doesn't do anything with the label. It should do:
Globals.seconds++;
countdowntext.setText("Now its :" + Globals.seconds);
Here's a complete example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Globals {
public static int seconds = 0;
}
class Main {
public static void main(String Args[]) {
//text timeline = new text();
JFrame testing = new JFrame();
testing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testing.setSize(1000,1000);
testing.setVisible(true);
JLabel countDownLabel = new JLabel();
countDownLabel.setText("Now it's : " + Globals.seconds);
testing.add(countDownLabel);
CountDown countdown = new CountDown(countDownLabel);
Timer timer = new Timer(5000, countDown);
timer.start();
}
}
class CountDown implements ActionListener {
private JLabel countDownLabel;
public CountDown(JLabel countDownLabel) {
this.countDownLabel = countDownLabel;
}
#Override
public void actionPerformed(ActionEvent e) {
Globals.seconds++;
this.countDownLabel.setText("Now it's : " + Globals.seconds);
}
}
Try this -
public class MainFrame{
JFrame frame = new JFrame("Main frame");
JPanel panel = new JPanel();
JLabel countdownText = new JLabel();
int seconds = 0;
public MainFrame() {
Timer timer = new Timer(5000, new Countdown());
timer.start();
panel.add(countdownText);
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setPreferredSize(new Dimension(320,240));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
countdownText.setText("Now its :" + seconds);
}
class Countdown implements ActionListener {
public void actionPerformed(ActionEvent e) {
seconds++;
countdownText.setText("Now its :" + seconds);
}
}
public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
I have created an ActionListener and the button but the button doesn't work.
The action listener is supposed to be integrated with the submit button, please help?
Code:
import javax.swing.*;
import javax.swing.event.DocumentListener;import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Executer {
private JLabel lblCommand;
private JTextField txtEnter;
private JButton btNext, btPrevious, btSubmit;
private JPanel panel;
public static void main(String[] args) {
new Executer();
}
public Executer() {
JFrame frame = new JFrame("Script Executer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,300);
frame.setVisible(true);
myPanel();
Text();
Fields();
Buttons();
frame.add(panel);
frame.setVisible(true);
}
public void myPanel() {
panel = new JPanel();
panel.setLayout(null);
}
public void Text() {
lblCommand = new JLabel("Enter Here");
lblCommand.setBounds(145, 100, 150, 20);
Font styleOne = new Font("Arial", Font.BOLD, 13);
lblCommand.setFont(styleOne);
panel.add(lblCommand);
}
public void Fields() {
txtEnter = new JTextField();
txtEnter.setBounds(230, 100, 120, 20);
panel.add(txtEnter);
}
public void Buttons() {
btNext = new JButton ("Next");
btNext.setBounds(300,215,100,20);
panel.add(btNext);
btPrevious = new JButton ("Previous");
btPrevious.setBounds(190,215,100,20);
panel.add(btPrevious);
btSubmit = new JButton("Submit");
btSubmit.setBounds(80,215,100,20);
panel.add(btSubmit);
btSubmit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String userEntered = txtEnter.getText();
if(userEntered.equalsIgnoreCase("yes"))
{
//run your script
}
}
});
}
}
Your code appears fine.
Enter a print statement and you can see it is working.
btSubmit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// here the click happend so you can check your Textfield
String userEntered = txtEnter.getText();
System.out.println("User enterd: " + userEntered);
if(userEntered.equalsIgnoreCase("yes"))
{
System.out.println("Entered Yes");
}
}
});
I am trying to remove a JPanel not hide it but i can't find anything that works.
This is the code in the panel that needs to remove itself when a button is pressed:
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Frame frame = new Frame(); //referencing to my JFrame class (this class is a JPanel)
//need to remove this panel on this line
frame.ThreeD(); // adds a new panel
}
});
UPDATED
This is the full code:
package ThreeD;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.UIManager;
import Run.Frame;
public class Launcher extends JPanel{
private JButton play, options, help, mainMenu;
private Rectangle rplay, roptions, rhelp, rmainMenu;
private int buttonWidthLocation, buttonWidth, buttonHeight;
private int width = 1280;
public Launcher() {
this.setLayout(null);
drawButtons();
}
private void drawButtons() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
e.printStackTrace();
}
play = new JButton("Play");
options = new JButton("Options");
help = new JButton("Help");
mainMenu = new JButton("Main Menu");
buttonWidthLocation = (width / 2) - (buttonWidth / 2);
buttonWidth = 80;
buttonHeight = 40;
rplay = new Rectangle(buttonWidthLocation, 150, buttonWidth, buttonHeight);
roptions = new Rectangle(buttonWidthLocation, 300, buttonWidth, buttonHeight);
rhelp = new Rectangle(buttonWidthLocation, 450, buttonWidth, buttonHeight);
rmainMenu = new Rectangle(buttonWidthLocation, 600, buttonWidth, buttonHeight);
play.setBounds(rplay);
options.setBounds(roptions);
help.setBounds(rhelp);
mainMenu.setBounds(rmainMenu);
add(play);
add(options);
add(help);
add(mainMenu);
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Frame frame = new Frame();
//need to remove this panel here
frame.ThreeD();
}
});
options.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("options");
}
});
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("help");
}
});
mainMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("mainMenu");
}
});
}
}
And this is my Frame class:
package Run;
import javax.swing.*;
import ThreeD.Display;
import ThreeD.Launcher;
import TowerDefence.Window;
import java.awt.*;
import java.awt.image.BufferedImage;
public class Frame extends JFrame{
public static String title = "Game";
/*public static int GetScreenWorkingWidth() {
return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().width;
}*/
/*public static int GetScreenWorkingHeight() {
return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height;
}*/
//public static Dimension size = new Dimension(GetScreenWorkingWidth(), GetScreenWorkingHeight());
public static Dimension size = new Dimension(1280, 774);
public static void main(String args[]) {
Frame frame = new Frame();
System.out.println("Width of the Frame Size is "+size.width+" pixels");
System.out.println("Height of the Frame Size is "+size.height+" pixels");
}
public Frame() {
setTitle(title);
setSize(size);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ThreeDLauncher();
}
public void ThreeDLauncher() {
Launcher launcher = new Launcher();
add(launcher);
setVisible(true);
}
public void TowerDefence() {
setLayout(new GridLayout(1, 1, 0, 0));
Window window = new Window(this);
add(window);
setVisible(true);
}
public void ThreeD() {
BufferedImage cursor = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
Cursor blank = Toolkit.getDefaultToolkit().createCustomCursor(cursor, new Point(0, 0), "blank");
getContentPane().setCursor(blank);
Display display = new Display();
add(display);
setVisible(true);
display.start();
}
}
Basically - you are creating new instance of Frame in line:
Frame frame = new Frame(); //referencing to my JFrame class (this class is a JPanel)
New instance of Frame is not visible, and you're try to remove your Launcher from not visible new Frame. But this is wrong - you should remove Launcher from Frame that you created previously in main function (that is: parent of Launcher component).
Here goes an example:
public class TestFrame extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestFrame frame = new TestFrame();
frame.getContentPane().add(new MyPanel(frame));
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
And MyPanel class:
public class MyPanel extends JPanel {
public MyPanel(final TestFrame frame) {
JButton b = new JButton("Play");
add(b);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Container pane = frame.getContentPane();
pane.remove(MyPanel.this);
JPanel otherPanel = new JPanel();
otherPanel.add(new JLabel("OtherPanel"));
pane.add(otherPanel);
pane.revalidate();
}
});
}
}
In your example you should add a reference to Frame in your Launcher constructor:
public Launcher(Frame frame) {
this.frame = frame;
...
Init Launcher:
public void ThreeDLauncher() {
Launcher launcher = new Launcher(this);
and use:
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//need to remove this panel here
frame.getContentPane().remove(Launcher.this);
frame.ThreeD();
}
});
Say your panel is myPanel you can remove it from the main frame by:
frame.getContentPane().remove(myPanel);