Using multiple classes with the same JFrame - java

I've been in a bit of a pickle here. I've been ripping my hair out over how to accomplish such a task. For my International Bacc I have to fill out certain criteria for my Program dossier and one of them is using inheritance and passing parameters etc. I'm in the stage of making my prototype and wanted to achieve the effect of using multiple JPanels within the same JFrame. I've achieved this rather crudely with setVisivble() and adding both panels to the JFrame. I understand that I can use the CardLayout for this and will probably implement it as soon as possible.
All in all what I'm trying to achieve is that I have a login button the loads the other jpanel, is there a way of doing this in separate classes? Because when I seem to use the myframe.add(new mypanelClass()) it creates an entirely new JFrame! Essentially the miniclass I have in this file I want to separate out into another class. Also how can I make a logout button on the other panel bring me back to the login screen from another class? Thanks in advance for any help.
Here's my code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.util.*;
class Menu extends JFrame
{
JFrame container = new JFrame();
JPanel screen = new JPanel();
JPanel screenBase = new JPanel();
Image ProgramIcon = Toolkit.getDefaultToolkit().getImage("imageIco.png");
ImageIcon logo = new ImageIcon ("Logo.png");
JLabel icon = new JLabel(logo);
JLabel username = new JLabel("Username");
JLabel password = new JLabel("Password");
JTextField user = new JTextField(18);
JPasswordField pass = new JPasswordField(18);
JButton login = new JButton("Login");
JLabel errorInfo = new JLabel("");
int WIDTH = 800;
int HEIGHT = 500;
JPanel screen2 = new JPanel();
JButton logout = new JButton("Logout");
ImageIcon title = new ImageIcon("title.png");
JLabel header = new JLabel(title);
public static void main(String[] args)
{
try {UIManager.setLookAndFeel("com.nilo.plaf.nimrod.NimRODLookAndFeel");}
catch (UnsupportedLookAndFeelException e){ JOptionPane.showMessageDialog(null, "GUI Load Error: Unsupported");}
catch (ClassNotFoundException e) { JOptionPane.showMessageDialog(null, "GUI Load Error: NimROD Missing");}
catch (InstantiationException e) { JOptionPane.showMessageDialog(null, "GUI Load Error: Instantiation Missing");}
catch (IllegalAccessException e) { JOptionPane.showMessageDialog(null, "GUI Load Error: Illegal Access"); }
Menu admin = new Menu();
}
public Menu()
{
container.setIconImage(ProgramIcon);
container.setTitle("Login");
container.setSize(WIDTH,HEIGHT);
container.setResizable(false);
container.setVisible(true);
container.add(screen);
container.setDefaultCloseOperation(EXIT_ON_CLOSE);
screen.add(username);
screen.add(password);
screen.add(user);
screen.add(pass);
screen.add(login);
screen.add(icon);
screen.setLayout(null);
Dimension iconSize = icon.getPreferredSize();
Dimension usernameSize = username.getPreferredSize();
Dimension passwordSize = password.getPreferredSize();
Dimension loginSize = login.getPreferredSize();
Dimension userSize = user.getPreferredSize();
Dimension passSize = pass.getPreferredSize();
username.setBounds(252,170,usernameSize.width,usernameSize.height);
password.setBounds(495,170,passwordSize.width,passwordSize.height);
user.setBounds(180,200,userSize.width,userSize.height);
pass.setBounds(420,200,passSize.width,passSize.height);
login.setBounds(375,250,loginSize.width,loginSize.height);
icon.setBounds(250,50,iconSize.width,iconSize.height);
ButtonHandler handle = new ButtonHandler();
login.addActionListener(handle);
new BaseScreen();
}
public class BaseScreen
{
public BaseScreen()
{
container.add(screen2);
screen2.setLayout(null);
screen2.add(logout);
screen2.add(header);
screen2.setVisible(false);
Dimension headerSize = header.getPreferredSize();
Dimension logoutSize = logout.getPreferredSize();
logout.setBounds(720,440,logoutSize.width,logoutSize.height);
header.setBounds(0,0,headerSize.width,headerSize.height);
setDefaultCloseOperation(EXIT_ON_CLOSE);
ButtonHandler handle = new ButtonHandler();
logout.addActionListener(handle);
}
}
public class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == login)
{
if((user.getText().equals("")) && (pass.getText().equals("")))
{
errorInfo.setText("Please enter username and password");
screen.add(errorInfo);
errorInfo.setForeground(Color.RED);
Dimension errorInfoSize = errorInfo.getPreferredSize();
errorInfo.setBounds(300,300,errorInfoSize.width,errorInfoSize.height);
}
if((user.getText().equals("admin"))&&(pass.getText().equals("password")))
{
screen.setVisible(false);
screen2.setVisible(true);
container.setTitle("Menu");
user.setText("");
pass.setText("");
}
}
if (event.getSource() == logout)
{
screen2.setVisible(false);
screen.setVisible(true);
container.setTitle("Login");
}
}
}
}

