open same frame when button click in java - java

i updated the code because many people doesn't understand so write a simple representation for that.
here is the problem whenever i clicked the button it open a new frame but i dont want this it does't open a new frame it remain open the same frame.
code for main frame :
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class JavaProject2_27 {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JavaProject2_27 window = new JavaProject2_27();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public JavaProject2_27() {
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);
frame.getContentPane().setLayout(null);
JButton btnClicked = new JButton("Clicked");
btnClicked.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JavaProject2_28 obj=new JavaProject2_28();
obj.getJavaProject2_28();
}
});
btnClicked.setBounds(150, 99, 89, 23);
frame.getContentPane().add(btnClicked);
}
}
code for the second frame :
import java.awt.EventQueue;
import javax.swing.JFrame;
public class JavaProject2_28 {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JavaProject2_28 window = new JavaProject2_28();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public JavaProject2_28() {
initialize();
}
public void getJavaProject2_28()
{
frame.setVisible(true);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
snapshot

I was checking your earlier program, still cannot find the implementation of getDataJavaProject2_23(); method in those three classes that you provided.
First of all answer to your question few things to mention:
Use proper naming convention, as a example: JavaProject2_28 this class name didnot make any sense to us or even for you if you look at this after a week or two.
You can divide your program for more classes, as a example: database data handling, GUI and etc.
And another important thing is multiple JFrames for one application is not good because of even if you look at your task bar when running your program you can see there is multiple icons, it is difficult to deal with your application. There is more disadvatages about this. read this to get clear idea. Instead of multiple JFrames you can use one JFrame and multiple JPanel with appropriate layouts.
Answer for your updated question:
whenever i clicked the button it open a new frame but i dont want this
it does't open a new frame it remain open the same frame.
I checked your program it is work fine(after press the button open up the other frame).
You can do some changes that are unnecessary:
Remove this function
public void getJavaProject2_28()
{
frame.setVisible(true);
}
And add frame.setVisible(true); to the initialize() method.
Solution:
Add frame.setVisible(true) to button action.
Like below:
}
});
btnClicked.setBounds(150, 99, 89, 23);
frame.getContentPane().add(btnClicked);
frame.setVisible(true);
}
And in the main frame(which is button button added) change like below:
JButton btnClicked = new JButton("Clicked");
btnClicked.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JavaProject2_28 obj=new JavaProject2_28();
}
});
Also you do not need the main() method in both if you are only open second JFrame in main frame button.

I solved It Please A look :
Parent Class:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class ParentClass {
private JFrame frame;
private int Count;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ParentClass window = new ParentClass();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ParentClass() {
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);
frame.getContentPane().setLayout(null);
JButton btnClicked = new JButton("Clicked");
btnClicked.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
Count++;
System.out.println("Count = "+Count);
if(Count==1)
{
ChildClass obj=new ChildClass();
obj.ChildClassVisibility();
}
}
});
btnClicked.setBounds(150, 99, 89, 23);
frame.getContentPane().add(btnClicked);
}
}
ChildClass:
import java.awt.EventQueue;
import javax.swing.JFrame;
public class ChildClass {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ChildClass window = new ChildClass();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ChildClass() {
initialize();
}
public void ChildClassVisibility()
{
frame.setVisible(true);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Related

Java swing Loader image not displaying properly? [duplicate]

This question already has answers here:
Java swing GUI freezes
(5 answers)
Closed 5 years ago.
I have tried the below code .
Functionality-
Click on Button
It will call a method which will take some time to process.
Need to display Loader image so that user can see that processing is going on.
I tried below but if the loaderLabel1.setVisible(true); before method call doesnot show image and if we comment loaderLabel1.setVisible(false); then it shows loader image after method is finished.
Will actionPerformed method not apply the visibility to Label unless it completes? If yes is there any alternative for this problem?
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TestLoader extends JPanel{
static ImageIcon loading1 = new ImageIcon("D:\\WORKSPACE\\STUDY\\images\\ajax-loader.gif");
static JLabel loaderLabel1 = new JLabel(loading1, JLabel.CENTER);
public TestLoader(){
super(new GridLayout(0, 1));
System.out.println("---------TEST ------");
JPanel submitPanel = new JPanel();
submitPanel.add(clearMessageButton);
this.add(submitPanel);
JPanel LOADER_PANEL = new JPanel();
loaderLabel1.setVisible(false);
LOADER_PANEL.add(loaderLabel1);
this.add(LOADER_PANEL);
}
JButton clearMessageButton = new JButton(new AbstractAction("Test Result") {
#Override
public void actionPerformed(ActionEvent arg0) {
loaderLabel1.setVisible(true);
TestMethod();
loaderLabel1.setVisible(false);
}});
public void TestMethod(){
System.out.println(" =========START TestMethod =========");
try {
Thread.currentThread().sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" =========complete TestMethod =========");
}
/**
* #param args
*/
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
TestLoader pf = new TestLoader();
pf.display();
}
});
}
private void display() {
JFrame frame = new JFrame("TEST LOADER");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.pack();
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
There is the class SwingWorker that allows you to perform Tasks in a different thread; here's an example of how your code could be changed to use a SwingWorker:
JButton clearMessageButton = new JButton(new AbstractAction("Test Result") {
#Override
public void actionPerformed(ActionEvent arg0) {
SwingWorker worker = new SwingWorker() {
#Override
protected Object doInBackground() throws Exception {
loaderLabel1.setVisible(true);
TestMethod();
return true;
}
public void TestMethod() {
System.out.println(" =========START TestMethod =========");
try {
Thread.currentThread().sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" =========complete TestMethod =========");
}
protected void done() {
loaderLabel1.setVisible(false);
};
};
worker.execute();
}
});
Note the methods doInBackground() that does the work in the other thread and done() that is called after doInBackground() is finished.

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);
}

