Java swing Button is invisible after revalidate() until clicked - java

I have a panel with box layout full of buttons {A, B, empty...}. When i try to remove A, I am left with {empty, B, empty}. So i try to add panel.revalidate() but now i have {invisible, empty, empty} and if I mouse over the spot were the button should be and click it appears {B, empty, empty}.
adding panel.repaint() did not help.
Component[] components = Gui.panel.getComponents();
for(int b = 0; b < components.length; b++) {
if(((Button) components[b]).getLabel().contentEquals(parts[2])) {
Gui.panel.remove((Button) components[b]);
Gui.panel.revalidate();
Gui.panel.repaint();
break;
}
}
I also tried to recreate the list skipping the component i wanted omitted but it returns the exact same results.
Component[] components = Gui.panel.getComponents();
Gui.panel.removeAll();
for(int b = 0; b < components.length; b++) {
if(!((Button) components[b]).getLabel().contentEquals(parts[2])) {
Gui.panel.add(components[b]);
}
}
Gui.panel.revalidate();
Gui.panel.repaint();
I know that swing is not thread safe, but i am not sure if that applies here.
The problem is occurring in a runnable class that listens for a message from the server. Although i do a lot of GUI manipulation from the same thread and this is my first problem.
EDIT:
here is a program that highlights my problem:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CreativeName {
public static Thread listen;
static Object VirtualServer = new Object();
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Gui.createAndShowGUI();
}
});
listen = new Thread(new FromServer());
listen.start();
}
}
class FromServer implements Runnable {
public void run() {
//Wait for a message from the "server".
synchronized(CreativeName.VirtualServer) {
try {
CreativeName.VirtualServer.wait();
} catch (InterruptedException e) {e.printStackTrace();}
}
//Message received,remove button.
Component[] components = Gui.panel.getComponents();
for(int b = 0; b < components.length; b++) {
if(((Button) components[b]).getLabel().contentEquals("A")) {
Gui.panel.remove((Button) components[b]);
Gui.panel.revalidate();
Gui.panel.repaint();
break;
}
}
}
}
class Gui extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
protected static JPanel panel;
protected static Button remove, A, B;
public Gui() {
super(new GridBagLayout());
remove = new Button("Remove");
remove.setBackground(new Color(250, 200, 200));
remove.addActionListener(this);
A = new Button("A");
A.setBackground(new Color(200, 200, 250));
B = new Button("B");
B.setBackground(new Color(250, 250, 0));
panel = new JPanel(new GridLayout(0,3));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
add(remove, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 5;
c.gridheight = 5;
add(panel, c);
panel.add(A);
panel.add(B);
}
public void actionPerformed(ActionEvent event) {
if(event.getSource() == remove) {
//Send a message from the "server".
synchronized(CreativeName.VirtualServer) {
CreativeName.VirtualServer.notify();
}
}
}
static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Button Dilemma");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(300, 400));
//Add contents to the window.
frame.add(new Gui());
//Display the window.
frame.pack();
frame.setVisible(true);
}
}
I set up a monitor to simulate the server and it seems the problem is the thread safety. Perhaps i can reverse the monitor so a message from the server will notify the Gui thread? I don't see were to get a handle on it yet tho.
EDIT: After making sure that the call occurs on the EDT I am getting the same results.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CreativeName {
public static Thread listen;
static Object VirtualServer = new Object();
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Gui.createAndShowGUI();
}
});
listen = new Thread(new FromServer());
listen.start();
}
}
class FromServer implements Runnable {
public void run() {
//Wait for a message from the "server".
synchronized(CreativeName.VirtualServer) {
try {
CreativeName.VirtualServer.wait();
} catch (InterruptedException e) {e.printStackTrace();}
}
//Message received,remove button.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (SwingUtilities.isEventDispatchThread()) {
System.err.println("Is running on EDT");
} else {
System.err.println("Is not running on EDT");
}
Component[] components = Gui.panel.getComponents();
for(int b = 0; b < components.length; b++) {
if(((Button) components[b]).getLabel().contentEquals("A")) {
Gui.panel.remove((Button) components[b]);
Gui.panel.revalidate();
Gui.panel.repaint();
break;
}
}
}
});
}
}
class Gui extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
protected static JPanel panel;
protected static Button remove, A, B;
public Gui() {
super(new GridBagLayout());
remove = new Button("Remove");
remove.setBackground(new Color(250, 200, 200));
remove.addActionListener(this);
A = new Button("A");
A.setBackground(new Color(200, 200, 250));
B = new Button("B");
B.setBackground(new Color(250, 250, 0));
panel = new JPanel(new GridLayout(0,3));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
add(remove, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 5;
c.gridheight = 5;
add(panel, c);
panel.add(A);
panel.add(B);
}
public void actionPerformed(ActionEvent event) {
if(event.getSource() == remove) {
//Send a message from the "server".
synchronized(CreativeName.VirtualServer) {
CreativeName.VirtualServer.notify();
}
}
}
static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Button Dilemma");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(300, 400));
//Add contents to the window.
frame.add(new Gui());
//Display the window.
frame.pack();
frame.setVisible(true);
}
}