You'll need to stop instantiating a JFrame within that class that extends JFrame, that's 2 JFrames right there. Write JFrame container = this; then use your IDE's inline feature to inline the container field.
If BaseScreen needs access to the JFrame 'this' you can pass that value into BaseScreen's constructor and BaseScreen can store that value as a field. There's no magic 'linking the classes together', you tell one object about another one by passing values around. If what I'm saying is unfamiliar you'll need to visit the constructors section of the Java tutorial - http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

Related

How can I transfer values of an int and string from one program to another in Java

Ok so In my code I'm asking the user for their name and asking them to click one of 3 buttons which gives a variable a corresponding value. Now in another program I want to call upon this program and then pretty much display the string and use the int value for a certain purpose.
public class MainMenuofgame extends JFrame implements ActionListener{
JButton slow, medium, fast;
JLabel pic1, pic2, pic3, pic4;
JTextField username;
Container frame;
static String name;
static int xspeed = 0;
public MainMenuofgame() {
super ("Main Menu of Rocket Launch");
frame = getContentPane ();
frame.setLayout (null);
pic1 = new JLabel (new ImageIcon ("welcome.png"));
pic2 = new JLabel (new ImageIcon ("name.png"));
pic3 = new JLabel (new ImageIcon ("speed.png"));
pic4 = new JLabel (new ImageIcon ("backgnd.jpg"));
username = new JTextField ();
slow = new JButton("Slow");
// slow.setActionCommand("slowspeed");
slow.addActionListener (this);
medium = new JButton("Medium");
// medium.setActionCommand("mediumspeed");
medium.addActionListener (this);
fast = new JButton("Fast");
// fast.setActionCommand("fastspeed");
fast.addActionListener (this);
pic1.setBounds (30,50, 525, 173);//welcome
pic2.setBounds (100,230,212,73);//name
pic3.setBounds (80,350,428,84);//speed
username.setBounds(310,255,150,30);
slow.setBounds (100,450,100,100);
medium.setBounds (250,450,100,100);
fast.setBounds (400,450,100,100);
//background bound goes in the end
pic4.setBounds (0,0, 600,900);
frame.add (pic1);
frame.add (pic2);
frame.add (pic3);
frame.add (username);
frame.add (slow);
frame.add (medium);
frame.add (fast);
frame.add (pic4);
setSize(600, 900);
setVisible (true);
setDefaultCloseOperation (EXIT_ON_CLOSE);
}
public void actionPerformed (ActionEvent evt){
String name = username.getText();
if (evt.getSource () == slow)
{
xspeed = 1;
}
else if(evt.getSource () == medium)
{
xspeed = 5;
}
else
{
xspeed = 10;
}
}
public static void main(String[] args) {
new MainMenuofgame ();
}
}
The behavior that you describe is not in fact the "transfer values of an int and string from one program to another in Java", but rather much more simply the transfer of data from one object to another, here the objects are represented by GUI components. Don't create two separate programs, but rather create separate objects that interact in a meaningful way. That is the essence of OOPs with Java. The simplest solution is to have the main application display the sub-application's GUI within a modal dialog such as a modal JDialog, and then once the dialog has been dealt with (i.e., is no longer visible) then the main program/object queries the dialog for the state of its components -- the data that was entered.
Also you are painting yourself in a corner by having your class extend JFrame, forcing you to create and display JFrames, when often more flexibility is called for. In fact, I would venture that most of the Swing GUI code that I've created and that I've seen does not extend JFrame, and in fact it is rare that you'll ever want to do this. More commonly your GUI classes will be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding.
For example:
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class MenuDemoMainPanel extends JPanel {
private MenuPanel menuPanel = new MenuPanel();
private JDialog menuDialog = null;
private String name;
private Speed speed;
private JTextField nameField = new JTextField(10);
private JTextField speedField = new JTextField(10);
public MenuDemoMainPanel() {
// these fields are for display only and should not allow user
// interaction
nameField.setFocusable(false);
speedField.setFocusable(false);
// not kosher to set this directly, per kleopatra, but oh well
setPreferredSize(new Dimension(600, 400));
// simple demo GUI -- add components
add(new JLabel("Name:"));
add(nameField);
add(new JLabel("Speed:"));
add(speedField);
add(new JButton(new GetNameAndSpeedAction("Get Name And Speed")));
}
// action for JButton that displays the menuDialog JDialog
private class GetNameAndSpeedAction extends AbstractAction {
public GetNameAndSpeedAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
if (menuDialog == null) {
// if the menu dialog has not been created yet -- create it
Window win = SwingUtilities.getWindowAncestor(MenuDemoMainPanel.this);
menuDialog = new JDialog(win, "Menu", ModalityType.APPLICATION_MODAL);
menuDialog.add(menuPanel);
menuDialog.pack();
menuDialog.setLocationRelativeTo(win);
}
// display the menu JDialog
menuDialog.setVisible(true);
// this code is called only when the dialog is no longer visible
// query the dialog for the state it holds
name = menuPanel.getNameText();
speed = menuPanel.getSpeed();
// and display the state in the main GUI
if (name != null && speed != null) {
nameField.setText(name);
speedField.setText(speed.getText());
}
}
}
private static void createAndShowGui() {
// create the main GUI JPanel
MenuDemoMainPanel mainPanel = new MenuDemoMainPanel();
// then create an application GUI
JFrame frame = new JFrame("Menu Demo -- Main GUI");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel); // place the main panel into the GUI
// and pack and display it:
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
// JPanel to hold menu dialog components
#SuppressWarnings("serial")
class MenuPanel extends JPanel {
private JComboBox<Speed> speedCombo = new JComboBox<>(Speed.values());
private JTextField nameField = new JTextField(10);
public MenuPanel() {
speedCombo.setSelectedIndex(-1);
add(new JLabel("Name:"));
add(nameField);
add(new JLabel("Speed:"));
add(speedCombo);
add(new JButton(new SubmitAction("Submit")));
}
// allow outside classes to query the nameField JTextField's state
public String getNameText() {
return nameField.getText();
}
// allow outside classes to query the speedCombo JComboBox's state
public Speed getSpeed() {
return (Speed) speedCombo.getSelectedItem();
}
// Action for JButton that submits the dialog to the main GUI
private class SubmitAction extends AbstractAction {
public SubmitAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// if the data is not all entered or selected
if (nameField.getText().trim().isEmpty() || speedCombo.getSelectedIndex() == -1) {
Component comp = MenuPanel.this;
String msg = "You must enter your name and select a speed";
String title = "Invalid Data";
int msgType = JOptionPane.ERROR_MESSAGE;
// warn the user and leave this dialog still visible
JOptionPane.showMessageDialog(comp, msg, title, msgType);
} else {
// otherwise dispose of this dialog and thereby pass control
// back to the main application / GUI
Window win = SwingUtilities.getWindowAncestor(MenuPanel.this);
win.dispose();
}
}
}
}
// an enum to encapsulate possible game speeds
enum Speed {
SLOW("Slow"), MEDIUM("Medium"), FAST("Fast");
private String text;
private Speed(String text) {
this.text = text;
}
public String getText() {
return text;
}
#Override
public String toString() {
return getText();
}
}
There are one of two ways that come to mind on how to transfer information from one program to another...
Client-Server applications
This requires you to have a third application running accepting information from each of the other two application (clients) through a socket. For further information Google "Client-Server applications in Java"
Have a text file passing information
To do this you should have a text file that one application stores information in and the other application just simply reads it... This is an easier solution but is less of a learning experience. Here is example code.
Application 1:
private void storeMessage(String msg){
File centralFile = new File("path to your file");
BufferedWriter writer = new BufferedWriter(new FileWriter(centralFile));
writer.write(msg);
writer.close();
}
Application 2:
private String getMessage(){
File centralFile = new File("path to your file");
String msg = "";
BufferedReader reader = new BufferedReader(new FileReader(centralFile));
while (reader.hasNextLine()){
msg += reader.nextLine();
}
reader.close();
return msg;
}
Hope this helps
Um... really all I needed to do was call upon my variable that I wanted to store my data in and then well... store it. This is done in the If statement at the bottom. Thanks everyone for helping but honestly most of your answers rised more questions than answered mine and just confused me but I figured it out so thanks anyways :)
public class MainMenuofgame extends JFrame implements ActionListener{
JButton slow, medium, fast;
JLabel pic1, pic2, pic3, pic4;
JTextField username;
Container frame;
static String name;
static int xspeed = 0;
public MainMenuofgame() {
super ("Main Menu of Rocket Launch");
frame = getContentPane ();
frame.setLayout (null);
pic1 = new JLabel (new ImageIcon ("welcome.png"));
pic2 = new JLabel (new ImageIcon ("name.png"));
pic3 = new JLabel (new ImageIcon ("speed.png"));
pic4 = new JLabel (new ImageIcon ("backgnd.jpg"));
username = new JTextField ();
slow = new JButton("Slow");
// slow.setActionCommand("slowspeed");
slow.addActionListener (this);
medium = new JButton("Medium");
// medium.setActionCommand("mediumspeed");
medium.addActionListener (this);
fast = new JButton("Fast");
// fast.setActionCommand("fastspeed");
fast.addActionListener (this);
pic1.setBounds (30,50, 525, 173);//welcome
pic2.setBounds (100,230,212,73);//name
pic3.setBounds (80,350,428,84);//speed
username.setBounds(310,255,150,30);
slow.setBounds (100,450,100,100);
medium.setBounds (250,450,100,100);
fast.setBounds (400,450,100,100);
//background bound goes in the end
pic4.setBounds (0,0, 600,900);
frame.add (pic1);
frame.add (pic2);
frame.add (pic3);
frame.add (username);
frame.add (slow);
frame.add (medium);
frame.add (fast);
frame.add (pic4);
setSize(600, 900);
setVisible (true);
setDefaultCloseOperation (EXIT_ON_CLOSE);
}
public void actionPerformed (ActionEvent evt){
String name = username.getText();
Rocketlaunch.name = name;
if (evt.getSource () == slow)
{
Rocketlaunch.moveSpeed = 1;
Rocketlaunch.speed = "Slow";
setVisible (false);
}
else if(evt.getSource () == medium)
{
Rocketlaunch.moveSpeed = 5;
Rocketlaunch.speed = "Medium";
setVisible (false);
}
else
{
Rocketlaunch.moveSpeed = 10;
Rocketlaunch.speed = "Fast";
setVisible (false);
}
new Rocketlaunch();
}
public static void main(String[] args) {
new MainMenuofgame ();
}
}