Java - change from Panel1 to Panel2

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

changing images in jLabel after certain intervals

I had to make a sort of animation thing in netbeans gui. So I was studying about swing timer on the internet and from what i found i worte a method which will change images in jLabel after certain time periods.
public void animation() throws InterruptedException {
ActionListener taskPerformer = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
t++;
System.out.printf("Reading SMTP Info. %d\n",t);
if(t%2==1){
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/oncsreen_keypad/a.jpg")));
}
else{
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/oncsreen_keypad/b.jpg")));
}
}
};
Timer timer = new Timer( 1000 , taskPerformer);
//timer.setRepeats(false);
timer.start();
Thread.sleep(5000);
}
this method is called nowhere. But if the System.out.printf works then changing image in jLabel should also work. But actually in the run those lines are having no effect on the jLabel.
So what should be the right approach.
Dont stop the main thread with Thread.sleep.., use the Swing Timer and give him the delay, when your image should change.
I made a small example for you.
This is the class which generates the JFrame with a JPanel, which contains the JLabel.
package timerdemo;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
/**
*
* #author ottp
* #version 1.0
*/
public class Gui extends JFrame {
private JLabel jLabel;
private Timer timer;
private boolean chromeShown;
public Gui() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800, 600);
JPanel panel = new JPanel(new BorderLayout());
jLabel = new JLabel(new ImageIcon("/home/ottp/Downloads/chrome.png"));
chromeShown = true;
panel.add(jLabel);
timer = new Timer(5000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(chromeShown) {
jLabel.setIcon(new ImageIcon("/home/ottp/Downloads/ok.png"));
chromeShown = false;
} else {
jLabel.setIcon(new ImageIcon("/home/ottp/Downloads/chrome.png"));
chromeShown = true;
}
}
});
timer.start();
this.getContentPane().add(panel);
this.setVisible(true);
}
}
And start it...
package timerdemo;
import javax.swing.SwingUtilities;
/**
*
* #author ottp
*/
public class TimerDemo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Gui();
}
});
}
}
After starting the timer in your Gui class, the image on the JLabel will be changed every 5 seconds, condition for this is the boolean flag. You could use your if... else construct also there.
Hope this helps
Patrick

Bringing borderless swing window to front

I have a swing program which creates a fullscreen borderless window -- I am running on Windows 7. I need the program to be able to focus and bring itself to the front. However, when I attempt to use the method found here, How to bring a window to the front?, instead of bringing the window to the front the window just flashes in the taskbar and does not accept input. Below I wrote a small program that demonstrates the issue:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class WindowTest extends JFrame{
WindowTest(){
setTitle("Window Test");
setSize(600, 600);
setLocationRelativeTo(null);
setUndecorated(true);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final WindowTest wt = new WindowTest();
wt.setVisible(true);
Timer t = new Timer(3000,new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
wt.toFront();
wt.repaint();
}
});
}
});
t.setRepeats(false);
t.start();
wt.addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent arg0) {
if(arg0.getKeyCode() == KeyEvent.VK_ESCAPE){
wt.dispose();
System.exit(0);
return;
}
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
});
}
});
}
}
This will create a borderless, maximized window, and then three seconds later will attempt to bring it to the front. If you change to another window before that, the taskbar button will flash but the window will not be brought to the front.
toFront(quite common issue) doesn't works for JFrame, this is basic property for JDialog
basically is possible to move toFront() only one JFrame, have to use setExtendedState, but with side effects flickering and jumping on the scren, use JDialog instead
don't use KeyListener, because JFrame isn't focusable for KeyEvent, have to use KeyBindings
for example
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class WindowTest extends JFrame {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame();
public WindowTest() {
frame.setTitle("Window Test");
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setExtendedState(JFrame.ICONIFIED);
Timer t = new Timer(3000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
frame.setExtendedState(JFrame.NORMAL);
}
});
}
});
t.setRepeats(false);
t.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final WindowTest wt = new WindowTest();
}
});
}
}
There's another trick that can be used in case you don't want to minimize and then maximize the window. I have no idea why it works, but if you move the mouse before making the window visible it will come to the front. It's pretty weird, I know, but it seems to work for JRE 1.4 through 1.8 at least. In order to minimize the effect on the mouse you can first see where it is and only move it a little. Your code might look something like this:
PointerInfo mInfo = MouseInfo.getPointerInfo();
Point mWhere = mInfo.getLocation();
(new Robot()).mouseMove(mWhere.x + 2, mWhere.y + 2);
frame_.setVisible(true);
I realize this is a rather late response for the person who posted the question but others may still be looking for the answer.

Categories

Resources