i created two classes one class is just like form the other class is main class and having jmenu and jinternal frames i want to print the input from the form class on the jinternal frame but i cannot understand how i recall the jinternalframe in the form classes, please guide me in this regard or any hint or some piece of code or tutorial that can help me here is code of both the classes. Moreover both classes are working fine .
JTextArea text;
static int openFrameCount = 0;
public form(){
super("Insert Form");
Container panel=getContentPane();
JPanel cc = new JPanel();
cc.setLayout(new FlowLayout());
JButton b=new JButton("print");
b.setPreferredSize(new Dimension(140,50));
b.setBounds(1000,500,350,50);
cc.add(b);
.......................................................
JLabel label1=new JLabel(" Question"+(++openFrameCount));
cc.add(label1);
text=new JTextArea();
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setPreferredSize(new Dimension(750,50));
text.setBounds(80, 60,750,50);
cc.add(text);
JLabel symbol=new JLabel("Selection for Option?");
symbol.setBounds(200, 120,1000,100);
cc.add(symbol);
..................................................
JLabel op4=new JLabel("4th Option?");
JTextArea otext4=new JTextArea();
otext4.setLineWrap(true);
otext4.setWrapStyleWord(true);
otext4.setPreferredSize(new Dimension(750,50));
otext4.setBounds(10, 40,700,30);
cc.add( op4 ) ;
cc.add( otext4 ) ;
cc.revalidate();
validate();
............................................................
}
#Override
public void actionPerformed(ActionEvent ae) {
if ( e.getSource() == b1 ){
}
}
}
and the second class of jinternalframe is
public class Desktop1 extends JFrame
implements ActionListener {
Desktop p=new Desktop();
JDesktopPane desktop;
static int openFrameCount = 0;
public Desktop1() {
super("InternalFrameDemo");
//Make the big window be indented 50 pixels from each edge
//of the screen.
int inset = 50;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(inset, inset,
screenSize.width - inset*2,
screenSize.height - inset*2);
//Set up the GUI.
desktop = new JDesktopPane(); //a specialized layered pane
createFrame(); //create first "window"
setContentPane(desktop);
setJMenuBar(createMenuBar());
//Make dragging a little faster but perhaps uglier.
desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
}
protected JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
//Set up the lone menu.
.................................................
return menuBar;
}
//React to menu selections.
public void actionPerformed(ActionEvent e) {
if ("new".equals(e.getActionCommand())) { //new
createFrame();
}
............................................
}
}
class MyInternalFrame extends JInternalFrame {
static final int xPosition = 30, yPosition = 30;
public MyInternalFrame() {
super("IFrame #" + (++openFrameCount), true, // resizable
true, // closable
true, // maximizable
true);// iconifiable
setSize(700, 700);
// Set the window's location.
setLocation(xPosition * openFrameCount, yPosition
* openFrameCount);
}
}
//Create a new internal frame.
protected void createFrame() {
Desktop1.MyInternalFrame frame = new Desktop1.MyInternalFrame();
JPanel panel=new JPanel();//to add scrollbar in jinternalpane insert jpanel
panel.setBackground(Color.white);//set background color of jinternal frame
JScrollPane scrollBar=new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
frame.add(scrollBar);
frame.setVisible(true);
desktop.add(frame);
try {
frame.setSelected(true);
frame.setMaximum(true);
} catch (java.beans.PropertyVetoException e) {}
}
public static void main(String[] args) {
Desktop1 d=new Desktop1();
d.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
d.setVisible(true);
}
}
i want to know hint about the work that come in this part of code to pass the value of form to internal frame when i click on print button
public void actionPerformed(ActionEvent ae) {
if ( e.getSource() == b1 ){
}
}
}
just call the constructor and pass the value
ClassName(parameter)
I guess you want to pass some text to your InternalFrame class on the button click from the main form.
Modify your createFrame() method to accept a String value
e.g-
protected void createFrame(String value){
//..your code
}
and when you call your InternalFrame class, pass this value to its constructor. e.g-
Desktop1.MyInternalFrame frame = new Desktop1.MyInternalFrame(value);
Parameterised constructor will solve your problem. Modify your InternalFrame constructor
e.g-
public MyInternalFrame(String value){
//..use this value
}
Related
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 ();
}
}
I have MDI project. I add the customer JPanel in the JInternalFrame. My customer JPanel has a public method to change some component background color. When the button on the JFrame is clicked, I want it to change the label or text on my customer JPanel for all InternalFrame. How can I call the method? Thanks in advance
The following code is the action for the button on JFrame
private void categoryAction(ActionEvent e){
try{
JButton b=(JButton)e.getSource();
Color c=b.getBackground();
JInternalFrame[] allframes = desktop.getAllFrames();
int count = allframes.length;
for (int i=0; i<allframes.length-1; i++){
//call the method on the PDFJPanel
}
}
catch(Exception err){
Utility.DisplayErrorMsg(err.toString());
}
The following code is add the internal frame into the desktop
private void AddNote(File file){
JInternalFrame internalFrame = new JInternalFrame("PDFAnnotation"
+ file.getName(), true, true, true, true);
internalFrame.setBounds(0, 0, 600, 100);
desktop.add(internalFrame);
PDFJPanel p=new PDFJPanel(file);
internalFrame.add(p, BorderLayout.CENTER);
internalFrame.setVisible(true);
try {
internalFrame.setSelected(true);
}
catch (java.beans.PropertyVetoException e) {}
this.add(desktop, BorderLayout.CENTER);
//resize the internal frame as full screen
Dimension size = desktop.getSize();
int w = size.width ;
int h = size.height ;
int x=0;
int y=0;
desktop.getDesktopManager().resizeFrame(internalFrame, x, y, w, h);
}
There is the method on my customer JPanel
Public void setDefaultColor(Color c){
//change the label and textbox color
}
You can utilize JDesktopPane.getSelectedFrame that returns currently active frame. You can retrieve PDFJPanel from the layout manager, ie using BorderLayout.getLayoutComponent(). Or easier and cleaner, you can extend JInternalFrame, ie:
class PDFFrame extends JInternalFrame {
private PDFJPanel panel;
public PDFFrame(File file) {
panel = new PDFJPanel(file);
add(panel, BorderLayout.CENTER);
}
public void setDefaultColor(Color c){
panel.setDefaultColor();
}
}
Then, access it:
JDesktopPane desktop = ...;
PDFFrame frame = (PDFFrame) desktop.getSelectedFrame();
frame.setDefaultColor(Color.BLUE);
The title of this quesiton speaks for itself. I am making a clone of minesweeper using a JFrame and have just finished the starting screen where the player selects a game size. When a button is clicked, the Frame is supposed to clear ready for the game screen. When I click a button, the button remains in the "pressed" state and the JFrame freezes and I have to close it down. What am I doing wrong?
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Minesweeper extends JFrame implements ActionListener{
JLabel starttitle;
ButtonObject[] gamefield;
JFrame frame;
JPanel startscreen;
JPanel gamescreen;
int gamesize;
JButton ten;
JButton tfive;
JButton fifty;
GridLayout layout;
public Minesweeper()
{
frame = new JFrame("Minesweeper");
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);;
startscreen = new JPanel();
startScreen();
}
public void startScreen()
{
ten = new JButton("10 x 10");
tfive = new JButton("25 x 25");
fifty = new JButton("50 x 50");
starttitle = new JLabel("Welcome to minesweeper. Click a game size to begin.");
frame.add(startscreen);
startscreen.add(starttitle);
startscreen.add(ten);
startscreen.add(tfive);
startscreen.add(fifty);
ten.addActionListener(this);
tfive.addActionListener(this);
fifty.addActionListener(this);
}
public void gameScreen()
{
frame.getContentPane().removeAll();//freezes JFrame
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==ten)
{
gamesize = 10;
gameScreen();
}
else if(e.getSource()==tfive)
{
gamesize = 25;
gameScreen();
}
else if(e.getSource()==fifty)
{
gamesize = 50;
gameScreen();
}
else
{
System.out.println("Fatal error");
}
}
public static void main(String[] args)
{
new Minesweeper();
}
}
It doesn't freeze, call repaint() method of your frame, and all components will be clear.
just add next line in your actionPerformed():
frame.repaint();
just like this..
public void gameScreen()
{
frame.getContentPane().removeAll();
frame.repaint();
}
JFrame's default LayoutManager is Borderlayout
all changes to the already visible Swing GUI (add, remove, resize, modify) must propertly to notify used LayoutManager
standard notifier for JFrame is frame.(re*)validate and frame.repaint()**,
*- in Java7 and newer versions
** - not required in all cases(for JTextComponents, JFrame.pack(), e.i.), by default is better to use this code line too
I'm trying to create a board for a game, i first made a frame then if the user //enters the rows and columns as numbers and pushes the start button, it should remove all //whats on frame and add a panel with a grid layout having buttons everywhere
Here is the code ( Problem is the frame gets cleared and nothing appears)
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Frame extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
JButton newButton;
JButton Start;
JTextArea row;
JTextArea col;
JLabel background;
JLabel rows;
JLabel columns;
JLabel Error;
JPanel myPanel;
JCheckBox box;
public Frame()
{
//adding frame
setTitle("DVONN Game");
setSize(1000, 700);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
//making start button
Start = new JButton(new ImageIcon("Start"));
Start.setBounds(500, 30, 300, 300);
Start.setOpaque(true);
Start.addActionListener(this);
//make background
background = new JLabel();
background.setBounds(0, -300, 2000, 1500);
background.setIcon(Color.BLUE));
rows = new JLabel("Enter the rows");
columns = new JLabel("Enter the columns");
rows.setForeground(Color.WHITE);
columns.setForeground(Color.WHITE);
rows.setBounds(10,10,100,30);
columns.setBounds(10,45,105,30);
row = new JTextArea();
col = new JTextArea();
row.setBounds(120,10,100,30);
col.setBounds(120,45,100,30);
Error = new JLabel("Enter numbers plz!");
Error.setBounds(10, 100, 400, 30);
Error.setForeground(Color.RED);
Error.setVisible(true);
box = new JCheckBox("Enable Random Filling");
box.setBounds(10, 200, 150, 20);
box.setVisible(true);
myPanel = new JPanel();
myPanel.setBounds(30, 30, 700, 500);
myPanel.setVisible(true);
newButton = new JButton();
newButton.setOpaque(true);
getContentPane().add(box);
getContentPane().add(rows);
getContentPane().add(columns);
getContentPane().add(row);
getContentPane().add(col);
getContentPane().add(Start);
getContentPane().add(background);
this.validate();
this.repaint();
}
public static void main(String[]args)
{
new Frame();
}
//adding actions for start button
public void actionPerformed(ActionEvent e) {
boolean flag = true;
String r1 = row.getText();
String c1 = col.getText();
int x = 0,y = 0;
try{
x = Integer.parseInt(r1);
y = Integer.parseInt(c1);
} catch(NumberFormatException l) {
flag = false;
}
int size = x * y;
if (flag == true) {
this.getContentPane().removeAll();
this.validate();
this.repaint();
myPanel.setLayout(new GridLayout(x, y));
while(size != 0)
{
myPanel.add(newButton);
size --;
}
this.getContentPane().add(myPanel);
} else {
this.getContentPane().add(Error);
}
}
}
There are several issues with this code
Is it really needed to post that much code. A simple UI with one button to press, and then another component which should appear would be sufficient for an SSCCE
The use of null layout's. Please learn to use LayoutManagers
Each Swing component can only be contained once in the hierarchy. So this loop is useless since you add the same component over and over again (not to mention that a negative size would result in an endless loop)
while(size != 0){
myPanel.add(newButton);
size --;
}
Have you tried debugging to see whether size is actually >0. Since you silently ignore ParseExceptions you might end up with a size of 0 which will clean the content pane and add nothing
Then do as goldilocks suggests and call validate after adding the components. See the javadoc of the Container#add method
This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to display the added component.
Call validate() and repaint() after the new elements have been added instead of after the old ones have been removed.
You don't need to be calling setVisible() on individual components, call it after pack() on the Frame itself, and you shouldn't use validate() and repaint() in the constructor. Ie, replace those with:
pack();
setVisible(true);
or you can do that on the object after the constructor is called.
Try to replace
public static void main(String[]args)
{
new Frame();
}
by
public static void main(String[]args)
{
new Frame().setVisible(true);
}
Remove the call to this.setVisible in the constructor and make this your main method.
public static void main(String[] args) {
final Frame fr = new Frame();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
fr.setVisible(true);
}
});
}
This will make sure that the frame elements will be in place before it becomes visible.
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;