Java - change from Panel1 to Panel2 - java

I wanna create a simple java application, and I have some problems.
This is my main class:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MainWindow {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
JButton btnNewButton = new JButton("First B");
panel.add(btnNewButton);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SecWindow SW = new SecWindow();
//-----
}
});
}
}
Secound class:
import javax.swing.JButton;
import javax.swing.JPanel;
public class SecWindow {
public SecWindow() {
SecPanel();
}
public void SecPanel() {
JPanel panel2 = new JPanel();
JButton btnNewButton_2 = new JButton("Sec B");
panel2.add(btnNewButton_2);
}
}
How can I do this: when I press the "First B" I wanna delete the first panel and create a new one class SecWindow().

How can I do this: when I press the "First B" I wanna delete the first panel and create a new one class SecWindow().
You should be using a CardLayout. The CardLayout will allow you to swap panels in the frame.
Read the section from the Swing tutorial on How to Use CardLayout for more information and working examples.
The example uses a combo box to swap the panels so you just need to move that code to the ActionListener of your button.

try{
secWindow secondWindow = new secWindow();
secondWindow.frame.setVisible(true);
window.frame.setVisible(false);
} catch (Exception e) {
e.printStackTrace();
This will hide first window and show second one.
You can not completely "delete" object that has main method in it. your app will start and end in main method.
instead you can make new class and transfer main method over there

Related

Toggle the visibility of Jlabel and JPanel

I am trying to toggle the visibility of JLable and JPanel. Both are in initial case in visible state. After pressing a Button, they should be invisible for two seconds. After this time they are going to be visible again. In adddition, there are two checkBoxes on the JPanel, which are grouped by ButtonGroup. The selection should be cleared after pressing the Button.
For solving I wrote the following code:
package Aufgaben;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.EmptyBorder;
public class Aufgabe1 extends JFrame {
private JPanel contentPane;
private JPanel checkPanel;
private JPanel pointPanel;
private JRadioButton rdbtnJa;
private JRadioButton rdbtnNein;
private ButtonGroup btnGroup;
private JButton btnStart;
private JLabel lblX;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Aufgabe1 frame = new Aufgabe1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Aufgabe1() {setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 700, 300);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
btnStart = new JButton("Start");
btnStart.setBounds(0, 0, 684, 23);
contentPane.add(btnStart);
checkPanel = new JPanel();
checkPanel.setBounds(0, 229, 684, 33);
contentPane.add(checkPanel);
btnGroup = new ButtonGroup();
rdbtnJa = new JRadioButton("Ja");
checkPanel.add(rdbtnJa);
btnGroup.add(rdbtnJa);
rdbtnNein = new JRadioButton("Nein");
checkPanel.add(rdbtnNein);
btnGroup.add(rdbtnNein);
pointPanel = new JPanel(new BorderLayout());
pointPanel.setBackground(Color.BLACK);
pointPanel.setBounds(0, 23, 684, 209);
contentPane.add(pointPanel);
lblX = new JLabel("X");
lblX.setForeground(Color.WHITE);
lblX.setVerticalAlignment(JLabel.CENTER);
lblX.setHorizontalAlignment(JLabel.CENTER);
pointPanel.add(lblX, BorderLayout.CENTER);
run();
}
public void run() {
System.out.println("----------");
System.out.println("Method run()");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("btn actionPerformed()");
createLightPoint();
}
});
}
private void createLightPoint() {
System.out.println("----------");
System.out.println("Method createLightPoint()");
btnGroup.clearSelection();
lblX.setVisible(false);
// lblX.repaint();
// pointPanel.repaint();
checkPanel.setVisible(false);
// checkPanel.repaint();
System.out.println("Bevor Sleep");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("After Sleep");
lblX.setVisible(true);
// lblX.repaint();
checkPanel.setVisible(true);
// checkPanel.repaint();
}
}
As you can see I tried to solve the problems (what I described above) over the function .setVisibility() as well .repaint(). I tried the functions .show() and .hide althought they are deprecatet as well.But in any case, it doesn't work.
I already read the following posts:
Show/Hide JLabel with button?
https://softwareengineering.stackexchange.com/questions/233068/is-better-show-hide-or-setvisiblebool-visible
But none of them could help the solve my problem.
I hope you can Help me.
Don't use sleep() on Event Dispatch Thread - it will prevent the thread from processing painting and other UI related events and the UI will become frozen. See The Event Dispatch Thread tutorial for more details.
You can use Swing timer instead, see How to Use Swing Timers tutorial for examples.

