Button not displaying frame connected to it - java

I am trying to write code for an application I'm making, I have my main frame with 6 buttons on them. When I push one of my buttons, it is meant to bring up a frame that has a tabbed layout set up.
I have the tabbed frame coded correctly and when I set each frame as visible they will appear to screen but they don't appear when the button is pushed.
I have action listeners connected to the buttons and the frames I want to connect with them as well as constructors but for some reason I can't get my code to work correctly.
I have added my driver and my first two forms I'm trying to connect to each other.
public class SimpsonsDriver {
//#param args the command line arguments
public static void main(String[] args) {
// TODO code application logic here
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame simpsonFrame = new JFrame("The Simpson");
JFrame homerFrame = new JFrame ("Homer Simpson");
JFrame margeFrame = new JFrame ("Marge Simpson");
JFrame bartFrame = new JFrame ("Bart Simpson");
JFrame lisaFrame = new JFrame("Lisa Simpson");
JFrame maggieFrame = new JFrame("Maggie Simpson");
SimpsonForm simpsonForm = new SimpsonForm(simpsonFrame, homerFrame, margeFrame, bartFrame,
lisaFrame, maggieFrame);
HomerForm homerForm = new HomerForm(homerFrame, simpsonFrame);
MargeForm margeForm = new MargeForm(margeFrame, simpsonFrame);
BartForm bartForm = new BartForm(bartFrame, simpsonFrame);
LisaForm lisaForm = new LisaForm(lisaFrame, simpsonFrame);
MaggieForm maggieForm = new MaggieForm(maggieFrame, simpsonFrame);
}
}
public class SimpsonForm implements ActionListener{
JFrame simpsonFrame, homerFrame, margeFrame, bartFrame, lisaFrame, maggieFrame;//instance variables
JButton homerBtn, margeBtn, bartBtn, lisaBtn, maggieBtn, closeBtn; //instance variables
public SimpsonForm(JFrame simpsonFrame, JFrame homerFrame, JFrame margeFrame, JFrame bartFrame, JFrame lisaFrame, JFrame maggieFrame) {
this.simpsonFrame = simpsonFrame;
this.homerFrame = homerFrame;
this.margeFrame = margeFrame;
this.bartFrame = bartFrame;
this.lisaFrame = lisaFrame;
this.maggieFrame = maggieFrame;
simpsonFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createPanel();
}//end constructor method SimpsonForm
private void createPanel(){
homerBtn = new JButton ("Homer");
margeBtn = new JButton ("Marge");
bartBtn = new JButton ("Bart");
lisaBtn = new JButton ("Lisa");
maggieBtn = new JButton ("Maggie");
closeBtn = new JButton ("Close");
FlowLayout flow = new FlowLayout();
JPanel p1 = new JPanel();
p1.setLayout(flow);
JPanel p2 = new JPanel();
p2.setLayout(flow);
ImageIcon img = new ImageIcon(this.getClass().getResource("simpsons.png"));
JLabel imgLabel = new JLabel();
imgLabel.setIcon(img);
imgLabel.setBounds(10, 10, img.getIconWidth(), img.getIconHeight());
p1.add(imgLabel);
p2.add(homerBtn);
homerBtn.addActionListener(this);
p2.add(margeBtn);
margeBtn.addActionListener(this);
p2.add(bartBtn);
bartBtn.addActionListener(this);
p2.add(lisaBtn);
lisaBtn.addActionListener(this);
p2.add(maggieBtn);
maggieBtn.addActionListener(this);
p2.add(closeBtn);
closeBtn.addActionListener(this);
simpsonFrame.setLayout(new BorderLayout());
simpsonFrame.setResizable(false);
simpsonFrame.add(p1, BorderLayout.BEFORE_FIRST_LINE);
simpsonFrame.add(p2, BorderLayout.CENTER);
simpsonFrame.setSize(425, 425);
simpsonFrame.setLocationRelativeTo(null);
simpsonFrame.setVisible(true);
}//end method createPanel
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == homerBtn) {
homerFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == margeBtn) {
margeFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == bartBtn) {
bartFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == lisaBtn) {
lisaFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == maggieBtn) {
maggieFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == closeBtn) {
System.exit(0);
}//end if
}//end event handler
}
public class HomerForm implements ActionListener{
JFrame simpsonFrame, homerFrame;
JButton closeBtn;
public HomerForm(JFrame simpsonFrame, JFrame homerFrame ) {
this.simpsonFrame = simpsonFrame;
this.homerFrame = homerFrame;
createPanel();
}
private void createPanel() {
homerFrame = new JFrame("Homer Simpson");
closeBtn = new JButton("Close");
closeBtn.setSize(200, 50);
ImageIcon ogImage = new ImageIcon(this.getClass().getResource("/homer1.png"));
JLabel ogLabel = new JLabel();
ogLabel.setIcon(ogImage);
JPanel p1 = new JPanel();
p1.add(ogLabel);
ImageIcon hwImage = new ImageIcon(this.getClass().getResource("/homer2.png"));
JLabel hwLabel = new JLabel();
hwLabel.setIcon(hwImage);
JPanel p2 = new JPanel();
p2.add(hwLabel);
ImageIcon cImage = new ImageIcon(this.getClass().getResource("/homer3.png"));
JLabel cLabel = new JLabel();
cLabel.setIcon(cImage);
JPanel p3 = new JPanel();
p3.add(cLabel);
JPanel p4 = new JPanel();
JTabbedPane tab = new JTabbedPane();
tab.setBounds(100, 100, 300, 300);
tab.add("Original", p1);
tab.add("HalfWay", p2);
tab.add("Current", p3);
tab.add("Close", p4);
p4.add(closeBtn);
closeBtn.setLayout(new BorderLayout());
closeBtn.addActionListener(this);
homerFrame.add(tab);
homerFrame.setResizable(false);
homerFrame.setSize(500, 500);
homerFrame.setLocationRelativeTo(null);
homerFrame.setVisible(false);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == closeBtn) {
homerFrame.setVisible(false);
simpsonFrame.setVisible(true);
}//end if
else
{
System.exit(0);
}
}
}
When i run it, i get this image. simpsonsFrame
this is what happens when i click the homer button i then have to max it to see a blank screen.homerFrame.
when i set the homerFrame to visible, it displays what i what to appear if the button was pushed.it shows homerFrame then it shows the simpsonFrame.homersetVisible true

