java - method and passing variable from jInternalFrame to jFrame - java

and I have the following problem.
i am new in java and i am trying to send a variable which is user_id, from JInternalFrame to JFrame.
I can't use constructor because JFrame is the main program activated at startup and containing jDesktoPane
so i was trying to use the methods, however, can't do it (i posted the two methods, both of which I tried but did not work)
Method A)
Code in jFrame (Main_window)
public javax.swing.JTextField getID() {
return jTextField_id;
}
public void setID(javax.swing.JTextField ID)
{
jTextField_id = ID;
}
code in jInternalFrame
Main_window send = new Main_window();
send.getID().setText("123");
Method B)
Code in jFrame (Main_window)
USER_ID is a variable accesible in any place of jFrame
public void setID(String ID)
{
USER_ID = ID;
}
code in jInternalFrame
Main_window send = new Main_window();
send.setID("123");
both method don't change anything but have no errors in compilation
if there is any other way of doing it pls tell me :)
sorry for my language and grammar.
if this help i use Eclipse compilator
this code worked for me, ty for help
public void set_ID(String ID)
{
Test_JF mainWindow = (Test_JF) this.getTopLevelAncestor();;
mainWindow.setID(ID);
}
activated by set_ID("1234");

Try this in your JInternalFrame class:
JFrame mainWindow = (JFrame)this.getTopLevelAncestor();
mainWindow.setID("123");

ok so here is smaller version of my program
"Test_JF" is a main JFrame and "Test_JIF" is a JInternalFrame
here is TestJF
public class Test_JF extends JFrame {
private JPanel contentPane;
private JTextField user_id;
String USER_ID;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test_JF frame = new Test_JF();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test_JF() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 750, 500);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
user_id = new JTextField();
user_id.setBounds(338, 11, 86, 20);
contentPane.add(user_id);
user_id.setColumns(10);
JButton button_user_id = new JButton("fill user id");
button_user_id.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
user_id.setText(USER_ID);
}
});
button_user_id.setBounds(239, 10, 89, 23);
contentPane.add(button_user_id);
JDesktopPane desktopPane = new JDesktopPane();
desktopPane.setBounds(10, 56, 714, 395);
contentPane.add(desktopPane);
addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent arg0) {
Test_JIF Open = new Test_JIF();
desktopPane.add(Open);
Open.show();
}
});
}
public void setID(String ID)
{
USER_ID = ID;
}}
here is TestJIF
public class Test_JIF extends JInternalFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test_JIF frame = new Test_JIF();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test_JIF() {
Test_JF mainWindow = (Test_JF)this.getTopLevelAncestor();
setBounds(100, 100, 328, 199);
getContentPane().setLayout(null);
JButton button_send = new JButton("New button");
button_send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainWindow.setID("123");
}
});
button_send.setBounds(111, 73, 89, 23);
getContentPane().add(button_send);
}}
i clear imports here(on web) so it will be cleaner

Related

Java Swing Class Objects