Java getContentPane().setBackground() not working

Im trying to encapsulate the GUI calls to a single class. My window appears but the background remains the default color instead of red.
ChatProgram.java
package ChatPkg;
public class ChatProgram {
/**
* Launch the application.
*/
public static void main(String[] args) {
ChatWindow.initialize();
ChatWindow.RunWindow();
}
}
ChatWindow.java
package ChatPkg;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
public final class ChatWindow {
static JFrame frame;
/**
* Create the application.
*/
private ChatWindow() { }
public static void RunWindow() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Initialize the contents of the frame.
*/
public static void initialize() {
frame = new JFrame("Chat program");
frame.setBounds(100, 100, 450, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JCheckBox chckbxCvbc = new JCheckBox("cvbc");
frame.getContentPane().add(chckbxCvbc);
// Set background color
frame.getContentPane().setBackground(Color.red);
}
}
Yes i am new to Java and none of the google results solved my problem.
You should NOT add GUI components directly to the content pane of the JFrame. Also, you shouldn't modify its properties (like you tried changing the background).
You always need a JPanel that acts as a container on which the graphical elements are added. Here is how you could write your initialize function:
public static void initialize() {
frame = new JFrame("Chat program");
frame.setBounds(100, 100, 450, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JCheckBox chckbxCvbc = new JCheckBox("cvbc");
panel.add(chckbxCvbc);
// Set background color and add panel to the Jframe
panel.setBackground(Color.RED);
frame.getContentPane().add(panel);
}

unable to close JOptionPane properly in chain order

I am displaying a JOptionPane suppose A on a button click from JFrame, and again displaying another JOptionPane suppose B on a button click from JOptionPane A, and I have a button on JOptionPane B suppoce button1, on the click event of button1, I am using code JOptionPane.getRootFrame().dispose() for closing the JOptionPane B, but it closes both A and B, please help me how can close only B but not A.
here is my sample code
i want second JOptionPane must be open
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SampleCode extends JFrame {
public SampleCode() {
setSize(new Dimension(500, 500));
setLocation(450, 150);
but1 = new JButton("Click me");
add(but1);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
but1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
but1Function();
}
});
}
public static void main(String args[]) {
new SampleCode();
}
void but1Function() {
JPanel panel1 = new JPanel();
JButton but2 = new JButton("Open new dialog");
panel1.add(but2);
but2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel pan2 = new JPanel();
JButton but3 = new JButton("click me to close");
pan2.add(but3);
but3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.getRootFrame().dispose();
}
});
JOptionPane.showMessageDialog(null, pan2);
}
});
JOptionPane jp = new JOptionPane(panel1, JOptionPane.CLOSED_OPTION,
JOptionPane.DEFAULT_OPTION, null, new Object[] {}, null);
JDialog dialog = jp.createDialog(null, "This one must be remain open");
dialog.setLocation(500, 200);
dialog.setSize(new Dimension(345, 200));
dialog.setVisible(true);
}
JButton but1;
}
You don't want to get the root frame nor dispose of it. You want to get the window that is displaying the JOptionPane, a Window that should be a modal JDialog. So instead, use SwingUtilities.getWindowAncestor(someComponentInJOptionPane), and call dispose() on that Window if you want to programmatically dispose of your JOPtionPane.
import java.awt.Component;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class OptionPaneFun {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#SuppressWarnings("serial")
public void run() {
final JPanel panel1 = new JPanel();
panel1.add(new JButton(new AbstractAction("Show new option pane") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_S);
}
#Override
public void actionPerformed(ActionEvent e1) {
final JPanel panel2= new JPanel();
panel2.add(new JButton(new AbstractAction("Dispose of this option pane") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_D);
}
#Override
public void actionPerformed(ActionEvent e2) {
Component comp = (Component) e2.getSource();
Window win = SwingUtilities.getWindowAncestor(comp);
if (win != null) {
win.dispose();
}
}
}));
JOptionPane.showMessageDialog(panel1, panel2);
}
}));
JOptionPane.showMessageDialog(null, panel1);
}
});
}
}
The static method "getRootFrame()" returns your root frame which is the only one and it's the same for both your components (A and B). What you need to do - you have to put two frames in your root frame (call them frameA and frameB) and put paneA to frameA and paneB to frameB. Instead of calling this static method just invoke frameB.dispose() on reference frameB which you already have.
Try to add
panel.validiate();
After the dispose command. I had the same problem once and it helped a lot when I used this trick.
Basically when you add this command, it is telling the frame to validate or actually do it.
Read the oracle docs for more info.