Related

How to know which reference is static in Java

I am currently working on GUI of simple food ordering system. I created a button that whenever user clicks it it will go to another frame, however I am facing problem when I want to close the first frame (setVisible(false)).
This is my first frame
public class MainFrame extends JFrame {
private Manager manager = new Manager();
private JPanel titlepane;
private JLabel title;
MainFrame(String name){
setTitle(name);
}
public void content() {
Font titlefont = new Font("Times New Roman", Font.PLAIN, 22);
setLayout(new BorderLayout());
titlepane = new JPanel();
title = new JLabel("Welcome to POS!");
title.setFont(titlefont);
titlepane.add(title);
manager.LoginGUI();
add(titlepane,BorderLayout.NORTH);
add(manager,BorderLayout.CENTER);
}
public void runGUI() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
content();
setSize(700,700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
}
});
}
This is another class where the button is
public class Manager extends JPanel implements ActionListener {
private ArrayList<AccountInfo> manager = new ArrayList<AccountInfo>();
private GridBagConstraints gbc = new GridBagConstraints();
private JLabel id;
private JLabel pw;
private JTextField idfill;
private JTextField pwfill;
private JButton login;
private int isManager = 0;
private String idinput, pwinput;
private int temp = -1;
Manager() {
this.manager.add(new AccountInfo("admin", "1234"));
}
public void addManager(AccountInfo newManager) {
this.manager.add(newManager);
}
public void LoginGUI() {
Font standard = new Font("Times New Roman", Font.PLAIN, 18);
setLayout(new GridBagLayout());
id = new JLabel("ID");
id.setFont(standard);
// Alignment
gbc.gridx = 0;
gbc.gridy = 0;
gbc.ipadx = 10;
gbc.ipady = 10;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(id, gbc);
idfill = new JTextField(10);
idfill.setFont(standard);
// Alignment
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(idfill, gbc);
pw = new JLabel("Password");
pw.setFont(standard);
// Alignment
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(pw, gbc);
pwfill = new JTextField(10);
pwfill.setFont(standard);
// Alignment
gbc.gridx = 1;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(pwfill, gbc);
login = new JButton("Login");
login.setFont(standard);
login.addActionListener(this);
// Alignment
gbc.gridx = 1;
gbc.gridy = 2;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(login, gbc);
}
public void actionPerformed(ActionEvent e) {
verify();
if(isManager == 1) {
MenuFrame menu = new MenuFrame("Menu");
menu.runGUI();
MainFrame.setVisible(false); // This is the problem
}
}
private void verify() {
idinput = idfill.getText().trim();
pwinput = pwfill.getText();
for (int i = 0; i < manager.size(); i++) {
if (idinput.equals(manager.get(i).id)) {
temp = i;
}
}
if(temp == -1) {
JOptionPane.showMessageDialog(null, "Id or password incorrect, try again");
} else if(pwinput.equals(manager.get(temp).password)) {
isManager = 1;
} else
JOptionPane.showMessageDialog(null, "Id or password incorrect, try again");
}
}
(The codes are a bit lengthy as I am not confident that the other part was correct. All I know this has nothing to do with MenuFrame)
I get this error:
Cannot make a static reference to the non-static method setVisible(boolean) from the type Window
It might be my fault where it is not obvious enough for me to know which part of Manager or MainFrame is static. I also came across other posts regarding the same issue but none relates with mine. (Other post was having obvious static method)
Also tried the create an MainFrame object in Manager but it made it worse, please help, thank you!
You indeed need to keep the MainFrame object somewhere accessible, keep a reference to it. For this MVC, Model-View-Controller, is a nice paradigm.
Use MVC
I personally have my main method for swing in a Controller class (so the controller is the application class). It creates the main frame (View) and the controller is passed.
public void actionPerformed(ActionEvent e) {
verify();
if(isManager == 1) {
MenuFrame menu = new MenuFrame("Menu");
menu.runGUI();
controller.setMainFrameVisible(false);
}
}
Controller:
private MainFrame mainFrame;
public setMainFrameVisible(boolean visible) {
MainFrame.setVisible(visible);
}
Pass the MainFrame instance.
However you may also pass the MainFrame:
private final MainFrame mainFrame;
Manager(MainFrame mainFrame) {
this.mainFrame = mainFrame;
}
public void actionPerformed(ActionEvent e) {
verify();
if(isManager == 1) {
MenuFrame menu = new MenuFrame("Menu");
menu.runGUI();
mainFrame.setVisible(false);
}
}
If the panel is inside the MainFrame
((JFrame) getTopLevelAncestor()).setVisible(false);
Tip:
Should the application exit (EXIT_ON_CLOSE), change the default close operation.
MainFrame(String name){
setTitle(name);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}