How to display one Jframe at a time? [duplicate]

I'm trying to make a little game that will first show the player a simple login screen where they can enter their name (I will need it later to store their game state info), let them pick a difficulty level etc, and will only show the main game screen once the player has clicked the play button. I'd also like to allow the player to navigate to a (hopefully for them rather large) trophy collection, likewise in what will appear to them to be a new screen.
So far I have a main game window with a grid layout and a game in it that works (Yay for me!). Now I want to add the above functionality.
How do I go about doing this? I don't think I want to go the multiple JFrame route as I only want one icon visible in the taskbar at a time (or would setting their visibility to false effect the icon too?) Do I instead make and destroy layouts or panels or something like that?
What are my options? How can I control what content is being displayed? Especially given my newbie skills?
A simple modal dialog such as a JDialog should work well here. The main GUI which will likely be a JFrame can be invisible when the dialog is called, and then set to visible (assuming that the log-on was successful) once the dialog completes. If the dialog is modal, you'll know exactly when the user has closed the dialog as the code will continue right after the line where you call setVisible(true) on the dialog. Note that the GUI held by a JDialog can be every bit as complex and rich as that held by a JFrame.
Another option is to use one GUI/JFrame but swap views (JPanels) in the main GUI via a CardLayout. This could work quite well and is easy to implement. Check out the CardLayout tutorial for more.
Oh, and welcome to stackoverflow.com!
Here is an example of a Login Dialog as #HovercraftFullOfEels suggested.
Username: stackoverflow Password: stackoverflow
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
public class TestFrame extends JFrame {
private PassWordDialog passDialog;
public TestFrame() {
passDialog = new PassWordDialog(this, true);
passDialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new TestFrame();
frame.getContentPane().setBackground(Color.BLACK);
frame.setTitle("Logged In");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
});
}
}
class PassWordDialog extends JDialog {
private final JLabel jlblUsername = new JLabel("Username");
private final JLabel jlblPassword = new JLabel("Password");
private final JTextField jtfUsername = new JTextField(15);
private final JPasswordField jpfPassword = new JPasswordField();
private final JButton jbtOk = new JButton("Login");
private final JButton jbtCancel = new JButton("Cancel");
private final JLabel jlblStatus = new JLabel(" ");
public PassWordDialog() {
this(null, true);
}
public PassWordDialog(final JFrame parent, boolean modal) {
super(parent, modal);
JPanel p3 = new JPanel(new GridLayout(2, 1));
p3.add(jlblUsername);
p3.add(jlblPassword);
JPanel p4 = new JPanel(new GridLayout(2, 1));
p4.add(jtfUsername);
p4.add(jpfPassword);
JPanel p1 = new JPanel();
p1.add(p3);
p1.add(p4);
JPanel p2 = new JPanel();
p2.add(jbtOk);
p2.add(jbtCancel);
JPanel p5 = new JPanel(new BorderLayout());
p5.add(p2, BorderLayout.CENTER);
p5.add(jlblStatus, BorderLayout.NORTH);
jlblStatus.setForeground(Color.RED);
jlblStatus.setHorizontalAlignment(SwingConstants.CENTER);
setLayout(new BorderLayout());
add(p1, BorderLayout.CENTER);
add(p5, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
jbtOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (Arrays.equals("stackoverflow".toCharArray(), jpfPassword.getPassword())
&& "stackoverflow".equals(jtfUsername.getText())) {
parent.setVisible(true);
setVisible(false);
} else {
jlblStatus.setText("Invalid username or password");
}
}
});
jbtCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
parent.dispose();
System.exit(0);
}
});
}
}
I suggest you insert the following code:
JFrame f = new JFrame();
JTextField text = new JTextField(15); //the 15 sets the size of the text field
JPanel p = new JPanel();
JButton b = new JButton("Login");
f.add(p); //so you can add more stuff to the JFrame
f.setSize(250,150);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Insert that when you want to add the stuff in. Next we will add all the stuff to the JPanel:
p.add(text);
p.add(b);
Now we add the ActionListeners to make the JButtons to work:
b.addActionListener(this);
public void actionPerforemed(ActionEvent e)
{
//Get the text of the JTextField
String TEXT = text.getText();
}
Don't forget to import the following if you haven't already:
import java.awt.event*;
import java.awt.*; //Just in case we need it
import java.x.swing.*;
I hope everything i said makes sense, because sometimes i don't (especially when I'm talking coding/Java) All the importing (if you didn't know) goes at the top of your code.
Instead of adding the game directly to JFrame, you can add your content to JPanel (let's call it GamePanel) and add this panel to the frame. Do the same thing for login screen: add all content to JPanel (LoginPanel) and add it to frame. When your game will start, you should do the following:
Add LoginPanel to frame
Get user input and load it's details
Add GamePanel and destroy LoginPanel (since it will be quite fast to re-create new one, so you don't need to keep it memory).

using listeners with both list and button

Very new to Java, but I am slowly picking my way through things. So please be kind. I understand most things I've tried so far, and built a version of the following that uses console output, but now I'm trying to make a GUI. I tried the netbeans GUI maker, but it created so much new code that when I tried to pick through it, I got lost. I'm much better at learning by piecing new things together myself, not having an IDE generate a ton of code and then attempt to find where I want to work.
I am trying to build an window that has a list with three choices on the left side, a button in the middle that confirms your choice, and an answer output on the right. Once the button is pressed, the input from the list is read and is converted into a corresponding answer. As of right now, all I get is "We recommend... null" after selecting an option in the list. The button appears to do nothing at the moment.
I have used tutorials, hacked up others' code from online, and referenced a few books, but I'm stuck.
Here is what I have:
package diffguidegui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class DiffGuideGUI extends JPanel implements ListSelectionListener {
private JList resultsTabList;
private DefaultListModel listModel;
private static final String recommendString = "Recommend a Option";
private JButton recommendButton;
private String recommendOutput;
final JLabel output = new JLabel("We recommend..." + recommendOutput);
//build list
public DiffGuideGUI () {
super(new BorderLayout());
listModel = new DefaultListModel();
listModel.addElement("A");
listModel.addElement("B");
//create the list and put it in the scroll pane
resultsTabList = new JList(listModel);
resultsTabList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
resultsTabList.setSelectedIndex(0);
//listener for user input
resultsTabList.addListSelectionListener(this);
resultsTabList.setVisibleRowCount(2);
JScrollPane listScrollPane = new JScrollPane(resultsTabList);
//build the button at the bottom to fire overall behavior
recommendButton = new JButton(recommendString);
recommendButton.setActionCommand(recommendString);
recommendButton.addActionListener(new RecommendListener());
//create a panel that uses Boxlayout for the button
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.add(recommendButton);
//create a panel that uses Boxlayout for the label
JPanel outputPane = new JPanel();
outputPane.setLayout(new BoxLayout(outputPane, BoxLayout.LINE_AXIS));
outputPane.add(output);
add(listScrollPane, BorderLayout.WEST);
add(buttonPane, BorderLayout.CENTER);
add(outputPane, BorderLayout.EAST);
}
//build listener class
class RecommendListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//build in logic for choice made here
String resultsTabChoice;
resultsTabChoice = (String)resultsTabList.getSelectedValue();
if( resultsTabChoice.equals("A")) {
recommendOutput = "One";}
else {recommendOutput = "Two";}
}
}
public void valueChanged(ListSelectionEvent e) {
if(e.getValueIsAdjusting() == false) {
if(resultsTabList.getSelectedIndex() == -1) {
recommendButton.setEnabled(false);
} else {
recommendButton.setEnabled(true);
}
}
}
//Create GUI and show it
private static void createAndShowGUI() {
JFrame frame = new JFrame("Recommend Window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//create and set up content pane
JComponent newContentPane = new DiffGuideGUI();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
//display the window
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
The button appears to do nothing at the moment.
It does something. It calculates the value for your recommendOutput varable. But you never output this value.
try the following:
//build listener class
class RecommendListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//build in logic for choice made here
String resultsTabChoice;
resultsTabChoice = (String)resultsTabList.getSelectedValue();
if( resultsTabChoice.equals("A")) {
recommendOutput = "One";}
else {recommendOutput = "Two";}
System.out.println(recommendOutput); // <-###################
}
}
This should print the value to stdout
To put the value into your label try this instead:
output.setText(recommendOutput);
where do you set the text for the JLabel? It says "We recommend NULL" because recommenedOutput is null when the object is created. I dont see
output.setText("We recommend "+value) anywhere. You probably need output.invalidate() also. Try putting setText(String text)/invalidate() in the RecommendListener.actionPerformed() method.
output.setText("We recommend A");
output.invalidate();

Change cards with a JButton from another class

I'm getting there step by step but have come across yet another hurdle.
The title is pretty self-explanatory, what I'm wondering is how would I be able to use the JButton "logout" with ActionListener to be able to swap the card in my main LoginScreen.class?
I've had a few whacks but to no avail. Also any tips on improving my coding and format are welcome. Thanks in advance.
Here's my code:
LoginScreen.class
/*Login Screen class for allowing
multiple levels of access and security*/
//Imports library files
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.util.*;
//Creates a LoginScreen class that extends the JFrame library class
class LoginScreen extends JFrame {
//Creates a swing components and CardLayout for organising JPanels
JPanel cardScreen;
JPanel screen = new JPanel();
Image ProgramIcon = Toolkit.getDefaultToolkit().getImage("imageIco.png");
ImageIcon logo = new ImageIcon ("Logo.png");
JLabel icon = new JLabel(logo);
JLabel username = new JLabel("Username");
JLabel password = new JLabel("Password");
JTextField user = new JTextField(18);
JPasswordField pass = new JPasswordField(18);
JButton login = new JButton("Login");
JLabel errorInfo = new JLabel("");
int WIDTH = 800;
int HEIGHT = 500;
int currentPanel = 1;
public static void main(String[] args){
//Sets the GUI (Look and Feel) to the NimROD theme
try {UIManager.setLookAndFeel("com.nilo.plaf.nimrod.NimRODLookAndFeel");}
catch (UnsupportedLookAndFeelException e){ JOptionPane.showMessageDialog(null, "GUI Load Error: Unsupported");}
catch (ClassNotFoundException e) { JOptionPane.showMessageDialog(null, "GUI Load Error: NimROD Missing");}
catch (InstantiationException e) { JOptionPane.showMessageDialog(null, "GUI Load Error: Instantiation Missing");}
catch (IllegalAccessException e) { JOptionPane.showMessageDialog(null, "GUI Load Error: Illegal Access"); }
//Creates a new LoginScreen via the LoginScreen method
LoginScreen LS = new LoginScreen();
}
public LoginScreen(){
//Adds the JPanel to the JFrame and set the JFrame's properties
//Sets the main JPanel to CardLayout platform and adds other JPanels it
final CardLayout cardL = new CardLayout();
cardScreen = new JPanel();
cardScreen.setLayout(cardL);
cardScreen.add(screen, "1");;
BaseScreen base = new BaseScreen();
cardScreen.add(base, "2");
this.setIconImage(ProgramIcon);
this.setTitle("Login");
this.setSize(WIDTH,HEIGHT);
this.setResizable(false);
this.add(cardScreen);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//Place the components on the JPanel and set their absolute posistions
screen.setLayout(null);
screen.add(username);
screen.add(password);
screen.add(user);
screen.add(pass);
screen.add(login);
screen.add(icon);
Dimension iconSize = icon.getPreferredSize();
Dimension usernameSize = username.getPreferredSize();
Dimension passwordSize = password.getPreferredSize();
Dimension loginSize = login.getPreferredSize();
Dimension userSize = user.getPreferredSize();
Dimension passSize = pass.getPreferredSize();
username.setBounds(252,170,usernameSize.width,usernameSize.height);
password.setBounds(495,170,passwordSize.width,passwordSize.height);
user.setBounds(180,200,userSize.width,userSize.height);
pass.setBounds(420,200,passSize.width,passSize.height);
login.setBounds(375,250,loginSize.width,loginSize.height);
icon.setBounds(250,50,iconSize.width,iconSize.height);
this.setVisible(true);
login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
//Checks if both the user and pass text fields are empty
if((user.getText().equals("")) && (pass.getText().equals(""))){
//Displays an error in the form of a label and adds it to the JPanel
errorInfo.setText("Please enter username and password");
screen.add(errorInfo);
errorInfo.setForeground(Color.RED);
Dimension errorInfoSize = errorInfo.getPreferredSize();
errorInfo.setBounds(300,300,errorInfoSize.width,errorInfoSize.height);
}
if((user.getText().equals("admin"))&&(pass.getText().equals("password"))){
cardL.show(cardScreen,"2");
}
}
});
}
}
BaseScreen.class
//Basescreen class
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class BaseScreen extends JPanel{
JPanel screen = this;
JButton logout = new JButton("Logout");
ImageIcon title = new ImageIcon("title.png");
JLabel header = new JLabel(title);
public BaseScreen(){
screen.setLayout(null);
screen.add(logout);
screen.add(header);
Dimension headerSize = header.getPreferredSize();
Dimension logoutSize = logout.getPreferredSize();
logout.setBounds(720,440,logoutSize.width,logoutSize.height);
header.setBounds(0,0,headerSize.width,headerSize.height);
screen.setVisible(true);
}
}
If your'e wondering why I've gone through all the effort to separate out the JPanel into another class, this is because I want to use my BaseScreen class to be inherited by many other JPanel classes and add each one as a card so being able to use a JButton in one of the classes is vital for the structure of the program to work. Hopefully I haven't gone about this the complete wrong way and won't need an etire rewrite of the program.
-Zalx

