i have an program which is an JFrame, but when i use my "starting" action it isn't able to be switched of, instead it just sticks running and I need to force-close it :( could you say me why, because I'm new to coding an i dont find my mistake here is my code:
public class ClickBotSetUp extends JFrame {
static ClickBotSetUp frame;
static Robot robot;
public static void ClickBot() throws AWTException{
final Robot robot = new Robot();
robot.delay(2000);
while(true)
{
{
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.delay(least);
}
}
}
public static void main(String[] args) throws IOException, AWTException {
frame = new ClickBotSetUp("setup speed");
frame.setVisible(true);
frame.setBackground(Color.WHITE);
robot = new Robot();
}
//settings
static int least = 100;
JTextField count;
JButton start;
static int bot = 0;
public ClickBotSetUp(String title) throws HeadlessException
{
super(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setSize(180, 145);
Container cont = getContentPane();
cont.setLayout(new BorderLayout());
((JComponent) cont).setBorder(BorderFactory.createEmptyBorder(15, 15,
15, 15));
//desing
JLabel instructions = new JLabel("low nubers can crash");
cont.add(instructions, BorderLayout.SOUTH);
//buttons
start = new JButton("start");
start.setAction(starting);
cont.add(start, BorderLayout.WEST);
//score
JPanel scores = new JPanel();
scores.setLayout(new BorderLayout());
cont.add(scores, BorderLayout.CENTER);
JPanel times = new JPanel();
times.setLayout(new BorderLayout());
scores.add(times, BorderLayout.WEST);
//times
count = new JTextField("100");
count.setEditable(false);
times.add(count, BorderLayout.CENTER);
JButton add10 = new JButton("+10");
add10.setAction(add_10);
times.add(add10, BorderLayout.NORTH);
JButton remove10 = new JButton("-10");
remove10.setAction(remove_10);
times.add(remove10, BorderLayout.SOUTH);
}
private AbstractAction starting = new AbstractAction("start") {
#Override
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
try {
ClickBot();
} catch (AWTException e) {
e.printStackTrace();
}
}
};
private AbstractAction add_10 = new AbstractAction("+10") {
#Override
public void actionPerformed(ActionEvent arg0) {
least = least + 10;
count.setText("" +least+ "");
}
};
private AbstractAction remove_10 = new AbstractAction("-10") {
#Override
public void actionPerformed(ActionEvent arg0) {
if(least < 20){
}else{
least = least - 10;
count.setText("" +least+ "");
}
}
};
}
while(true) is an infinite loop. It will never exit this.
Have some condition in the while(someCondition Here) which will break the while loop.
Also as #ArnaudDenoyelle pointed out
You need the line
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
That is because the default behavior for the JFrame for the X button is the equivalent to
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
So most of the times you will need to add the line manually when creating your JFrame
while(true) will create a never ending loop. you should be using a flag and when a condition is met that flag should be changed so that the loop may be exited.
Related
I was just messing around with GUI in Java and created a little game. In it, 105 randomly placed buttons are created and then an instruction screen pops up, telling the user which button to find. I've tried to figure out how to program a "Loading..." JDialog, which will pop up while the buttons are being created in the background. The trouble is, when I run the program the JDialog doesn't load until AFTER all the buttons have been created, which kind of defeats the purpose of the box in the first place. How can I force the "Loading..." box to load BEFORE the buttons begin to be created??? Thanks in advance.
Because I've just been tinkering, my code is not perfect but here it is:
import java.util.Scanner;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.ProgressMonitor;
public class ButtonGame {
private static int butNum = 1;
private static JFrame frame;
private static ActionListener notIt;
private static ActionListener it;
private static Random rand = new Random();
private static int butToFind = rand.nextInt(105);
private static JFrame frameToClose;
//private static int mouseClicks;
//private static double time;
public static void main(String[] args) {
//actionlistener for all incorrect buttons (buttons that are "not it")
notIt = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
JFrame frame5 = (JFrame) SwingUtilities.getRoot(component);
frame5.dispose();
}
};
//actionlistener for the correct button (the button that's "it")
it = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame youWin = new JFrame("YOU WON!");
//removes all panels to begin game again
JButton again = new JButton("Play again");
again.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
java.awt.Window windows[] = java.awt.Window.getWindows();
for(int i=0;i<windows.length;i++){
if (windows[i] != frame) { windows[i].dispose(); }
butToFind = rand.nextInt(105);
butNum = 1;
youWin.dispose();
}
frame.setVisible(true);
}
});
//quits game
JButton win = new JButton("Quit");
win.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
//layout
youWin.setSize(775, 300);
youWin.setLayout(new FlowLayout());
JLabel label1 = new JLabel("Fantastic!");
Font font1 = new Font("Courier", Font.BOLD,120);
label1.setFont(font1);
label1.setHorizontalAlignment(JLabel.CENTER);
JLabel label2 = new JLabel("You beat the game!");
Font font2 = new Font("Courier", Font.BOLD,60);
label2.setFont(font2);
label2.setHorizontalAlignment(JLabel.CENTER);
youWin.add(label1);
youWin.add(label2);
JPanel panel = new JPanel();
youWin.add(panel);
panel.add(again);
panel.add(win);
youWin.setLocation(260, 100);
youWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
youWin.setVisible(true);
java.awt.Window windows[] = java.awt.Window.getWindows();
}
};
//start window
frame = new JFrame("Window");
frame.setLocation(400, 200);
JButton button1 = new JButton("Click to begin");
//button to begin game
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// JDialog load = new JDialog();
// load.setAlwaysOnTop(true);
// load.setSize(500,500);
// load.setVisible(true);
// load.add(new Label("Loading..."));
// load.pack();
frame.setVisible(false); // "start" window's visibility
// try {
// Thread.sleep(100000);
// } catch (Exception t) {
// }
// creates buttons
for (int i = 0; i < 105; i++) {
JFrame nextFrame = newFrame(butNum);
nextFrame.setVisible(true);
butNum++;
}
//creates instructions and tells user what button to find
JFrame instructions = new JFrame("How to play");
instructions.setSize(300,175);
instructions.setLayout(new GridLayout(4,1));
JPanel instPanel = new JPanel();
//button to remove instruction panel
JButton ok = new JButton("Ok");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
instructions.dispose();
}
});
instPanel.add(ok);
instructions.setLocation(400,200);
//layout of instruction panel
JLabel find = new JLabel("Your goal is to find Button " + butToFind + ".");
find.setHorizontalAlignment(JLabel.CENTER);
JLabel find2 = new JLabel("Click a button to make it disappear.");
find2.setHorizontalAlignment(JLabel.CENTER);
JLabel find3 = new JLabel("Good luck!");
find3.setHorizontalAlignment(JLabel.CENTER);
instructions.add(find);
instructions.add(find2);
instructions.add(find3);
instructions.add(instPanel);
instructions.setVisible(true);
}
});
frame.add(button1);
frame.setSize(150,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
//creates frame with button in it
public static JFrame newFrame(int num) {
JFrame frame2 = new JFrame();
JButton button = new JButton("Button " + num);
if (num == butToFind) {
button.addActionListener(it);
frameToClose = frame2;
} else {
button.addActionListener(notIt);
}
frame2.add(button);
frame2.setSize(randNum(90,200), randNum(50,100));
frame2.setLocation(rand.nextInt(1200), rand.nextInt(800));
frame2.getContentPane().setBackground(new Color(rand.nextInt(255),
rand.nextInt(255),
rand.nextInt(255)));
frame2.setVisible(true);
return frame2;
}
//provides random number between high and low
public static int randNum(int low, int high) {
int result = -1;
while (result < low || result > high) {
result = rand.nextInt(high);
}
return result;
}
}
Also, as a side-question, which of the variables defined before main should be static? And how can I get the program to compile without being static? Thanks!
First take a look at The Use of Multiple JFrames, Good/Bad Practice? and understand why I freaked out when I ran your code...
Instead of creating a bunch of frames, why not use something like JButton on another JPanel and add it to the current frame (this would also be a good use for a CardLayout)
JPanel panel = new JPanel(new GridLayout(10, 0));
Random rnd = new Random();
// creates buttons
for (int i = 0; i < 105; i++) {
JButton btn = new JButton(String.valueOf(i));
panel.add(btn);
//JFrame nextFrame = newFrame(butNum);
//nextFrame.setVisible(true);
//butNum++;
}
frame.getContentPane().removeAll();
frame.add(panel);
frame.revalidate();
frame.pack();
Alternatively, if you're really hell bent on using "frames", consider using a JDesktopPane and JInternalFrame instead.
See How to Use Internal Frames for more details
Also, as a side-question, which of the variables defined before main should be static? And how can I get the program to compile without being static?
As much as possible, none. Instead of trying to create the whole thing in the main method, use the classes constructor to initialise the UI and use another method to actually get the game rolling...
public class ButtonGame {
private int butNum = 1;
private JFrame frame;
private ActionListener notIt;
private ActionListener it;
private Random rand = new Random();
private int butToFind = rand.nextInt(105);
private JFrame frameToClose;
//private static int mouseClicks;
//private static double time;
public static void main(String[] args) {
ButtonGame game = new ButtonGame();
game.start();
}
public ButtonGame() {
//... All the code that was once in main...
frame.add(button1);
frame.setSize(150, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void start() {
frame.setVisible(true);
}
Answering to your side questions:
a static method can only accept static global variables
You can put all your code in the constructor and use main to only run the program.
Constructor:
public ButtonGame() {
// All of your code goes here - except the static methods
}
You should also make all other methods non-static.
To run the program:
public static void main(String[] args) {
new ButtonGame();
}
I have an assignment question that requires me to create a JPasswordField. Two buttons are needed, one to show the actual password in another textfield, and the other just shows the character count in the textfield. Here's what I have to far, but I can't get it to compile because Method setText in class javax.swing.text.JTextComponent cannot be applied to given types.
The compiler stops under bt1 when I want it to read the password itself.
Can anyone help?
Thanks.
Code:
public class JavaPasswordCount {
public JavaPasswordCount() {
JFrame window = new JFrame("Password Character Count");
window.setSize(50, 50);
JButton bt1 = new JButton("Show Count");
JButton bt2 = new JButton("Show Password");
final JPasswordField pwd = new JPasswordField();
final JTextField tf = new JTextField();
final int counter;
JPanel panel = new JPanel();
bt1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tf.setText(pwd.getPassword());
}
});
bt2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
counter = pwd.length();
tf.setText(counter);
}
});
panel.setLayout(new FlowLayout()); // Add buttons and TextField to the panel
panel.add(tf);
panel.add(pwd);
panel.add(bt1);
panel.add(bt2);
window.getContentPane().add(panel, BorderLayout.CENTER);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.pack();
window.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
}
JavaPasswordCount application = new JavaPasswordCount();
}
}
Change this lines:
counter = pwd.length();
tf.setText(counter);
to
int counter = pwd.getPassword().length;
tf.setText(String.valueOf((counter)));
and this
tf.setText(pwd.getPassword());
To
tf.setText(pwd.getPassword().toString());
I am having problems understanding how to use an actionlistener to change the value of variables.
In my program I need to store the choices the user makes by selecting some radio buttons.
I have got a main class with a card layout, then several classes which each are different panels. In one of the panels I have some radio buttons, with an actionlistener as an inner class.
When I try to print the variable value in the main class, it is printed immediately, before the user has made a choice, as I instantiate the panel class and get the variable from it I get the variable before it has been changed by the user.
I know I should not think in a linear manner with Java, but how can I make sure that I fetch the variable after it has been changed by the user and not before? I will not be able to do that will I? I understand there is some flaw in my thinking but I haven't slept properly for ages and I just cannot get my head around this.
public class Screen3 extends JPanel{
JRadioButton addition = new JRadioButton("Addition");
JRadioButton subtraction = new JRadioButton("Subtraction");
JRadioButton multiplication = new JRadioButton("Multiplication");
JRadioButton division = new JRadioButton("Division");
JRadioButton all = new JRadioButton("All");
JRadioButton single = new JRadioButton("Single");
JRadioButton two = new JRadioButton("Double");
JRadioButton triple = new JRadioButton("Triple");
JRadioButton mix = new JRadioButton("Mix");
JRadioButton five = new JRadioButton("5");
JRadioButton ten = new JRadioButton("10");
private int type, digit, rounds;
public Screen3() {
JPanel firstButtonPanel = new JPanel();
JPanel secondButtonPanel = new JPanel();
ButtonGroup myFirstGroup = new ButtonGroup();
ButtonGroup mySecondGroup = new ButtonGroup();
myFirstGroup.add(addition);
myFirstGroup.add(subtraction);
myFirstGroup.add(multiplication);
myFirstGroup.add(division);
//myFirstGroup.add(all);
mySecondGroup.add(single);
mySecondGroup.add(two);
mySecondGroup.add(triple);
//mySecondGroup.add(mix);
firstButtonPanel.setLayout(new FlowLayout());
firstButtonPanel.add(addition);
firstButtonPanel.add(subtraction);
firstButtonPanel.add(multiplication);
firstButtonPanel.add(division);
//firstButtonPanel.add(all);
secondButtonPanel.setLayout(new FlowLayout());
secondButtonPanel.add(single);
secondButtonPanel.add(two);
secondButtonPanel.add(triple);
//secondButtonPanel.add(mix);
JPanel buttons = new JPanel();
buttons.setLayout(new BorderLayout());
buttons.add(selectionLabel, BorderLayout.NORTH);
buttons.add(firstButtonPanel, BorderLayout.CENTER);
buttons.add(secondButtonPanel, BorderLayout.SOUTH);
ButtonGroup myThirdGroup = new ButtonGroup();
JPanel endButtons = new JPanel();
myThirdGroup.add(five);
myThirdGroup.add(ten);
endButtons.add(five);
endButtons.add(ten);
endPanel.setLayout(new BorderLayout());
endPanel.add(rounds, BorderLayout.NORTH);
endPanel.add(endButtons, BorderLayout.CENTER);
setLayout(new BorderLayout());
add(buttons, BorderLayout.NORTH);
Selection sn = new Selection();
addition.addActionListener(sn);
subtraction.addActionListener(sn);
multiplication.addActionListener(sn);
division.addActionListener(sn);
single.addActionListener(sn);
two.addActionListener(sn);
triple.addActionListener(sn);
five.addActionListener(sn);
ten.addActionListener(sn);
}
public int getType() {
return type;
}
public int getDigit() {
return digit;
}
public int getRounds() {
return rounds;
}
public class Selection implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(addition.isSelected()) {
type = 1;
}
else if(subtraction.isSelected()) {
type = 2;
}
else if(multiplication.isSelected())
type = 3;
else if(division.isSelected())
type = 4;
//else if(all.isSelected())
//type = 5;
if(single.isSelected()) {
digit = 1;
System.out.println("single");
}
else if(two.isSelected())
digit = 2;
else if(triple.isSelected())
digit = 3;
if(five.isSelected())
rounds = 5;
else if(ten.isSelected())
rounds = 10;
}
}
}
Here is the main class:
public class Driver {
public JFrame frame = new JFrame("Math Game");
public JPanel screens = new JPanel(new CardLayout());
int digit = 1;
int rounds = 1;
int type = 1;
Driver() {
}
public void show() {
JPanel buttonPanel = new JPanel();
JButton next = new JButton("Next");
JButton previous = new JButton("Previous");
buttonPanel.add(previous);
buttonPanel.add(next);
Screen1 screen1 = new Screen1();
Screen2 screen2 = new Screen2();
Screen3 screen3 = new Screen3();
screens.add(screen1, "welcome");
screens.add(screen2, "next");
screens.add(screen3, "selection");
frame.add(screens);
frame.add(buttonPanel, BorderLayout.PAGE_END);
frame.setSize(400, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
next.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cl = (CardLayout)(screens.getLayout());
cl.next(screens);
}
});
previous.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cl = (CardLayout)(screens.getLayout());
cl.previous(screens);
}
});
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Driver dr = new Driver();
dr.show();
}
});
}
}
I just try a test print of System.out.println(screen3.getType()); either in show() or main
Use JOptionPane/JDialog which has modality.
Have a read on How to Make Dialogs
In example here is only printed after JDialog is closed:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JDialog jd = new JDialog();
jd.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
jd.setModal(true);
jd.pack();
jd.setVisible(true);
System.out.println("Here");
}
});
}
In this example here is only printed after JOptionPane is closed:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JPanel panel=new JPanel();
panel.add(new JLabel("Hello, world!"));
JOptionPane.showMessageDialog(null, panel, "Panel Message",JOptionPane.PLAIN_MESSAGE);
System.out.println("Here");
}
});
}
I know I should not think in a linear manner with Java, but how can I
make sure that I fetch the variable after it has been changed by the
user and not before?
After using a modal JDialog/JOptionPane you would simply use public getters to access the variable contained within the class instance:
public class Test {
public static void main(String[] args) {
X x= new X();//will only return after dialog closed
System.out.println(x.getY());
}
}
class X {
private int y=0;//will be assigned during dialog/joptionpanes life span
public X() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//creates and shows the modal dialog/optionpane which will allow modification of variable y through some input/controls
}
});
}
public int getY() {
return y;
}
}
I have some code here, and when the button is pressed, I'm trying to extend the JPanel. However, it remains at the height it was previously. Is there a way to do this or is it fixed on the dimensions it was set when it was created?
public class GUITest extends JFrame {
JPanel jp;
JButton one;
public static void main(String[] args) {
new GUITest();
}
public GUITest() {
initWidgets();
}
public void initWidgets() {
setSize(250, 250);
setTitle("Stretch Panel Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
one = new JButton("Click me!");
ActionListener extend = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 80; i++) {
jp.setPreferredSize(new Dimension(200,(i+70)));
}
//System.out.println(jp.getHeight());
}
};
one.addActionListener(extend);
add(one, BorderLayout.NORTH);
jp = new JPanel();
jp.setBackground(Color.BLACK);
jp.setPreferredSize(new Dimension(200,70));
add(jp, BorderLayout.CENTER);
setVisible(true);
}
}
alternatively, you can call revalidate() on the jpanel after the button click
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 80; i++) {
jp.setPreferredSize(new Dimension(200,(i+70)));
**jp.revalidate();**
}
//System.out.println(jp.getHeight());
}
to clarify, once you change the dimensions, it has to be redrawn. the thing has been changed, but it hasn't been told to update that change visually
You should use the validate() method in order to do that.
I hope i was able to help!
Have a great day!
try this:
jp.setSize(new Dimension(200,(i+70)));
instead of jp.setPreferredSize(new Dimension(200,(i+70)));
in this code on eachclick the size will be increase by 10 :
ActionListener extend = new ActionListener() {
int count=0;
public void actionPerformed(ActionEvent e) {
count=count+10;
jp.setSize(new Dimension(100+count,70+count));
System.out.println("in listener");
}
};
one more thing setPrefferedsize is the default size which is called whenever component re-validates. to change the setPrefferedSize on each click :
count=count+10;
jp.setSize(new Dimension(100+count,70+count));
jp.setPreferredSize(new Dimension(100+count,70+count));
I unfortunately have to use multiple windows in this program and I don't think CardLayout is going to work because I can't have any buttons constant between the different layouts. So I'm trying to code a button to hide the present JPanel (thePanel) and show a new one (thePlacebo).
I'm trying to hide thePanel in an ActionListener like this:
frame.getContentPane().remove(thePanel);
I thought this would work, but it just freezes my program as soon as I hit the button.
Here's a chunk of the code for context:
public class Reflexology1 extends JFrame{
JButton button1, button2;
JButton movingButton;
JTextArea textArea1;
int buttonAClicked, buttonDClicked;
private long _openTime = 0;
private long _closeTime = 0;
JPanel thePanel = new JPanel();
JPanel thePlacebo = new JPanel();
final JFrame frame = new JFrame("Reflexology");
public static void main(String[] args){
new Reflexology1();
}
public Reflexology1(){
frame.setSize(600, 475);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Reflexology 1.0");
frame.setResizable(false);
button1 = new JButton("Accept");
button2 = new JButton("Decline");
movingButton = new JButton("Click Me");
ListenForAcceptButton lForAButton = new ListenForAcceptButton();
ListenForDeclineButton lForDButton = new ListenForDeclineButton();
button1.addActionListener(lForAButton);
button2.addActionListener(lForDButton);
//movingButton.addActionListener(lForMButton);
JTextArea textArea1 = new JTextArea(24, 50);
textArea1.setText("Tracking Events\n");
textArea1.setLineWrap(true);
textArea1.setWrapStyleWord(true);
textArea1.setSize(15, 50);
FileReader reader = null;
try {
reader = new FileReader("EULA.txt");
textArea1.read(reader, "EULA.txt");
} catch (IOException exception) {
System.err.println("Problem loading file");
exception.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException exception) {
System.err.println("Error closing reader");
exception.printStackTrace();
}
}
}
JScrollPane scrollBar1 = new JScrollPane(textArea1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
AdjustmentListener listener = new MyAdjustmentListener();
thePanel.add(scrollBar1);
thePanel.add(button1);
thePanel.add(button2);
thePlacebo.add(movingButton);
frame.add(thePanel);
ListenForWindow lForWindow = new ListenForWindow();
frame.addWindowListener(lForWindow);
frame.setVisible(true);
}
// Implement listeners
private class ListenForAcceptButton implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == button1){
Calendar ClCDateTime = Calendar.getInstance();
System.out.println(ClCDateTime.getTimeInMillis() - _openTime);
_closeTime = ClCDateTime.getTimeInMillis() - _openTime;
frame.getContentPane().remove(thePanel);
}
}
}
Does anybody know what I might be doing wrong?
After removing components from a container, it goes into the invalidate state. To bring it back to the valid state you have to revalidate and repaint that. In your case you are directly adding/removing components from JFrame so depending on the Java version you can do this :
frame.revalidate(); // For Java 1.7 or above
frame.getContentPane().validate(); // For Java 1.6 or below
frame.repaint();
Here is one working example for your help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Assignment
{
private JFrame frame;
private JPanel firstPanel;
private JPanel secondPanel;
private JButton forwardButton;
private JButton backButton;
private void displayGUI()
{
frame = new JFrame("Assignment");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstPanel = new JPanel();
firstPanel.setOpaque(true);
firstPanel.setBackground(Color.BLUE);
secondPanel = new JPanel();
secondPanel.setOpaque(true);
secondPanel.setBackground(Color.RED);
forwardButton = new JButton("Forward");
forwardButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
frame.remove(firstPanel);
frame.add(secondPanel);
frame.revalidate(); // For Java 1.7 or above.
// frame.getContentPane().validate(); // For Java 1.6 or below.
frame.repaint();
}
});
backButton = new JButton("Back");
backButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
frame.remove(secondPanel);
frame.add(firstPanel);
frame.revalidate(); // For Java 1.7 or above.
// frame.getContentPane().validate(); // For Java 1.6 or below.
frame.repaint();
}
});
firstPanel.add(forwardButton);
secondPanel.add(backButton);
frame.add(firstPanel);
frame.setSize(300, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new Assignment().displayGUI();
}
});
}
}
correct way could be (only) by using CardLayout
otherwise have to remove JPanel from container and to call (as last code line and call only one times after all changes for container are done)
.
myJPanelsContainer#revalidate(); // in Java6 for JFrame validate()
myJPanelsContainer#repaint();