Timer continues ticking when button is clicked instead of restarting

I am working on a Quiz app game (screenshot above). Each time the user clicks on the Next button, I want the timer to restart. Unfortunately this does not happen, the timer keeps ticking. I'm not sure why. What can I try to fix this?
final class Gui extends JFrame {
private Timer timer;
private JLabel timerLabel;
private void createWindow() {
display = new Display();
setLayout(new BorderLayout(3, 3));
add(display, BorderLayout.CENTER);
JPanel timerPanel = new JPanel();
timerPanel.setBorder(new EmptyBorder(0, 0, 0, 0));
timerPanel.setBackground(new Color(0x00bcda));
add(timerPanel, BorderLayout.PAGE_START);
timerLabel = new JLabel("01:00", SwingConstants.RIGHT);
timerLabel.setFont(new Font("Arial", Font.BOLD, 20));
timerLabel.setHorizontalAlignment(JLabel.RIGHT);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridy = 0;
timerLabel.setForeground(Color.black);
timerPanel.add(timerLabel, c);
timer = new Timer(1000, new ActionListener() {
int time = 60;
#Override
public void actionPerformed(ActionEvent e) {
time--;
timerLabel.setText(format(time / 60) + ":" + format(time % 60));
if (time == 0) {
timer = (Timer) e.getSource();
timer.stop();
}
}
});
}
private class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("Quit")) {
System.exit(0);
} else if (cmd.equals("Start")) {
timer.start();
} else if (cmd.equals("Next")) {
timer.restart();
}
display.repaint();
}
}
}
Restart of timer provides no reinitialization of your time filed.
int time = 60; // here is your problem
To avoid this problem you need to recreate your timer and start it again. For example you can move your timer initialization in a separate method:
final class Gui extends JFrame {
private Timer timer;
private JLabel timerLabel;
private void createWindow() {
display = new Display();
setLayout(new BorderLayout(3, 3));
add(display, BorderLayout.CENTER);
JPanel timerPanel = new JPanel();
timerPanel.setBorder(new EmptyBorder(0, 0, 0, 0));
timerPanel.setBackground(new Color(0x00bcda));
add(timerPanel, BorderLayout.PAGE_START);
timerLabel = new JLabel("01:00", SwingConstants.RIGHT);
timerLabel.setFont(new Font("Arial", Font.BOLD, 20));
timerLabel.setHorizontalAlignment(JLabel.RIGHT);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridy = 0;
timerLabel.setForeground(Color.black);
timerPanel.add(timerLabel, c);
initTimer();
}
private void initTimer() {
timer = new Timer(1000, new ActionListener() {
int time = 60;
#Override
public void actionPerformed(ActionEvent e) {
time--;
timerLabel.setText(format(time / 60) + ":" + format(time % 60));
if (time == 0) {
timer = (Timer) e.getSource();
timer.stop();
}
}
});
}
private class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("Quit")) {
System.exit(0);
} else if (cmd.equals("Start")) {
timer.start();
} else if (cmd.equals("Next")) {
timer.stop();
initTimer();
timer.start();
}
display.repaint();
}
}
}
Another possibility is to move your time field in your Gui class. In this case you need to reset this field on timer restart.