Question is about the object cont in mainWindow, I cant use it!
I got a Package (View) containing mainWindow and main. In my main I got the code:
package View;
import java.awt.EventQueue;
import Controller.mainController;
public class main {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainWindow view = new mainWindow();
mainController cont = new mainController(view);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
in my mainWindow, I got:
public class mainWindow {
public mainWindow() {
initialize();
}
public void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(SystemColor.control);
frame.setBounds(100, 100, 728, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton ButtonStartGame = new JButton("Start Game");
ButtonStartGame.setToolTipText("Start the game");
ButtonStartGame.setEnabled(false);
ButtonStartGame.setBounds(12, 189, 117, 25);
frame.getContentPane().add(ButtonStartGame);
ButtonStartGame.addActionListener(e->cont.StartGame());
frame.setVisible(true);
}
}

Window not appearing properly after opening with JButton in Java

I have a very strange problem with my java application. I basically click the JButton and the new window I want to open opens but with no content showing. Here is what happens.
If I run the class on its own without using a JButton it runs proberly like so.
Here is the code for the button.
public Create()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 629, 316);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 255, 204));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnBuildData = new JButton("Build Graph");
btnBuildData.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
//CreateTest frame = new CreateTest();
new CreateTest().setVisible(true);
}
});
btnBuildData.setBackground(Color.WHITE);
btnBuildData.setForeground(Color.BLACK);
btnBuildData.setBounds(29, 59, 107, 23);
contentPane.add(btnBuildData);
This is strange to me because I have used this code for other classes and it works as intended. I have tried many different ways to do the same thing but none of them have worked. Here is some code for the frame I am opening with the button.
public class CreateTest extends JFrame {
public CreateTest() {
}
//Create the connection to Neo4j
Driver driver = GraphDatabase.driver( "bolt://localhost", AuthTokens.basic( "*****", "*******" ) );
Session session = driver.session();
StatementResult resultVariable;
Record recordVariable;
//Create variables to manage communication with Neo4j
String resultString = new String();
Query neoQuery = new Query();
private JTextField progressTextField;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new CreateTest().initUI();
}
});
}
protected void initUI()
{
final JFrame frame = new JFrame();
//the form
frame.setTitle(CreateTest.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click here to add data");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
doWork();
}
});
progressTextField = new JTextField(25);
progressTextField.setEditable(false);
frame.getContentPane().add(progressTextField, BorderLayout.NORTH);
frame.getContentPane().add(button, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
protected void doWork() {
SwingWorker<Void, Integer> worker = new SwingWorker<Void, Integer>() {
#Override
protected Void doInBackground() throws Exception {
CreateTest frame = new CreateTest();
}
#Override
protected void process(List<Integer> chunks) {
progressTextField.setText(chunks.get(chunks.size() - 1).toString());
}
#Override
protected void done() {
progressTextField.setText("Success: All Nodes have been added ");
}
};
worker.execute();
}
}
There is a difference between the two windows. One being absolute layout and the other jpanel but I don't think this is the problem. If anyone has any ideas please let me know, any ideas will be appreciated. Thanks.
Your calling an empty constructor with new CreateTest()
public CreateTest() {
}
It does nothing since your code is outside of it.

Closing JFrame with Button

I am currently using Eclipse's drag and Drop feature, I have one application window which comes with JFrame by default and is able to setVisible(false); but my other frames/panel/window I have created with JPanel and with extending JFrame.
Because of extend I am unable to setVisible(false or true); it has no effect at all on the window it still remains true.
My code :
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LibrarianMenu frame = new LibrarianMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public LibrarianMenu() {
setTitle("Librarian");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 385, 230);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
.
.
. so on
Here I am trying to execute my button:
btnLogout.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
LibrarianMenu frame = new LibrarianMenu();
frame.setVisible(false);
}
});
Any solutions for it?
Because you're creating the frame inside the Runnable, its scope is limited to that of the runnable. Try declaring the variable outside of the runnable, then initializing it within the runnable, like so:
private JPanel contentPane;
private LibrarianMenu frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new LibrarianMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Then setvisible to false without declaring a new instance of LibrarianMenu:
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
});
This is happening because every time you press the button you create a new instance of that frame. Here is your code updated :
static LibrarianMenu frame ;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new LibrarianMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
And the logout button event should be like this :
btnLogout.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
});

Open a JFrame into another JFrame

