switch to an animation image in cardlayout - java

I want to create a login dialog. when user press login button it will show a animation image. with some search I find that use cardlayout can switch to another panel so I chose cardlayout for my login dialog. but when a switch to a panel contain a jlabel that have animation image jlabel just load text
here is my code:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author 20133_000
*/
public class Draft9 {
public static void main(String[] args) {
TestCardLayout test = new TestCardLayout();
}
}
class TestCardLayout extends JFrame {
private JPanel mainPanel;
private CardPanel panel1;
private JPanel panel2;
private CardLayout layout;
public TestCardLayout() {
mainPanel = new JPanel();
panel1 = new CardPanel();
panel2 = new JPanel();
layout = new CardLayout();
panel1.add(new JButton("here is panel 1"));
JLabel jLabel1 = new javax.swing.JLabel("here is panel 2",new javax.swing.ImageIcon( "E:\\programming\\programming java\\Netbean Projectr\\Project1\\src\\images\\loading3.gif") , JLabel.CENTER);
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
//jLabel1.setIcon(new javax.swing.ImageIcon("/images/loading3.gif")); // NOI18N
// jLabel1.setIcon(new javax.swing.ImageIcon("E:\\programming\\programming java\\Netbean Projectr\\Project1\\src\\images\\loading3.gif"));
panel2.add(new JButton("here is panel 2"), BorderLayout.NORTH);
panel2.add(jLabel1, BorderLayout.CENTER);
mainPanel.setLayout(layout);
mainPanel.add("panel1", panel1);
mainPanel.add("panel2", panel2);
add(mainPanel, BorderLayout.CENTER);
setSize(400, 450);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//layout.show(mainPanel, "panel2");
}
}
class CardPanel extends JPanel {
JButton btnChangePanel;
public CardPanel() {
btnChangePanel = new JButton("show panel 2");
btnChangePanel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showPanel2();
calculateData();
}
});
add(btnChangePanel);
}
public void showPanel2() {
JPanel parentPanel = (JPanel) getParent();
CardLayout layout = (CardLayout) parentPanel.getLayout();
layout.show(parentPanel, "panel2");
}
public void showPanel1() {
JPanel parentPanel = (JPanel) getParent();
CardLayout layout = (CardLayout) parentPanel.getLayout();
layout.show(parentPanel, "panel1");
}
public void calculateData() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
System.out.println("calculating data...");
//doing some calculate here
Thread.sleep(3000);
System.out.println("done calculting");
//System.exit(0);
int res = 1;
if (res == 1) {
System.out.print("login ok");
showPanel2();
} else {
System.out.print("login failed");
showPanel1();
}
} catch (Exception ex) {
Logger.getLogger(CardPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
when i leave Thread.sleep(3000); comment it work but when i uncomment that line it doesn't work. How can i fix it ?

It's because your image is animated (would work with a normal one) and your Thread.sleep(3000) freezes the whole frame, note that you also can't click the button (or move frame). You could start a new thread to solve this:
public void calculateData() {
new Thread(new Runnable() {
public void run() {
try {
System.out.println("calculating data...");
// doing some calculate here
Thread.sleep(3000);
System.out.println("done calculting");
// System.exit(0);
int res = 1;
if (res == 1) {
System.out.print("login ok");
showPanel2();
} else {
System.out.print("login failed");
showPanel1();
}
} catch (Exception ex) {
Logger.getLogger(CardPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}).start();
}

Related

Moving from one frame to another

I am new to JAVA swing , where i develop two different JFrame if I click on button frame should move to another frame and previous frame should close by opening of next frame.
I click on button a next frame open but data inside frame is not displaying and previous frame is not closed on button . Please help to find the problem in code.
Frame 1:---------------------------------
package com.demo.test;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import com.demo.gui.TestjigWindow;
public class TestjigWindowCheck extends JFrame{
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public TestjigWindowCheck() {
initUI();
}
private void initUI() {
mainFrame = new JFrame("Fuse Test jig");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(500,500);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
public void showEventDemo(){
//TestjigWindow frame1 = new TestjigWindow();
headerLabel.setText("Fuse Test Jig");
headerLabel.setFont(new Font( "Arial", Font.BOLD, 25));
headerLabel.setBackground(Color.green);
JButton startButton = new JButton("Start");
startButton.setActionCommand("Start");
JButton closeButton = new JButton("Close");
closeButton.setActionCommand("close");
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
if(e.getSource() == startButton)
{
TestjigWindow2 frame2 = new TestjigWindow2();
frame2.setVisible(true);
dispose();
}
else if(e.getSource() == closeButton)
{
System.exit(0);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
closeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
System.exit(0);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
controlPanel.add(startButton);
controlPanel.add(closeButton);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
TestjigWindowCheck test = new TestjigWindowCheck();
test.showEventDemo();
//test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Frame 2----------------------------------- .
package com.demo.test;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TestjigWindow2 extends JFrame{
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private JPanel controlPanel1;
public TestjigWindow2()
{
prepareGUI();
}
public static void main(String args[])
{
TestjigWindow2 test = new TestjigWindow2();
test.showRadioButton();
}
private void prepareGUI()
{
mainFrame = new JFrame("Fuse Test2 jig");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(500,500);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
public void showRadioButton()
{
headerLabel.setText("Fuse Mode");
final JRadioButton setting =new JRadioButton("Setting");
final JRadioButton testing =new JRadioButton("Testing");
setting.setBounds(75,50,100,30);
testing.setBounds(75,100,100,30);
setting.setMnemonic(KeyEvent.VK_S);
testing.setMnemonic(KeyEvent.VK_T);
ButtonGroup group = new ButtonGroup();
group.add(setting);
group.add(testing);
controlPanel.add(setting);
controlPanel.add(testing);
JButton button = new JButton("Next");
button.setActionCommand("Next");
controlPanel.add(button);
mainFrame.setVisible(true);
}
}
For this problem, I think it's a fairly simple solution, as Andrew commented, you don't need to keep creating JFrames, you can create your JFrame in your first program, and pass it to your second class through the constructor.
Why I think your program is closing is because you are calling dispose() after creating the new frame which might be destroying the components in your new frame.
You could take this approach, which uses only one frame creating in the opening class and carried over to the second class
For Example (using snipplets of your code):
Frame 1
//This is where you are moving to the second frame.
if(e.getSource() == startButton)
{
mainFrame.getContentPane().removeAll(); //removeAll() method wipes all components attached to the contentpane of the frame
//Frame can be reused when passed to second class
TestjigWindow2 frame2 = new TestjigWindow2(this.mainFrame);
}
Frame 2
//In your constructor you could have something like this
private JFrame mainFrame;
/*
* Other variables and constants go here
*
*/
public TestjigWindow2(JFrame mainFrame)
{
this.mainFrame = mainFrame;
prepareGUI();
}
And then in prepareGUI(), you would then be adding your components to your frame, without creating a new frame. With this, your first page will be closed, and the second frame will be open, without you having to creating mutiple JFrames.
You should just create a new Instance of TestjigWindow2 in the actionPerformed method within your first frame. Instead of adding actionPerformed on the startbutton and stopbutton seperately, implement ActionListener interface in your Frame1 class and just keep one method since you are checking for the source inside the method anyways.
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
if(e.getSource() == startButton)
{
TestjigWindow2 frame2 = new TestjigWindow2();
//frame2.setVisible(true); do this inside the frame2 preparegui method
dispose();
}
else if(e.getSource() == closeButton)
{
System.exit(0);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
Also the code will have a more generalized flow if you have the main method inside Frame1 and instantiate the Frame1 in it.
And you don't need to use setVisible inside the actionPerformed of Frame1.

How to delete button after clicking on "delete" button?

My program seems to run fine, except for the delete part. Every time I click on the 'delete' button, it deletes itself. So my question is, how would I delete a selected button after I clicked on the "delete" button?
Here is a snippet of my code:
public class DeleteButton extends JFrame implements ActionListener
{
JButton b18a = new JButton("Delete");
JPanel panel = new JPanel();
panel.add(b18);
class ClickListenerTwo implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton buttonThatWasClicked = (JButton) e.getSource();
Container parent = buttonThatWasClicked.getParent();
parent.remove(buttonThatWasClicked);
parent.revalidate();
parent.repaint();
}
}
}
ActionListener b18aClicked = new ClickListenerTwo();
b18a.addActionListener(b18aClicked);
P.S - This selected button that I'm talking about is made during run time, so I want to delete it during run time too, if that would be possible. Thanks!
So, assuming that you need to click the "other" button first, you could use an instance field to maintain a reference to the "last" clicked button and then use that when the delete button is clicked
For example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JButton lastButton;
public TestPane() {
JPanel grid = new JPanel(new GridLayout(8, 8));
for (int index = 0; index < 8 * 8; index++) {
JButton btn = new JButton(Integer.toString(index + 1));
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lastButton = btn;
}
});
grid.add(btn);
}
JButton delete = new JButton("Delete");
delete.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (lastButton != null) {
lastButton.getParent().remove(lastButton);
grid.revalidate();
grid.repaint();
}
lastButton = null;
}
});
setLayout(new BorderLayout());
add(grid);
add(delete, BorderLayout.SOUTH);
}
}
}
Personally, a JToggleButton would give a better user experience
You have to find the Component from the Top Frame.
May be this code will help you.
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if (source instanceof Component) {
Window w = findWindow((Component) source);
//Find your component and remove it from this window.
} else {
System.out.println("source is not a Component");
}
}
public static Window findWindow(Component c) {
System.out.println(c.getClass().getName());
if (c instanceof Window) {
return (Window) c;
} else if (c instanceof JPopupMenu) {
JPopupMenu pop = (JPopupMenu) c;
return findWindow(pop.getInvoker());
} else {
Container parent = c.getParent();
return parent == null ? null : findWindow(parent);
}
}