Java not able to close the JFrame

I am not able to close my frame after I click the button. The tricky part is that I do not need to quit the whole application, just close the GUI (not with system exit).
Would you be able to assist me?
Thank you in advance!!!
Main.java
public class Main {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://my.emerchantpay.com/");
eMerchantPay emp = PageFactory.initElements(driver, eMerchantPay.class);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new MainFrame("Please enter your credentials");
frame.setSize(500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
MainFrame.java
public class MainFrame extends JFrame {
private DetailsPanel detailsPanel;
public MainFrame(String title) {
super(title);
// Set layout manager
setLayout(new BorderLayout());
// Create Swing components
final JTextArea textArea = new JTextArea();
detailsPanel = new DetailsPanel();
detailsPanel.addDetailsListener(new DetailListener() {
public void detailEventOccured(DetailEvent event) {
String text = event.getText();
textArea.append(text);
}
});
// Add Swing components to content pane
Container c = getContentPane();
//c.add(textArea, BorderLayout.CENTER);
c.add(detailsPanel, BorderLayout.CENTER);
}
DetailsPanel.java
public class DetailsPanel extends JPanel{
private static final long serialVersionUID = 1234567891;
private EventListenerList listenerList = new EventListenerList();
public DetailsPanel() {
Dimension size = getPreferredSize();
size.width = 250;
setPreferredSize(size);
setBorder(BorderFactory.createTitledBorder("Personal Details"));
JLabel nameLabel = new JLabel("Name: ");
JLabel passwordLabel = new JLabel("Password: ");
final JTextField nameField = new JTextField(10);
final JPasswordField passwordField = new JPasswordField(10);
JButton addBtn = new JButton("Submit");
addBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
String name = nameField.getText();
String password = passwordField.getText();
String text = name + ": " + password + "\n";
System.out.println (text);
}
});
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
/// First column ///
gc.anchor = GridBagConstraints.LINE_END;
gc.weightx = 0.5;
gc.weighty = 0.5;
gc.gridx = 0;
gc.gridy = 0;
add(nameLabel, gc);
gc.gridx = 0;
gc.gridy = 1;
add(passwordLabel, gc);
/// Second column ///
gc.anchor = GridBagConstraints.LINE_START;
gc.gridx = 1;
gc.gridy = 0;
add(nameField, gc);
gc.gridx = 1;
gc.gridy = 1;
add(passwordField, gc);
/// Final row ///
gc.weighty = 10;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
gc.gridx = 1;
gc.gridy = 2;
add(addBtn, gc);
}
public void fireDetailEvent(DetailEvent event) {
Object[] listeners = listenerList.getListenerList();
for (int i=0; i < listeners.length; i += 2) {
if (listeners[i] == DetailListener.class) {
((DetailListener)listeners[i+1]).detailEventOccured(event);
}
}
}
public void addDetailsListener(DetailListener listener) {
listenerList.add(DetailListener.class, listener);
}
public void removeDetailListener(DetailListener listener) {
listenerList.remove(DetailListener.class, listener);
}
I need to close the frame once I click the login button in this piece of code:
addBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
String name = nameField.getText();
String password = passwordField.getText();
String text = name + ": " + password + "\n";
System.out.println (text);
}
});
In actionPerformed, add these lines to obtain and close the parent frame :
JFrame frame = (JFrame) SwingUtilities.getWindowAncestor(addBtn);
frame.dispose();// or frame.setVisible(false), depending on your needs
Note that you will have to declare your button final in order to use it in the anonymous listener :
final JButton addBtn = new JButton("Submit");