I am creating a program, and I have my main class that works with all the JButtons, but I can't get my second class that calls the first class launch with the buttons. The JFrame will launch, but the buttons won't.
I am using eclipse just for the information.
Here is the code of my main class:
public class Unescapable extends JPanel implements ActionListener
{
private static final long serialVersionUID = 1L;
private static final Font font1 = new Font("FONT", Font.BOLD, 75);
protected JButton b1;
protected JButton b2;
protected JButton b3;
protected JButton b5;
protected JTextField t1;
public Unescapable()
{
t1 = new JTextField("Unescapable");
t1.setText("Unescapable");
t1.setBounds(225, 50, 750, 100);
t1.setForeground(Color.LIGHT_GRAY);
t1.setOpaque(true);
t1.setVisible(true);
t1.setEditable(false);
t1.setBackground(Color.BLACK);
t1.setFont(font1);
b1 = new JButton("Open Window");
b1.setActionCommand("open");
b1.setBackground(Color.GRAY);
b1.setForeground(Color.white);
b1.setOpaque(true);
b1.setBorderPainted(false);
b1.setBounds(280, 200, 390, 40);
b1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b1.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b1.setBackground(Color.GRAY);
}
});
b2 = new JButton("Delete File");
b2.setActionCommand("delete");
b2.setBackground(Color.GRAY);
b2.setForeground(Color.white);
b2.setOpaque(true);
b2.setBorderPainted(false);
b2.setBounds(280, 255, 390, 40);
b2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b2.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b2.setBackground(Color.GRAY);
}
});
b3 = new JButton("Info...");
b3.setActionCommand("info");
b3.setBackground(Color.GRAY);
b3.setForeground(Color.white);
b3.setOpaque(true);
b3.setBorderPainted(false);
b3.setBounds(278, 330, 185, 40);
b3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b3.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b3.setBackground(Color.GRAY);
}
});
b5 = new JButton("Quit Game");
b5.setActionCommand("close");
b5.setBackground(Color.GRAY);
b5.setForeground(Color.white);
b5.setOpaque(true);
b5.setBorderPainted(false);
b5.setBounds(485, 330, 185, 40);
b5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b5.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b5.setBackground(Color.GRAY);
}
});
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b5.addActionListener(this);
b1.setToolTipText("Opens Another JWindow");
b2.setToolTipText("Deletes \"text.txt\"");
b3.setToolTipText("Give's some information.");
add(b1);
add(b2);
add(b3);
add(b5);
add(t1);
System.out.println("Main Window Is Running");
}
public void actionPerformed(ActionEvent e)
{
if ("open".equals(e.getActionCommand()))
{
File f = new File("text.txt");
try
{
PrintWriter out = new PrintWriter(f);
out.println("TheBestMacTutorials");
out.close();
}
catch (Exception e2)
{
}
}
else if ("delete".equals(e.getActionCommand()))
{
File f = new File("text.txt");
f.delete();
}
else if ("info".equals(e.getActionCommand()))
{
InfoBook add = new InfoBook();
add.call();
}
else
{
System.out.println("Window Is Now Closing");
System.exit(0);
}
}
private static void createAndShowGUI()
{
JFrame program = new JFrame("My Program");
program.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Unescapable newContentPane = new Unescapable();
program.setContentPane(newContentPane);
program.setLayout(null);
program.setVisible(true);
program.setLocation(850, 445);
program.setSize(900, 580);
program.setTitle("Unescapable 1.0");
program.setBackground(Color.GREEN);
program.isOpaque();
program.isForegroundSet();
program.getContentPane().setBackground(Color.BLACK);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
The code for the "Info Book":
public class InfoBook extends JFrame
{
private static final long serialVersionUID = 1L;
private static final Font font1 = new Font("FONT", Font.BOLD, 75);
protected JButton b1;
protected JButton b2;
protected JTextField t1;
public InfoBook()
{
b1 = new JButton("Cancel");
b1.setActionCommand("cancel");
b1.setBackground(Color.GRAY);
b1.setForeground(Color.white);
b1.setOpaque(true);
b1.setBorderPainted(false);
b1.setBounds(280, 200, 390, 40);
b1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b1.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b1.setBackground(Color.GRAY);
}
});
b2 = new JButton("More Info");
b2.setBackground(Color.GRAY);
b2.setForeground(Color.WHITE);
b2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b2.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b2.setBackground(Color.GRAY);
}
});
t1 = new JTextField("Info");
t1.setText("Info...");
t1.setBounds(225, 50, 750, 100);
t1.setForeground(Color.LIGHT_GRAY);
t1.setOpaque(true);
t1.setVisible(true);
t1.setEditable(false);
t1.setBackground(Color.BLACK);
t1.setFont(font1);
b1.setToolTipText("Opens Another JWindow");
b2.setToolTipText("Gives More Infomation");
add(b1);
add(b2);
add(t1);
System.out.println("Info is now running");
}
public static void creatAndShowGUI()
{
JFrame frame = new JFrame("Info Panel");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
InfoBook newContentPane = new InfoBook();
frame.setLayout(null);
frame.setVisible(true);
frame.setLocation(850, 445);
frame.setSize(900, 580);
frame.setTitle("Unescapable 1.0");
frame.setBackground(Color.GREEN);
frame.isOpaque();
frame.isForegroundSet();
frame.getContentPane().setBackground(Color.BLACK);
}
public static void call()
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
creatAndShowGUI();
}
});
}
}
I believe thats all the code, and I am not very used to how to format the code in stack overflow, so I might of messed something up. I am probably just getting something messed up, so i am sorry for that but thanks in advance.
The main problem is in your createAndShowGUI in your InfoBook class...
public static void creatAndShowGUI() {
JFrame frame = new JFrame("Info Panel");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
InfoBook newContentPane = new InfoBook();
frame.setLayout(null);
frame.setVisible(true);
frame.setLocation(850, 445);
frame.setSize(900, 580);
frame.setTitle("Unescapable 1.0");
frame.setBackground(Color.GREEN);
frame.isOpaque();
frame.isForegroundSet();
frame.getContentPane().setBackground(Color.BLACK);
}
Essentially, you create an instance of newContentPane, but you never use it.
But, you're about to run into a second problem...
} else if ("info".equals(e.getActionCommand())) {
InfoBook add = new InfoBook();
add.call();
Here you create an instance of InfoBook, but this instance will have no relationship to the one that is created in your creatAndShowGUI and which I assume you want to show on the screen, so getting information from the class will be impossible
I suspect, you actually want to use a JDialog of some kind instead, which will allow you to present a window to the user, BUT which will block the execution of the code until the user closes the window, at which time you could then interrogate the object for it's information.
See How to Make Dialogs for more details
As a general rule of thumb, you don't want to extend from top level containers like JFrame or JDialog, instead, you want to use a JPanel as the base component and add these to what ever container you need.
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
You might also like to have a look at The Use of Multiple JFrames, Good/Bad Practice?

Switch between JPanels of different classes

How do I switch between JPanels of different classes? I do not wish to use a Card Layout.
I have 2 classes - MainPage & MenuPage. For instance, I would like to clear the contentPane (a JPanel) # MainPage and replace it with the content pane # MenuPage. For testing purposes, I included a button # MenuPage.
Please see my following attempt - it gives an error:
java.lang.IllegalArgumentException: adding a window to a container
MainPage
public class MainPage extends JFrame {
private static JPanel contentPane;
private JLabel imgBackground;
private JLabel lblTitle;
private JLabel imgLogo;
private Dimension dim;
//timer
private final static int interval = 40;
private int i;
private Timer t;
//private JButton start;
//private JLabel lblLoading;
private JProgressBar pbar;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainPage frame = new MainPage();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainPage() {
dim = Toolkit.getDefaultToolkit().getScreenSize();
System.out.println(dim);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
contentPane.setBounds(0,0,dim.width,dim.height);
setContentPane(contentPane);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
t = new Timer (interval, new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (i == 20){
t.stop();
//start.setEnabled(true);
//refresh + load next page ???
contentPane.removeAll();
MenuPage loadpanel2 = new MenuPage();
setContentPane(loadpanel2);
revalidate();
repaint();
}
else{
i++;
pbar.setValue(i);
}
}
});
t.start();
MenuPage
public class MenuPage extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MenuPage frame = new MenuPage();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MenuPage() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
JButton btnSadfsafsa = new JButton("sadfsafsa");
btnSadfsafsa.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnSadfsafsa.setBounds(10, 52, 89, 23);
btnSadfsafsa.setEnabled(true);
btnSadfsafsa.setVisible(true);
contentPane.add(btnSadfsafsa);
}
}
java.lang.IllegalArgumentException: adding a window to a container
That is pretty straightforward. Both GUIs extend JFrame and are therefore top level containers. We cannot add one top level container to another.
Instead of extending frame, both GUIs might extend JPanel. A JPanel (or more than one) can then be added to a JFrame instantiated in the main(String[]) or a showGUI() method.

Categories

Resources