Related

JLable not change after change the TextFiled and also the combox

Hi I'm doing a program that firstly opens setting menu like in the picture
enter image description here
first I select the choices of the game I want from the jcombox and jdialog that open window to set the names .
this is the code of it :
public class SettingMenu extends JFrame {
boolean is3players = false, is4players = false;
BufferedImage settingImage;
String[] playersChoises = { "2", "3", "4" };
String[] sizeChoises = { "30", "50", "100" };
JComboBox comboBoxPlayers;
JComboBox comboBoxSizes;
static JButton startGame, writeNames;
public SettingMenu() {
JLabel howManyPlayersText = new JLabel("How many players ?");
comboBoxPlayers = new JComboBox(playersChoises);
if (comboBoxPlayers.getSelectedItem().equals("3")) {
is3players = true;
}
if (comboBoxPlayers.getSelectedItem().equals("4")) {
is3players = true;
is4players = true;
}
JLabel writeNamesText = new JLabel("Set names of playes");
writeNames = new JButton("set names");
JLabel sizeOfBoredText = new JLabel("What the size of the bored ?");
comboBoxSizes = new JComboBox(sizeChoises);
startGame = new JButton("Click to start the game!");
howManyPlayersText.setBounds(177, 200, 270, 100);
comboBoxPlayers.setBounds(230, 270, 100, 30);
writeNamesText.setBounds(230, 210, 380, 250);
writeNames.setBounds(240, 350, 100, 36);
sizeOfBoredText.setBounds(177, 376, 300, 100);
comboBoxSizes.setBounds(230, 450, 100, 30);
startGame.setBounds(200, 500, 200, 44);
add(howManyPlayersText);
add(comboBoxPlayers);
add(writeNamesText);
add(writeNames);
add(sizeOfBoredText);
add(comboBoxSizes);
add(startGame);
setVisible(true);
}
public static void main(String[] args) {
// open this class
new SettingMenu();
// when i click on startgame bottun open the class of the game
startGame.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new LeadersAndSnake_Project201();
}
});
// when i click on writeNames bottun open the class of dialog
writeNames.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new SetNames();
}
});
}
}
and this is Set Names class which open the set names window
enter image description here
class SetNames extends JDialog {
public JTextField setNamePlayer1, setNamePlayer2, setNamePlayer3, setNamePlayer4;
public SetNames() {
this.setSize(280, 151);
this.setLocationRelativeTo(null);
JLabel name1 = new JLabel("Set Player's 1 name : ");
setNamePlayer1 = new JTextField(7);
setNamePlayer1.setText("Player 1");
JLabel name2 = new JLabel("Set Player's 2 name : ");
setNamePlayer2 = new JTextField(7);
setNamePlayer2.setText("Player 2");
JPanel panelOfDialog_1 = new JPanel();
panelOfDialog_1.add(name1);
panelOfDialog_1.add(setNamePlayer1);
JPanel panelOfDialog_2 = new JPanel();
panelOfDialog_2.add(name2);
panelOfDialog_2.add(setNamePlayer2);
JPanel panelOfDialog_3 = new JPanel();
JButton okBotton = new JButton("OK");
add(okBotton);
okBotton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setNamePlayer1 = new JTextField(setNamePlayer1.getText());
setNamePlayer2 = new JTextField(setNamePlayer2.getText());
setVisible(false);
}
});
panelOfDialog_3.add(okBotton);
add(panelOfDialog_1, BorderLayout.NORTH);
add(panelOfDialog_2, BorderLayout.CENTER);
add(panelOfDialog_3, BorderLayout.AFTER_LAST_LINE);
this.setVisible(true);
}
}
and this is the large class for the game but I just put the imprtant thinga here :
class LeadersAndSnake_Project201 extends JFrame implements ActionListener{
// Here I made an object of Setting Menu class for use the varible that it has
SettingMenu obj1 = new SettingMenu();
// Here I made an object of Set Names class to take the name inside the textfiled
SetNames obj2 = new SetNames();
public LeadersAndSnake_Project201() {
// -----------------left panel------------------------------
JPanel leftPanel = new JPanel();
GroupLayout groupLayout = new GroupLayout(leftPanel);
leftPanel.setLayout(groupLayout);
//---------------------------panel 1 for information player 1 -------------------------------------
JPanel panel1 = new JPanel();
ImageIcon imageMan1 = new ImageIcon("man1.png");
JLabel imageMan11 = new JLabel("", imageMan1, JLabel.CENTER);
JLabel player1text = new JLabel(obj2.setNamePlayer1.getText());
panel1.add(imageMan11);
panel1.add(player1text);
//---------------------------panel 2 for information player 2------------------------------------
JPanel panel2 = new JPanel();
ImageIcon imageMan2 = new ImageIcon("man2.png");
JLabel imageMan22 = new JLabel("", imageMan2, JLabel.CENTER);
JLabel player2text = new JLabel(obj2.setNamePlayer2.getText());
panel2.add(imageMan22);
panel2.add(player2text);
//---------------------------panel 3 for information player 3-------------------------------------
JPanel panel3 = new JPanel();
if(obj.is3 == true){
ImageIcon imageMan3 = new ImageIcon("man3.png");
JLabel imageMan33 = new JLabel("", imageMan3, JLabel.CENTER);
JLabel player3text = new JLabel("Player 3");
player2text.setFont(fontText);
panel3.add(imageMan33);
panel3.add(player3text);
}
}
}
Here on left panel are my problems
the jlable of player 1 and player 2 didn't chang even if I try to change them in the textfiled and the second problem is that the panel of player 3 didn't apper even if I select the chois "3" from the combox .
enter image description here
Try to call .pack() on the Frame after altering the elements.
EDIT
You have no code changing the labels. What you need is store the labels in a variable, like you did with other components, and in the ActionListener on on the okButton in SetNames(), instead of doing whatever you do to the TextFields there (which looks wrong), update the Label text.
So, for example
class SetNames extends JDialog {
[...]
public JButton okButton; // save okButton so others can add listeners
}
class LeadersAndSnake_Project201 extends JFrame implements ActionListener{
// Here I made an object of Set Names class to take the name inside the textfiled
SetNames obj2 = new SetNames();
public LeadersAndSnake_Project201() {
[...]
obj2.okButton.addActionListener(new ActionListener(){/*update labels*/});
}}