Duplicating a JPanel - (Copy JPanel's static image to different JPanel)

I'm pretty new to swing and I would like to receive some help as Im stuck with a task.
Current state:
Im having a nice JFrame object (guiFrame) which is having two JPanel on it (tabsPanel and cardPanel)(one is a simple JPanel with buttons, the other has CardLayout which is switched by the tabsPanel buttons).
Problem:
The task is that if I press the button "Show" on tabsPanel I need to send the cardPanel to a different window (ShowFrame) as a static "image", while on the previous window the program is still running and nice. So basicly Im trying to copy / clone the cardPanel.
What I have tried:
I have tried to simply
JPanel jPanelShow = cardPanel;
show.add(jPanelShow);
Of course not working because the reference number is being copied and if I run the program, the cardPanel "disappears".
I have tried to use clone()
For this its almost working but I'm getting some weird NullPointerException which isn't caused by my code.
Current codes (cloning try):
CardPanel.java
/**
* This is basicly a JPanel, just with a clone() implemented
*/
package javaapplication5;
import javax.swing.JPanel;
import java.util.Stack;
public class CardPanel extends JPanel implements Cloneable {
public CardPanel() {
super();
}
#Override
public CardPanel clone() throws NullPointerException {
/* Creating return object */
final CardPanel copy;
try {
/* Cloning */
copy = (CardPanel) super.clone();
} catch (CloneNotSupportedException e) {
/* Exception (should not happen though) */
e.printStackTrace();
return null;
}
return copy;
}
}
CardLayoutExample.java
package javaapplication5;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class CardLayoutExample {
JFrame guiFrame;
CardLayout cards;
CardPanel cardPanel;
private int showFrameNotShownYet = 1;
public ShowFrame show = new ShowFrame();
public static void main(String[] args) {
/* Random things for Swing */
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new CardLayoutExample();
}
});
}
public CardLayoutExample()
{
/* Creating the main JFrame */
guiFrame = new JFrame();
/* Making sure the program exits when the frame closes */
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("CardLayout Example");
guiFrame.setSize(400,300);
/* This will center the JFrame in the middle of the screen */
guiFrame.setLocationRelativeTo(null);
guiFrame.setLayout(new BorderLayout());
/* Border for JPanel separation */
Border outline = BorderFactory.createLineBorder(Color.black);
/* Creating JButton1 for tabsPanel */
JButton switchCards1 = new JButton("1");
switchCards1.setActionCommand("1");
switchCards1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
cards.show(cardPanel, "TestContent");
}
});
/* Creating JButton2 for tabsPanel */
JButton switchCards2 = new JButton("2");
switchCards2.setActionCommand("2");
switchCards2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
cards.show(cardPanel, "TestContent1");
}
});
/* Creating JButton3 for tabsPanel */
JButton switchCards3 = new JButton("3");
switchCards3.setActionCommand("3");
switchCards3.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
cards.show(cardPanel, "TestContent2");
}
});
JButton switchCards4 = new JButton("Show");
switchCards4.setActionCommand("Show");
switchCards4.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
/* If there is no ShowFrame yet */
if(showFrameNotShownYet == 1){
show.add((JPanel)cardPanel.clone());
show.setVisible(true);
showFrameNotShownYet = 0;
}
/* If there is a ShowFrame already */
else {
show.setVisible(false);
showFrameNotShownYet = 1;
guiFrame.repaint();
}
}
});
JButton switchCards5 = new JButton("Refresh");
switchCards5.setActionCommand("Refresh");
switchCards5.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
show.setVisible(false);
show.add((JPanel)cardPanel.clone());
show.setVisible(true);
showFrameNotShownYet = 0;
}
});
/* Creating JPanel for buttons */
JPanel tabsPanel = new JPanel();
tabsPanel.setBorder(outline);
tabsPanel.add(switchCards1);
tabsPanel.add(switchCards2);
tabsPanel.add(switchCards3);
tabsPanel.add(switchCards4);
tabsPanel.add(switchCards5);
/* Creating JPanel for CardLayout */
cards = new CardLayout();
cardPanel = new CardPanel();
cardPanel.setLayout(cards);
cards.show(cardPanel, "TestContent");
/* Adding 1st card */
JPanel firstCard = new TestContent();
cardPanel.add(firstCard, "TestContent");
/* Adding 2nd card */
JPanel secondCard = new TestContent1();
cardPanel.add(secondCard, "TestContent1");
/* Adding 3rd card */
JPanel thirdCard = new TestContent2();
cardPanel.add(thirdCard, "TestContent2");
/* Filling up JFrame with stuff */
guiFrame.add(tabsPanel,BorderLayout.NORTH);
guiFrame.add(cardPanel,BorderLayout.CENTER);
guiFrame.setVisible(true);
}
}
TestContent, TestContent1 and TestContent2 are simple JPanels with random stuff generated by SwingGUI, just as ShowFrame is empty JFrame. But if needed I will paste in those codes too.
If you only need an "image" of the cardPanel, you can simply create an image and use a JLabel to show, for example...
BufferedImage img = new BufferedImage(cardPanel.getWidth(), cardPane.getHeight(), BufferedImage.BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();
cardPanel.printAll(g2d);
g2d.dispose();
Now you have a "copy" of the cardPanel, you can simply use a JLabel to display it, for example...
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.DIPOSE_ON_CLOSE);
frame.add(new JLabel(new ImageIcon(img)));
frame.pack();
frame.setLocationRelativeTo(this);
frame.setVisible(true);