How to open another program with for statements java?

I'm very new to java I have been doing basic stuff and for my final project we wanted to create a gui rpg. Our problem right now is we can't figure out how to open another program by clicking the gui button. My friends told me you guys use eclipse so I don't have to show imports. Keep in mind I'm in highschool so don't judge too harsh :D Here is our code:
public class Narnia {
private static final String BACKHGROUND_IMAGE_URL = "http://randomwallpapers.net/fantasy-castle-1920x1080-wallpaper328374.jpg";
protected void initUI() throws MalformedURLException {
JFrame frame = new JFrame(Narnia.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final ImageIcon backgroundImage = new ImageIcon(new URL(BACKHGROUND_IMAGE_URL));
JLabel mainPanel = new JLabel(backgroundImage) {
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
Dimension lmPrefSize = getLayout().preferredLayoutSize(this);
size.width = Math.max(size.width, lmPrefSize.width);
size.height = Math.max(size.height, lmPrefSize.height);
return size;
}
};
mainPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
gbc.weightx = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = GridBagConstraints.REMAINDER;
for (int i = 0; i < 1; i++) {
mainPanel.add(new JButton("Play" + ("")), gbc);
}
for (int i = 0; i < 1; i++) {
mainPanel.add(new JButton("Credits " + ("")), gbc);
}
for (int i = 0; i < 1; i++) {
mainPanel.add(new JButton("Exit " + ("")), gbc);
}
// Let's put a filler bottom component that will push the rest to the top
gbc.weighty = 1.0;
mainPanel.add(Box.createGlue(), gbc);
frame.add(mainPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new Narnia().initUI();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Here is the class we want to open:
public class chooseaclass {
private static final String BACKHGROUND_IMAGE_URL = "http://randomwallpapers.net/fantasy-castle-1920x1080-wallpaper328374.jpg";
protected void initUI() throws MalformedURLException {
JFrame frame = new JFrame(chooseaclass.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final ImageIcon backgroundImage = new ImageIcon(new URL(BACKHGROUND_IMAGE_URL));
JLabel mainPanel = new JLabel(backgroundImage) {
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
Dimension lmPrefSize = getLayout().preferredLayoutSize(this);
size.width = Math.max(size.width, lmPrefSize.width);
size.height = Math.max(size.height, lmPrefSize.height);
return size;
}
};
mainPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(40, 40, 40, 40);
gbc.weightx = 1.0;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
for (int i = 0; i < 1; i++) {
mainPanel.add(new JButton("Archer" + ("")), gbc);
}
for (int i = 0; i < 1; i++) {
mainPanel.add(new JButton("Mage " + ("")), gbc);
}
for (int i = 0; i < 1; i++) {
mainPanel.add(new JButton("Knight " + ("")), gbc);
}
// Let's put a filler bottom component that will push the rest to the top
gbc.weighty = 1.0;
mainPanel.add(Box.createGlue(), gbc);
frame.add(mainPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new chooseaclass().initUI();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
You need to add a listener to whatever button you want. In this case, we'll use an ActionListener.
Let's just use this existing line that you already have: mainPanel.add(new JButton("Play" + ("")), gbc);
First of all, to make it simpler, let's put that JButton in a variable:
JButton playButton = new JButton("Play" + (""));
To add a listener, we need to use the method addActionListener().
Now add an ActionListener as an anonymous class so that we can implement a method that the system can call behind the scenes:
JButton playButton = new JButton("Play" + (""));
playButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
new chooseaclass.initUI() //insantiate a new chooseaclass instance
}
});
mainPanel.add(playButton, gbc);
Within the actionPerformed() method, I instantiated a chooseaclass. You can do whatever you want from there.
I wrote this code off the cuff without an editor so it may contain syntax errors.

java JFame will not work when started by actionPerformed

I have been googling an sherthing for an solution to this problem a lot but can't find any answer how to fix this. My problem is that when i start a new jframe from an actionevent from pressing a button the class white the JFrame opens but then the programs starts to freeze and the pop up windows stays blank.
Her is the cod i apologize if there is some bad programing or some words in swedish:
The start upp class:
import java.util.ArrayList;
public class maineClassen {
ArrayList<infoClass> Infon = new ArrayList<>();
public static void main (String [] args)
{
referenser referens = new referenser();
Startskärmen ss = new Startskärmen(referens);
}
}
The "startskärm" the first screen to com to:
public class Startskärmen extends JFrame implements ActionListener {
referenser referens;
ArrayList<infoClass> Infon;
JButton öppna = new JButton("open");
JButton ny = new JButton("create new");
JButton radera = new JButton("erase");
JScrollPane pane = new JScrollPane();
DefaultListModel mod = new DefaultListModel();
JList list = new JList(mod);
JScrollPane sp = new JScrollPane(list);
JLabel texten = new JLabel("pre-alpha 0.1");
public Startskärmen(referenser re)
{
//references should be sent by itself or received
referens = re;
Infon = referens.getInfoReferens();
//build up the window
JPanel labelPanel = new JPanel();
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.LINE_AXIS));
labelPanel.setBorder(BorderFactory.createEmptyBorder(10,10,0,10));
labelPanel.add(texten);
JPanel scrollPanel = new JPanel();
scrollPanel.setLayout(new BoxLayout(scrollPanel, BoxLayout.LINE_AXIS));
scrollPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
scrollPanel.add(sp);// man kan ocksä sätta in --> pane <--
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(öppna);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(ny);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(radera);
Container contentPane = getContentPane();
contentPane.add(labelPanel,BorderLayout.NORTH);
contentPane.add(scrollPanel, BorderLayout.CENTER);
contentPane.add(buttonPanel, BorderLayout.PAGE_END);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setSize(500, 500);
//adda action listener
ny.addActionListener(this);
öppna.addActionListener(this);
radera.addActionListener(this);
//skapaNyIC();
}
infoClass hh;
public void skapaNyIC()
{
Infon.add(new infoClass());
Infon.get(Infon.size() -1).referenser(Infon); //Infon.get(Infon.size() -1)
mod.addElement(Infon.get(Infon.size() -1).getName());
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == ny)
{
skapaNyIC();
}
else if(e.getSource() == öppna)
{
JOptionPane.showMessageDialog(texten,"This function doesn't exist yet");
}
else if(e.getSource() == radera)
{
JOptionPane.showMessageDialog(texten, "This function doesn't exist yet");
}
}
}
The class where the information will be stored and that creates the window (class) that will show the info:
public class infoClass {
ArrayList<infoClass> Infon;
private infoClass ic;
private String namn = "inget namn existerar";
private String infoOmInfo = null;
private int X_Rutor = 3;
private int Y_Rutor = 3;
private String[] information = new String[X_Rutor + Y_Rutor];
//info om dessa värden
public infoClass()
{
}
public void referenser(infoClass Tic)
{
ic = Tic;
infonGrafiskt ig = new infonGrafiskt(ic);
}
public void referenser(ArrayList<infoClass> Tic)
{
ic = Tic.get((Tic.size() - 1 ));
System.out.println("inna");
infonGrafiskt ig = new infonGrafiskt(ic);
ig.setVisible(true);
System.out.println("efter");
}
public String namnPåInfon()
{
return namn;
}
//namnen
public String getName()
{
return namn;
}
public void setNamn(String n)
{
namn = n;
}
//xkordinaterna
public int getX_Rutor()
{
return X_Rutor;
}
public void setX_Rutor(int n)
{
X_Rutor = n;
}
//y kordinaterna
public int getY_Rutor()
{
return Y_Rutor;
}
public void setY_Rutor(int n)
{
Y_Rutor = n;
}
//informationen
public String[] getInformationen()
{
return information;
}
public void setInformationen(String[] n)
{
information = n;
}
//infoOmInfo
public String getinfoOmInfo()
{
return infoOmInfo;
}
public void setinfoOmInfo(String n)
{
infoOmInfo = n;
}
}
The class that will show the info created by the window a bow:
public class infonGrafiskt extends JFrame implements ActionListener{
infoClass ic;
infonGrafiskt ig;
//tillrutnätet
JPanel panel = new JPanel(new SpringLayout());
boolean pausa = true;
//sakerna till desigen grund inställningar GI = grund inställningar
JButton GIklarKnapp = new JButton("Spara och gå vidare");
JTextField GInamn = new JTextField();
JLabel GINamnText = new JLabel("Namn:");
JTextField GIxRutor = new JTextField();
JLabel GIxRutorText = new JLabel("Antal rutor i X-led:");
JTextField GIyRutor = new JTextField();
JLabel GIyRutorText = new JLabel("Antal rutor i Y-led:");
JLabel GIInfo = new JLabel("Grund Inställningar");
// de olika framm:arna
JFrame GIframe = new JFrame("SpringGrid");
JFrame frame = new JFrame("SpringGrid");
//info om denna infon som finns här
JTextArea textArea = new JTextArea();
JScrollPane infoOmClasen = new JScrollPane(textArea); //hadde text area förut
JLabel infoRutan = new JLabel("Informatin om denna resuldatdatabank:");
//namnet på informationsdatabanken
JLabel namnetPåInfot = new JLabel("Namnet på denna resuldatdatabas.");
JButton ändraNamn = new JButton("Ändra namn");
JButton sparaAllt = new JButton("Spara allt");
public infonGrafiskt(infoClass Tic)
{
//få startinfo
namnOchRutor();
ic = Tic;
//skapar om rutan
JPanel p1 = new JPanel();
p1.setLayout(new BoxLayout(p1, BoxLayout.PAGE_AXIS));
p1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
namnetPåInfot.setFont(new Font("Dialog",1,22));
p1.add(namnetPåInfot);
//pausa programet tills grundinställningarna är instälda
int m =1;
try {
while(m ==1)
{
Thread.sleep(100);
if(pausa == false)
m =2;
}
} catch(InterruptedException e) {
}
//Create the panel and populate it. skapar den så alla kommer åt den
//JPanel panel = new JPanel(new SpringLayout());
for (int i = 0; i < ic.getX_Rutor()*ic.getY_Rutor(); i++) {
JTextField textField = new JTextField(Integer.toString(i));
panel.add(textField);
}
//Lay out the panel.
SpringUtilities.makeGrid(panel,
ic.getY_Rutor(), ic.getX_Rutor(), //rows, cols
5, 5, //initialX, initialY
5, 5);//xPad, yPad
//set up the window.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//p1.add(ändraNamn);
JPanel p2 = new JPanel();
p2.setLayout(new BoxLayout(p2, BoxLayout.PAGE_AXIS));
p2.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
p2.add(infoRutan);
infoOmClasen.setPreferredSize(new Dimension(0,100));
p2.add(infoOmClasen);
JPanel p3 = new JPanel();
p3.setLayout(new FlowLayout());
p3.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
p3.setLayout(new BoxLayout(p3, BoxLayout.LINE_AXIS));
p3.add(ändraNamn);
p3.add(sparaAllt);
//Set up the content pane.
panel.setOpaque(true); //content panes must be opaque
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));
frame.add(p1);
frame.add(p2);
frame.add(panel);//frame.setContentPane(panel);
frame.add(p3);
//Display the window.
frame.pack();
sparaAllt.addActionListener(this);
ändraNamn.addActionListener(this);
}
private void namnOchRutor()
{
System.out.println("inna 2");
//sättigång action listner
GIklarKnapp.addActionListener(this);
frame.setVisible(false);
//frameStart.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GIframe.setLayout(new BoxLayout(GIframe.getContentPane(), BoxLayout.PAGE_AXIS));
JPanel GIP0 = new JPanel();
GIP0.setLayout(new BoxLayout(GIP0,BoxLayout.LINE_AXIS));
GIP0.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
GIP0.add(GIInfo);
GIInfo.setFont(new Font("Dialog",1,22));
JPanel GIP1 = new JPanel();
GIP1.setLayout(new BoxLayout(GIP1,BoxLayout.LINE_AXIS));
GIP1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
GIP1.add(GINamnText);
GIP1.add(Box.createRigidArea(new Dimension(10, 0)));
GIP1.add(GInamn);
JPanel GIP2 = new JPanel();
GIP2.setLayout(new BoxLayout(GIP2,BoxLayout.LINE_AXIS));
GIP2.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP2.add(GIxRutorText);
GIP2.add(Box.createRigidArea(new Dimension(10, 0)));
GIP2.add(GIxRutor);
JPanel GIP3 = new JPanel();
GIP3.setLayout(new BoxLayout(GIP3,BoxLayout.LINE_AXIS));
GIP3.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP3.add(GIyRutorText);
GIP3.add(Box.createRigidArea(new Dimension(10, 0)));
GIP3.add(GIyRutor);
JPanel GIP4 = new JPanel();
GIP4.setLayout(new BoxLayout(GIP4,BoxLayout.LINE_AXIS));
GIP4.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP4.add(GIklarKnapp);
System.out.println("inna 3");
//lägga till sakerna gurund instllnings framen
GIframe.add(GIP0);
GIframe.add(GIP1);
GIframe.add(GIP2);
GIframe.add(GIP3);
GIframe.add(GIP4);
//desigen
System.out.println("inna 4");
GIframe.pack();
GIframe.setVisible(true);
System.out.println("inna5");
}
/*public static void main (String [] args)
{
infoClass i = new infoClass();
infonGrafiskt ig = new infonGrafiskt(i);
}*/
public void referenserna( infonGrafiskt Tig)
{
ig = Tig;
}
private void skrivTillbaka()
{
String[] tillfäligString = ic.getInformationen();
Component[] children = panel.getComponents();
for (int i=0;i<children.length;i++){
if (children[i] instanceof JTextField){
((JTextField)children[i]).setText(tillfäligString[i]);
System.out.println(tillfäligString[i]);
}
}
namnetPåInfot.setText(ic.getName());
textArea.setText(ic.getinfoOmInfo());
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == GIklarKnapp)
{
//skicka x och y antal ett och så
ic.setNamn(GInamn.getText());
ic.setX_Rutor(Integer.parseInt(GIxRutor.getText()));
ic.setY_Rutor(Integer.parseInt( GIyRutor.getText()));
namnetPåInfot.setText(ic.getName());
pausa = false;
GIframe.setVisible(false);
frame.setVisible(true);
}
if(e.getSource() == sparaAllt)
{
String[] tillfäligString = ic.getInformationen();
Component[] children = panel.getComponents();
for (int i=0;i<children.length;i++){
if (children[i] instanceof JTextField){
tillfäligString[i] = ((JTextField)children[i]).getText();
System.out.println(tillfäligString[i]);
}
}
ic.setInformationen(tillfäligString);
ic.setNamn(namnetPåInfot.getText());
ic.setinfoOmInfo(textArea.getText());
}
if(e.getSource() == ändraNamn)
{
skrivTillbaka();
}
}
}
so my problem now is that i can't create a new "infoclass" that will show the info in the "infoGrafikst" class. with the code:
Infon.add(new infoClass());
Infon.get(Infon.size() -1).referenser(Infon); //Infon.get(Infon.size() -1)
mod.addElement(Infon.get(Infon.size() -1).getName());
that am triggered by an button click.
Sorry for all the cod, but didn't know how to show my problem in another way.
Thanks a lot. I did find out that it was this code
int m =1;
try {
while(m ==1) {
Thread.sleep(100);
if(pausa == false)
m =2;
}
} catch(InterruptedException e) {
}
that made it not work...
Well I haven't gone through your code may be beacuse I am too lazy to read pages of code.Well i think the new window you are creating must be interfering with EDT.
Well i have done a short example which may help you, and its smooth:
import java.awt.event.ActionEvent;
import javax.swing.*;
public class FrameLaunch {
void inti(){
final JFrame f=new JFrame();
final JFrame f2=new JFrame();
final JTextArea ja=new JTextArea();
JButton b =new JButton("press for a new JFrame");
f2.add(b);
f2.pack();
f2.setVisible(true);
b.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e) {
f2.setVisible(false);
f.setSize(200,200);
ja.setText("THIS IS NOT FROZEN");
f.add(ja);
f.setVisible(true);
f.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
}
});
}
public static void main(String[] args)
{
FrameLaunch frame = new FrameLaunch();
frame.inti();
}
}

Categories

Resources