More than 1 object in a single JFrame

I'm hoping someone can push me in the right direction with this. I have 3 separate classes, Calculator, Calculator2, and a Calculator3. In principal they are all the same, except for a few changes to some of the buttons, so I'll just paste the code for Calculator. I was wondering how can I get them so all appear in a single JFrame next to each other in a main? I attached my most recent attempt of the main as well.
Here is Calculator:
public class Calculator implements ActionListener {
private JFrame frame;
private JTextField xfield, yfield;
private JLabel result;
private JButton subtractButton;
private JButton divideButton;
private JButton addButton;
private JButton timesButton;
private JPanel xpanel;
public Calculator() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
xpanel = new JPanel();
xpanel.setLayout(new GridLayout(3,2));
xpanel.add(new JLabel("x:", SwingConstants.RIGHT));
xfield = new JTextField("0", 5);
xpanel.add(xfield);
xpanel.add(new JLabel("y:", SwingConstants.RIGHT));
yfield = new JTextField("0", 5);
xpanel.add(yfield);
xpanel.add(new JLabel("Result:"));
result = new JLabel("0");
xpanel.add(result);
frame.add(xpanel, BorderLayout.NORTH);
/***********************************************************************
***********************************************************************
**********************************************************************/
JPanel southPanel = new JPanel(); //New panel for the artimatic buttons
southPanel.setBorder(BorderFactory.createEtchedBorder());
timesButton = new JButton("Multiplication");
southPanel.add(timesButton);
timesButton.addActionListener(this);
subtractButton = new JButton("Subtract");
southPanel.add(subtractButton);
subtractButton.addActionListener(this);
divideButton = new JButton("Division");
southPanel.add(divideButton);
divideButton.addActionListener(this);
addButton = new JButton("Addition");
southPanel.add(addButton);
addButton.addActionListener(this);
frame.add(southPanel , BorderLayout.SOUTH);
Font thisFont = result.getFont(); //Get current font
result.setFont(thisFont.deriveFont(thisFont.getStyle() ^ Font.BOLD)); //Make the result bold
result.setForeground(Color.red); //Male the result answer red in color
result.setBackground(Color.yellow); //Make result background yellow
result.setOpaque(true);
frame.pack();
frame.setVisible(true);
}
/**
* clear()
* Resets the x and y field to 0 after invalid integers were input
*/
public void clear() {
xfield.setText("0");
yfield.setText("0");
}
#Override
public void actionPerformed(ActionEvent event) {
String xText = xfield.getText(); //Get the JLabel fiels and set them to strings
String yText = yfield.getText();
int xVal;
int yVal;
try {
xVal = Integer.parseInt(xText); //Set global var xVal to incoming string
yVal = Integer.parseInt(yText); //Set global var yVal to incoming string
}
catch (NumberFormatException e) { //xVal or yVal werent valid integers, print message and don't continue
result.setText("ERROR");
clear();
return ;
}
if(event.getSource().equals(timesButton)) { //Button pressed was multiply
result.setText(Integer.toString(xVal*yVal));
}
else if(event.getSource().equals(divideButton)) { //Button pressed was division
if(yVal == 0) { //Is the yVal (bottom number) 0?
result.setForeground(Color.red); //Yes it is, print message
result.setText("CAN'T DIVIDE BY ZERO!");
clear();
}
else
result.setText(Integer.toString(xVal/yVal)); //No it's not, do the math
}
else if(event.getSource().equals(subtractButton)) { //Button pressed was subtraction
result.setText(Integer.toString(xVal-yVal));
}
else if(event.getSource().equals(addButton)) { //Button pressed was addition
result.setText(Integer.toString(xVal+yVal));
}
}
}
And here is my current main:
public class DemoCalculator {
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Calculators");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Calculator calc = new Calculator();
Calculator2 calc2 = new Calculator2();
JPanel calcPanel = new JPanel(new BorderLayout());
JPanel calcPanel2 = new JPanel(new BorderLayout());
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
//calcPanel.add(calc, BorderLayout.CENTER);
//calcPanel2.add(calc2, BorderLayout.CENTER);
mainPanel.add(calcPanel);
mainPanel.add(calcPanel2);
calcPanel.add(mainPanel);
mainFrame.getContentPane().add(calcPanel);
mainFrame.getContentPane().add(calcPanel2);
mainFrame.pack();
mainFrame.setVisible(true);
}
}
You should just create a single JFrame and put your Calculator classes each into a single JPanel.Don't create a new JFrame for each class.
public class Calculator{
JPanel panel;
public Calculator(){
panel = new JPanel();
/*
* Add labels and buttons etc.
*/
panel.add(buttons);
panel.add(labels);
}
//Method to return the JPanel
public JPanel getPanel(){
return panel;
}
}
Then add the panels to your JFrame in your testers class using whatever layout best suits your needs.
public class DemoCalculator {
public static void main(String[] args) {
JPanel cal1,cal2;
JFrame frame = new JFrame("Calculators");
frame.add(cal1 = new Calculator().getPanel(),new BorderLayout().EAST);
frame.add(cal2 = new Calculator2().getPanel(),new BorderLayout().WEST);
frame.setSize(1000,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
}

Java GUI not showing anything

I am new to Java and I am creating a Gui. I don't have any error but when I ran the main nothing is shown.
I can not understand why. Can please someone help?
Here is my code of the GUI:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
public class DartsGUI implements ActionListener {
//Gui components
JFrame mainDartsFrame;
JPanel buttonsPanel,infoPanel;
JRadioButton viewTableAsc,viewTableDesc,editScores,viewDetails,searchById;
CardLayout cLayout;
JTextArea table1,table2;
JScrollPane scrollTable1,scrollTable2;
JLabel edit,details,search;
public void DartGUI() {
mainDartsFrame= new JFrame("Darts Competition");
mainDartsFrame.setSize(700, 500);
mainDartsFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainDartsFrame.setLayout(new BorderLayout());
mainDartsFrame.setLocationRelativeTo(null);
createButtonsPanel();
createInfoPanel();
mainDartsFrame.setVisible(true);
}
private void createButtonsPanel() {
JPanel buttonsPanel = new JPanel( new GridLayout(5,1) );
viewTableAsc= new JRadioButton("Info Ascending Order");
viewTableAsc.addActionListener(this);
viewTableDesc= new JRadioButton("Info Descending Order");
viewTableDesc.addActionListener(this);
editScores= new JRadioButton("Edit Scores");
editScores.addActionListener(this);
viewDetails= new JRadioButton("View Details");
viewDetails.addActionListener(this);
searchById=new JRadioButton("Search Competitor");
searchById.addActionListener(this);
//Group radio buttons to ensure only one is chosen each time
ButtonGroup radioButtons = new ButtonGroup();
radioButtons.add(searchById);
radioButtons.add(viewTableAsc);
radioButtons.add(viewTableDesc);
radioButtons.add(editScores);
radioButtons.add(viewDetails);
//Push buttons into the buttons Panel
buttonsPanel.add(viewTableAsc);
buttonsPanel.add(viewTableDesc);
buttonsPanel.add(editScores);
buttonsPanel.add(viewDetails);
buttonsPanel.add(searchById);
mainDartsFrame.add(buttonsPanel,BorderLayout.WEST);
}
private void createInfoPanel() {
infoPanel = new JPanel();
cLayout = new CardLayout();
infoPanel.setLayout(cLayout);
table1 = new JTextArea(10,10);
table1.setEditable(false);
scrollTable1 = new JScrollPane(table1);
table2 = new JTextArea(10,10);
table2.setEditable(false);
scrollTable2 = new JScrollPane(table1);
edit = new JLabel("Edit Scores");
search= new JLabel("Search Id");
details=new JLabel("View Details");
infoPanel.add(scrollTable1, "viewTable1");
infoPanel.add(scrollTable2, "viewTable2");
infoPanel.add(edit, "edit");
infoPanel.add(search, "searchId");
infoPanel.add(details, "viewDetails");
mainDartsFrame.add(infoPanel,BorderLayout.CENTER);
}
public void actionPerformed (ActionEvent e) {
JRadioButton eventButton = (JRadioButton) e.getSource();
if(eventButton==viewTableAsc){
cLayout.show(infoPanel,"viewTable1");
}
else if(eventButton==viewTableDesc){
cLayout.show(infoPanel, "viewTable2");
}
else if(eventButton==editScores){
cLayout.show(infoPanel, "edit");
}
else if(eventButton==viewDetails){
cLayout.show(infoPanel, "viewDetails");
}
else{
cLayout.show(infoPanel, "searchId");
}
}
}
And the main class:
public class mainGui {
public static void main(String[] args) {
DartsGUI gui = new DartsGUI();
}
}
You need to call the DartGUI method:
public static void main(String[] args) {
DartsGUI gui = new DartsGUI();
gui.DartGUI();
}
You are using a method instead of constructor.
Here's how your code should be:
public class DartsGUI implements ActionListener {
//Gui components
JFrame mainDartsFrame;
JPanel buttonsPanel,infoPanel;
JRadioButton viewTableAsc,viewTableDesc,editScores,viewDetails,searchById;
CardLayout cLayout;
JTextArea table1,table2;
JScrollPane scrollTable1,scrollTable2;
JLabel edit,details,search;
public DartGUI(){
mainDartsFrame= new JFrame("Darts Competition");
mainDartsFrame.setSize(700, 500);
mainDartsFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainDartsFrame.setLayout(new BorderLayout());
mainDartsFrame.setLocationRelativeTo(null);
createButtonsPanel();
createInfoPanel();
mainDartsFrame.setVisible(true);
}
private void createButtonsPanel(){
JPanel buttonsPanel = new JPanel( new GridLayout(5,1) );
viewTableAsc= new JRadioButton("Info Ascending Order");
viewTableAsc.addActionListener(this);
viewTableDesc= new JRadioButton("Info Descending Order");
viewTableDesc.addActionListener(this);
editScores= new JRadioButton("Edit Scores");
editScores.addActionListener(this);
viewDetails= new JRadioButton("View Details");
viewDetails.addActionListener(this);
searchById=new JRadioButton("Search Competitor");
searchById.addActionListener(this);
//Group radio buttons to ensure only one is chosen each time
ButtonGroup radioButtons = new ButtonGroup();
radioButtons.add(searchById);
radioButtons.add(viewTableAsc);
radioButtons.add(viewTableDesc);
radioButtons.add(editScores);
radioButtons.add(viewDetails);
//Push buttons into the buttons Panel
buttonsPanel.add(viewTableAsc);
buttonsPanel.add(viewTableDesc);
buttonsPanel.add(editScores);
buttonsPanel.add(viewDetails);
buttonsPanel.add(searchById);
mainDartsFrame.add(buttonsPanel,BorderLayout.WEST);
}
private void createInfoPanel(){
infoPanel = new JPanel();
cLayout = new CardLayout();
infoPanel.setLayout(cLayout);
table1 = new JTextArea(10,10);
table1.setEditable(false);
scrollTable1 = new JScrollPane(table1);
table2 = new JTextArea(10,10);
table2.setEditable(false);
scrollTable2 = new JScrollPane(table1);
edit = new JLabel("Edit Scores");
search= new JLabel("Search Id");
details=new JLabel("View Details");
infoPanel.add(scrollTable1, "viewTable1");
infoPanel.add(scrollTable2, "viewTable2");
infoPanel.add(edit, "edit");
infoPanel.add(search, "searchId");
infoPanel.add(details, "viewDetails");
mainDartsFrame.add(infoPanel,BorderLayout.CENTER);
}
public void actionPerformed (ActionEvent e){
JRadioButton eventButton = (JRadioButton) e.getSource();
if(eventButton==viewTableAsc){
cLayout.show(infoPanel,"viewTable1");
}
else if(eventButton==viewTableDesc){
cLayout.show(infoPanel, "viewTable2");
}
else if(eventButton==editScores){
cLayout.show(infoPanel, "edit");
}
else if(eventButton==viewDetails){
cLayout.show(infoPanel, "viewDetails");
}
else{
cLayout.show(infoPanel, "searchId");
}
}
}

Moving method after JButton selection

When I select the first option and hit select the JFrame stays as is and I want it to close and move into the next method being called and open a different JFrame. Can anyone see the problem? I can't figure out where I am going wrong
public class GUI extends JFrame
{
public static void main(String args [])
{
final JFrame frame = new JFrame("Choose an option");
frame.setSize(350, 180);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1, 0, 0));
final JRadioButton sb = new JRadioButton("Student");
final JRadioButton lb = new JRadioButton("Lecturer");
final JRadioButton cdb = new JRadioButton("Course Director");
final JRadioButton ab = new JRadioButton("Admin");
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(sb);
buttonGroup.add(lb);
buttonGroup.add(cdb);
buttonGroup.add(ab);
JPanel panel = new JPanel();
panel.add(sb);
panel.add(lb);
panel.add(cdb);
panel.add(ab);
frame.getContentPane().add(panel);
panel.setLayout(new GridLayout(0, 1, 0, 0));
JButton select = new JButton("Select");
JButton cancel = new JButton("Cancel");
select.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if(sb.isSelected())
{
frame.dispose();
StudentGUI();
}
else if(lb.isSelected())
System.out.println("Lecturer");
else if(cdb.isSelected())
System.out.println("Course Director");
else if(ab.isSelected())
System.out.println("Admin");
}
});
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
JPanel panel2 = new JPanel();
panel2.add(select);
panel2.add(cancel);
panel2.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 0));
frame.getContentPane().add(panel2);
frame.setVisible(true);
}
public static void StudentGUI()
{
JFrame frame1 = new JFrame("Input Username");
frame1.setSize(350, 180);
frame1.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
JTextField tf = new JTextField("Input username here");
JButton submit = new JButton("Submit");
JPanel panel1 = new JPanel();
panel1.add(tf);
panel1.add(submit);
frame1.getContentPane().add(panel1);
}
You forgot to set frame1.setVisible(true); in your StudentGUI method, and you never close the window in the first method (use yourframe.dispose()).
So try:
public void actionPerformed(ActionEvent e)
{
if(sb.isSelected())
StudentGUI();
else if(lb.isSelected())
System.out.println("Lecturer");
else if(cdb.isSelected())
System.out.println("Course Director");
else if(ab.isSelected())
System.out.println("Admin");
yourframe.dispose();//don't know your frame variable
}
public static void StudentGUI()
{
JFrame frame1 = new JFrame("Input Username");
frame1.setSize(350, 180);
frame1.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
//code omitted
}

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