Java JDialogs How To Pass Information Between?

after looking for an answer for 3 hours, I am just about to give up on this idea:
I am making an application that displays the followers of a Twitch streamer.
A couple of features i am trying to add:
the display frame is a separate window from the controls frame.
I am trying to use (JFrame as display window) (JDialog as controls frame)
And furthermore: Settings is in another JDialog (this one has Modal(true))
Settings needs to be able to send the JFrame information such as: "username" and "text color"
And the settings JDialog will only pop up from clicking "settings" on the controls JDialog.
It will setVisible(false) when you click "save settings" or the X.
On the controls JDialog (b_console) needs to receive error messages and info like that.
And on the same JDialog, "filler" needs to receive follower count and things like that.
Here follows my code involving the transfers listed above:
package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics.*;
import javax.swing.*;
import java.io.*;
import java.net.URL;
public class JavaFollowerNotifier extends JFrame implements ComponentListener
{
Settings settings = new Settings();
ControlPanel ctrlPnl = new ControlPanel();
public JavaFollowerNotifier()
{
try
{
settings.readSettings();
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void grabFollower()
{
ctrlPnl.b_console.setText("Retrieving Info...");
try
{
URL twitch = new URL("https://api.twitch.tv/kraken/channels/" + savedSettings[1] + "/follows?limit=1&offset=0");
ctrlPnl.b_console.setText("Retrieved");
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void grabStats()
{
ctrlPnl.b_console.setText("Retrieving Info...");
try
{
URL twitch = new URL("https://api.twitch.tv/kraken/channels/" + savedSettings[1] + "/follows?limit=1&offset=0");
ctrlPnl.filler.setText("Followers: " + totalFollowers + "\nLatest: " + lastFollower);
ctrlPnl.b_console.setText("Retrieved");
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void componentMoved(ComponentEvent arg0)
{
//this is only to *attach this JDialog to the JFrame and make it move together my plan is to have it undecorated as well
int x = this.getX() + this.getWidth();
int y = this.getY();
ctrlPnl.movePanel(x, y);
}
public void paint(Graphics g)
{
if(clearPaint == false)
{
//any "savedSettings[n]" are saved in Settings.java (just not in this version)
g.setColor(Color.decode(savedSettings[3]));
scaledFont = scaleFont(follower + " followed!", bounds, g, new Font(savedSettings[2], Font.PLAIN, 200));
}
}
}
package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Settings extends JDialog implements ActionListener
{
JavaFollowerNotifier jfollow = new JavaFollowerNotifier();
ControlPanel ctrlPnl = new ControlPanel();
//here are the settings mention above
String[] savedSettings = {"imgs/b_b.jpg","username","font","color","Nightbot"};
public Settings()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
}
public void saveSettings()
{
savedSettings[4] = jfollow.lastFollower;
try
{
PrintWriter save = new PrintWriter("config.cfg");
ctrlPnl.b_console.setText("Saving...");
for(int i = 0; i < 5; i++)
{
save.println(savedSettings[i]);
}
save.close();
ctrlPnl.b_console.setText("Saved");
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
canClose = false;
}
readSettings();
this.repaint();
}
public void readSettings()
{
ctrlPnl.b_console.setText("Loading...");
try
{
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
jfollow.lastFollower = savedSettings[4];
try
{
}
catch(Exception e)
{
ctrlPnl.b_console.setText("Error");
System.out.println(e);
}
ctrlPnl.b_console.setText("Loaded Settings");
}
}
package javafollowernotifier;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ControlPanel extends JDialog implements ActionListener
{
public ControlPanel()
{
try
{
}
catch (Exception e)
{
b_console.setText("Error");
System.out.println(e);
}
}
public void movePanel(int x, int y)
{
//here is where i *attach the JDialog to the JFrame
controlPanel.setLocation(x, y);
}
public void actionPerformed(ActionEvent ie)
{
if(ie.getSource() == b_settings)
{
settings.frame.setVisible(true);
}
}
}
I tried to fix your program, but I wasn't too sure about its flow. So I created another simple one. What I did was pass the labels from the main frame to the dialogs' constructors. In the dialog, I took those labels and changed them with text entered in their text fields. If you hit enter after writing text from the dialog, you'll see the text in the frame change
public class JavaFollowerNotifier1 extends JFrame{
private JLabel controlDialogLabel = new JLabel(" ");
private JLabel settingDialogLabel = new JLabel(" ");
private ControlDialog control;
private SettingsDialog settings;
public JavaFollowerNotifier1() {
control = new ControlDialog(this, true, controlDialogLabel);
settings = new SettingsDialog(this, true, settingDialogLabel);
....
class ControlDialog extends JDialog {
private JLabel label;
public ControlDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
....
class SettingsDialog extends JDialog {
private JLabel label;
public SettingsDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
Test it out and let me know if you have any questions
import java.awt.BorderLayout;
import java.awt.Frame;
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.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class JavaFollowerNotifier1 extends JFrame{
private JLabel controlDialogLabel = new JLabel(" ");
private JLabel settingDialogLabel = new JLabel(" ");
private JButton showControl = new JButton("Show Control");
private JButton showSetting = new JButton("Show Settings");
private ControlDialog control;
private SettingsDialog settings;
public JavaFollowerNotifier1() {
control = new ControlDialog(this, true, controlDialogLabel);
settings = new SettingsDialog(this, true, settingDialogLabel);
showControl.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
control.setVisible(true);
}
});
showSetting.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
settings.setVisible(true);
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(showControl);
buttonPanel.add(showSetting);
add(buttonPanel, BorderLayout.SOUTH);
add(controlDialogLabel, BorderLayout.NORTH);
add(settingDialogLabel, BorderLayout.CENTER);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JavaFollowerNotifier1();
}
});
}
}
class ControlDialog extends JDialog {
private JLabel label;
private JTextField field = new JTextField(15);
private JButton button = new JButton("Close");
private String s = "";
public ControlDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
setLayout(new BorderLayout());
add(field, BorderLayout.NORTH);
add(button, BorderLayout.CENTER);
pack();
setLocationRelativeTo(frame);
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
s = field.getText();
label.setText("Message from Control Dialog: " + s);
}
});
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
ControlDialog.this.setVisible(false);
}
});
}
}
class SettingsDialog extends JDialog {
private JLabel label;
private JTextField field = new JTextField(15);
private JButton button = new JButton("Close");
private String s = "";
public SettingsDialog(final Frame frame, boolean modal, final JLabel label) {
super(frame, modal);
this.label = label;
setLayout(new BorderLayout());
add(field, BorderLayout.NORTH);
add(button, BorderLayout.CENTER);
pack();
setLocationRelativeTo(frame);
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
s = field.getText();
label.setText("Message from Settings Dialog: " + s);
}
});
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
SettingsDialog.this.setVisible(false);
}
});
}
}
Typically when I build GUI's which use modal dialogs to gather user input, I build my own class, which extends the JDialog or in some cases a JFrame. In that class I expose a getter method for an object which I usually call DialgResult. This object acts as the Model for the input I gather from the user. In the class that has the button, or whatever control which triggers asking the user for the information, I create it, show it as a modal dialog, then when it is closed, I retrieve the object using that same getter.
This is a very primitive example:
package arg;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class asdfas extends JFrame {
public static void main(String[] args) {
asdfas ex = new asdfas();
ex.setVisible(true);
}
public asdfas() {
init();
}
private void init() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBounds(100,100,200,200);
final JButton button = new JButton("Show modal dialog");
button.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Dialog d = new Dialog();
d.setVisible(true);
button.setText(d.getDialogResult().value);
revalidate();
repaint();
}
});
this.add(button);
}
class DialogResult {
public String value;
}
class Dialog extends JDialog {
JTextField tf = new JTextField(20);
private DialogResult result = new DialogResult();
public Dialog() {
super();
init();
}
private void init() {
this.setModal(true);
this.setSize(new Dimension(100,100));
JButton ok = new JButton("ok");
ok.addActionListener( new ActionListener () {
#Override
public void actionPerformed(ActionEvent arg0) {
result = new DialogResult();
result.value = tf.getText();
setVisible(false);
}
});
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.add(tf);
p.add(ok);
this.add(p);
}
public DialogResult getDialogResult() {
return result;
}
}
}