Adding a panel from a method to a frame

I didn't really know how else to phrase that but essentially:
-I have a few separate "pieces" that I am trying to add onto a master frame; to keep the code from getting unwieldy I have each "piece" be its own class.
-I'm getting stuck on adding the panells onto the master frame, because the classes themselves aren't panels, rather the method of the class creates the panel, which creates issues that I don't know how to solve.
PIECE (works on its own when I have it make a dialog instead of be a panel):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PieceThing3 extends JPanel //<switched from JDialog
{
//set up variables here
private ActionListener pieceAction = new ActionListener()
{
public void actionPerformed (ActionEvent ae)
{
// Action Listener (this also works)
}
};
private void createPiece()
{
//setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
//setLocationByPlatform(true);
// the above are commented out when I switch from dialog to panel
JPanel contentPane = new JPanel();
//something that uses pieceAction is here
//two buttons, b and s, with action listeners are here
contentPane.add(b);
contentPane.add(s);
add(contentPane);
//pack();
//again, commented out to switch from dialog
setVisible(true);
System.out.println("hi I'm done");
//just to check and make sure it's done
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PieceThing3().createPiece();
}
});
}
}
Sorry that is very vague, but the intricacies are not as important as the general idea - it works perfectly when I have it create its own dialog box, but now I am trying to get it to make a panel within a master code, below:
MASTER:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CollectGUI extends JFrame{
private void createDialog(){
this.setSize(2000,1000);
this.setLocation(0,0);
this.setTitle("TITLE");
PieceThing3 pt = new PieceThing3();
//HERE, if I do pt.main(null); while it is in "dialog mode" (rather than panel) it pops up a dialog box and everything is hunky dory. But I don't know how to get it to add the method as a panel.
this.add(pt.main(null));
//this gives an error
this.setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new CollectGUI().createDialog();
}
}
As I said in the comments, if I just do pt.main(null) when pt is set to make a dialog, it does it, but if I try to add pt.main(null) as a panel it throws an error. Can anybody give me some insight on how to add a method of a class rather than a class? I'm pretty stumped.
THANK YOU!!
You are definitely on the right track working to maintain separation of concerns and implement your gui in a number of distinct components. Try something like this:
Panel1
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Panel1 extends JPanel {
public Panel1() {
this.add(new JLabel("This is panel 1"));
}
}
Panel2
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Panel2 extends JPanel {
public Panel2() {
this.add(new JLabel("This is panel 2"));
}
}
JFrame
import java.awt.BorderLayout;
import javax.swing.JFrame;
import org.yaorma.example.jframe.panel.panel1.Panel1;
import org.yaorma.example.jframe.panel.panel2.Panel2;
public class ExampleJFrame extends JFrame {
public ExampleJFrame() {
super("Example JFrame Application");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400,400);
this.setLayout(new BorderLayout());
Panel1 pan1 = new Panel1();
Panel2 pan2 = new Panel2();
this.add(pan1, BorderLayout.NORTH);
this.add(pan2, BorderLayout.SOUTH);
this.setVisible(true);
}
}
main:
public class ExampleApplication {
public static void main(String[] args) throws Exception {
new ExampleJFrame();
}
}
EDIT:
Here's a Panel1 with a little more content.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.yaorma.example.action.sayhello.SayHelloAction;
public class Panel1 extends JPanel {
//
// instance variables
//
private JButton pressMeButton;
//
// constructor
//
public Panel1() {
this.setLayout(new BorderLayout());
this.add(new JLabel("This is panel 1"), BorderLayout.NORTH);
this.initPressMeButton();
}
//
// button
//
private void initPressMeButton() {
this.pressMeButton = new JButton("Press Me");
this.pressMeButton.addActionListener(new PressMeButtonActionListener());
this.add(pressMeButton, BorderLayout.SOUTH);
}
//
// method to get the parent jframe
//
private JFrame getParentJFrame() {
Container con = this;
while(con != null) {
con = con.getParent();
if(con instanceof JFrame) {
return (JFrame)con;
}
}
return null;
}
//
// action listener for Press Me button
//
private class PressMeButtonActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JFrame jFrame = getParentJFrame();
SayHelloAction action = new SayHelloAction(jFrame);
action.execute();
}
}
}
Action called by button:
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class SayHelloAction {
private JFrame owner;
public SayHelloAction(JFrame owner) {
this.owner = owner;
}
public void execute() {
JOptionPane.showMessageDialog(owner, "Hello World");
}
}