Accessing JFrame created in main from actionlistener

I've created a frame (mainframe) for my program in the main class which I want to add and remove panels from in order switch between different screens of my program. The first screen of my program is the login panel which has a start button. When I press the start button I want to switch to the menu frame.
The removeAll method seems to work fine since the login panel disappears, but nothing appears in its place when I use the add, validate and repaint methods. I have tried to refer explicitly to the mainframe in the actionlistener (i.e. mainframe.add(menu)) but it does not recognise the object.
Thanks in advance!
public class Main {
public static JFrame mainframe = new JFrame();
public static void main(String[] args) {
// Create mainframe to add and remove panels from
LoginPanel lp = new LoginPanel();
System.out.println("mainframe created!");
// Set size of mainframe
mainframe.setBounds(0, 0, 500, 500);
mainframe.add(lp);
// Get the size of the screen
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
// Determine the new location of the mainframe
int w = mainframe.getSize().width;
int h = mainframe.getSize().height;
int x = (dim.width-w)/2;
int y = (dim.height-h)/2;
// Move the mainframe
mainframe.setLocation(x, y);
mainframe.setVisible(true);
}
}
This is my login panel class:
public class LoginPanel extends JPanel {
private JTextField usernameField;
private JPasswordField passwordField;
private final Action action = new SwingAction();
/**
* Create the panel.
*/
public LoginPanel() {
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = new String (passwordField.getPassword());
Login login = new Login();
boolean Correct = login.isCorrect(username, password);
**if (Correct == true){
removeAll();
Menu menu = new Menu();
add(menu);
validate();
repaint();
setBounds(0, 0, 500, 500);
System.out.println("Attempted to start menu!");
}**
}
});
btnLogin.setAction(action);
btnLogin.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
}});
}
I want to add and remove panels from in order switch between different screens of my program
Sounds like you should be using a Card Layout.
Define mainframe as a class field:
private JFrame mainframe;

Categories