Having Trouble to use jbutton to open a new window

i modified my code but still faced problem ,i want to MyPanel2 inside open to MyPanel by clicking button , how do i do that , here is my code given which is pop open after clicking button of Myplanel..
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.jpedal.PdfDecoder;
import org.jpedal.examples.viewer.Viewer;
import org.jpedal.gui.GUIFactory;
import org.jpedal.utils.LogWriter;
public class Button extends Viewer {
private MyPanel panel1;
private MyPanel2 panel2;
private void displayGUI() {
JFrame frame = new JFrame("eBookReader Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
panel1 = new MyPanel(contentPane);
contentPane.add(panel1, "Panel 1");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Button().displayGUI();
}
});
}
}
class MyPanel extends JPanel {
private JButton jcomp4;
private JPanel contentPane;
public MyPanel(JPanel panel) {
contentPane = panel;
jcomp4 = new JButton("openNewWindow");
// adjust size and set layout
setPreferredSize(new Dimension(315, 85));
setLayout(null);
jcomp4.setLocation(0, 0);
jcomp4.setSize(315, 25);
jcomp4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelClassName());
} catch (Exception e1) {
LogWriter.writeLog("Exception " + e1
+ " setting look and feel");
}
MyPanel2 a = new MyPanel2();
a.setupViewer();
}
});
add(jcomp4);
}
}
class MyPanel2 extends Viewer {
public MyPanel2() {
// tell user we are in multipanel display
currentGUI.setDisplayMode(GUIFactory.MULTIPAGE);
// enable error messages which are OFF by default
PdfDecoder.showErrorMessages = true;
}
public MyPanel2(int modeOfOperation) {
// tell user we are in multipanel display
currentGUI.setDisplayMode(GUIFactory.MULTIPAGE);
// enable error messages which are OFF by default
PdfDecoder.showErrorMessages = true;
commonValues.setModeOfOperation(modeOfOperation);
}
}
private void displayGUI() {
JFrame frame = new JFrame("eBookReader Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
panel1 = new MyPanel(contentPane);
contentPane.add(panel1, "Panel 1");
frame.setContentPane(contentPane);
// we need to increase the size of the panel so when we switch views we can see the viewer
frame.setPreferredSize(new Dimension(2000, 700));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
Now in the button event handler
jcomp4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelClassName());
} catch (Exception e1) {
LogWriter.writeLog("Exception " + e1
+ " setting look and feel");
}
MyPanel2 a = new MyPanel2();
// inform the viewer of where it is to be displayed
a.setRootContainer(contentPane);
// hide the curently visible panel
MyPanel.this.setVisible(false);
// show the viewer
a.setupViewer();
}
});

Categories