Refresh a Jlist from another JFrame

i want to refresh a JList when i push a button in another JFrame.
So i have a JFrame GuiBoss that manages employees (add,delete,update).When i press the button add, another Jframe opens, in wich i create a new employee.
//Open the "add_form" where i give details about a new employee.
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
GuiBoss gb = new GuiBoss(contrb,boss);
Add_form af = new Add_form(gb,contrb,boss);
af.setVisible(true);
}
//refresh the list with the new employee added.
public void refresh(Employee e){
System.out.println("I reach this point!");
//if i print e.getName() it works, printing the right name that i give in the "add_form"
listModel.addElement(e);
//listModel.clear(); //don't work either.
}
My problem is that when i submit the details about the new employee i call the function refresh(Employee e) from the GuiBoss frame , the message ("I reach this point!") shows up on the console, the size of the listModel changes, but the list it doesen't refresh.
Also i must say that i set the model properly for the list.
//take data from form and call refresh(Employee e) from the main frame("GuiBoss")
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
//String Id = txtID.getText();
String UserName = txtName.getText();
txtHour.setVisible(false);
boolean b = false;
if(rbtnYes.isSelected() == true){
b = true;
}
if(rbtnNo.isSelected() == true){
b = false;
}
if(rbtnYes.isSelected()==false && rbtnNo.isSelected() == false){
System.out.println("Select the presence!");
}
else{
txtOra.setVisible(true);
String Hour = txtHour.getText();
e = new Employee(UserName,b,Hour,boss); //boss i get from main frame when i start this add new employee form
contrb.addEmployee(e);
gb.refresh(e); //gb is of type GuiBoss were i have the function that does
// the refresh
}
}
Please let me know if u have any ideeas.Thanks.
Instead of popping up another frame, why not use a modal JDialog to collect the information about the new employee. When the dialog is closed, you can then extract the details from the dialog and refresh the list from within the current frame.
This prevents the need to expose portions of your API unnecessarily.
Check out How to use Dialogs for details.
Updated
Assuming you've set the model correctly, then your code should work...as per this example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestList03 {
public static void main(String[] args) {
new TestList03();
}
public TestList03() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private DefaultListModel model;
public TestPane() {
setLayout(new BorderLayout());
model = new DefaultListModel();
JList list = new JList(model);
add(new JScrollPane(list));
JButton btn = new JButton("Add");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.addElement("New Element");
}
});
add(btn, BorderLayout.SOUTH);
}
}
}
That would suggest that there is something else wrong that you're not showing us...
Updated with possible fix for reference issues
This basically demonstrates passing a reference of the main panel to a sub factory that is responsible for actually adding the value back into the main panel. Normally I'd use a interface of some kind instead of exposing the entire panel to simply provide access to a single method, but this was a quick example.
It uses both a normal implements and inner class as ActionListener to demonstrate the two most common means for passing a reference of "self" to another class.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestList03 {
public static void main(String[] args) {
new TestList03();
}
public TestList03() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel implements ActionListener {
private DefaultListModel model;
public TestPane() {
setLayout(new BorderLayout());
model = new DefaultListModel();
JList list = new JList(model);
add(new JScrollPane(list));
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton btn1 = new JButton("Add 1");
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new Factory(TestPane.this, "Added by Button 1");
}
});
buttons.add(btn1);
JButton btn2 = new JButton("Add 2");
btn2.addActionListener(this);
buttons.add(btn2);
add(buttons, BorderLayout.SOUTH);
}
public void addItem(String text) {
model.addElement(text);
}
#Override
public void actionPerformed(ActionEvent e) {
new Factory(TestPane.this, "Added by Button 2");
}
}
public class Factory {
public Factory(TestPane testPane, String text) {
testPane.addItem(text);
}
}
}

Categories

Resources