Opening a new JFrame from a Button - java

I want to open a new JFrame by clicking a button (btnAdd); I have tried to create an actionlistener but I am having no luck; the code runs but nothing happens when the button is clicked. The methods in question are the last two in the following code. Any help is much appreciated!
package AdvancedWeatherApp;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionListener;
import weatherforecast.FetchWeatherForecast;
public class MainFrame extends JFrame implements ListSelectionListener {
private boolean initialized = false;
private Actions actions = new Actions();
private javax.swing.JScrollPane jspFavouritesList = new javax.swing.JScrollPane();
private javax.swing.DefaultListModel<String> listModel = new javax.swing.DefaultListModel<String>();
private javax.swing.JList<String> favouritesList = new javax.swing.JList<String>(
listModel);
private javax.swing.JLabel lblAcknowledgement = new javax.swing.JLabel();
private javax.swing.JLabel lblTitle = new javax.swing.JLabel();
private javax.swing.JButton btnAdd = new javax.swing.JButton();
private javax.swing.JButton btnRemove = new javax.swing.JButton();
public void initialize() {
initializeGui();
initializeEvents();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
/**
*
*/
private void initializeGui() {
if (initialized)
return;
initialized = true;
this.setSize(500, 400);
Dimension windowSize = this.getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(screenSize.width / 2 - windowSize.width / 2,
screenSize.height / 2 - windowSize.height / 2);
Container pane = this.getContentPane();
pane.setLayout(new BorderLayout());
setLayout(new BorderLayout());
setTitle("Favourite Weather Locations");
JPanel jpSouth = new JPanel();
jpSouth.setLayout(new FlowLayout());
JPanel jpNorth = new JPanel();
jpNorth.setLayout(new FlowLayout());
JPanel jpCenter = new JPanel();
jpCenter.setLayout(new BoxLayout(jpCenter, BoxLayout.PAGE_AXIS));
JPanel jpEast = new JPanel();
JPanel jpWest = new JPanel();
getContentPane().setBackground(Color.WHITE);
jpEast.setBackground(Color.WHITE);
jpWest.setBackground(Color.WHITE);
jpCenter.setBackground(Color.WHITE);
getContentPane().add(jspFavouritesList);
jpCenter.add(jspFavouritesList);
jspFavouritesList.setViewportView(favouritesList);
favouritesList
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
favouritesList.addListSelectionListener(this);
jpCenter.add(btnAdd);
jpCenter.add(btnRemove);
jpCenter.setAlignmentY(CENTER_ALIGNMENT);
btnAdd.setText("Add Location");
btnAdd.setAlignmentX(Component.CENTER_ALIGNMENT);
btnAdd.setFont(new Font("Calibri", Font.PLAIN, 18));
jpCenter.add(btnRemove);
btnRemove.setText("Remove Location");
btnRemove.setAlignmentX(Component.CENTER_ALIGNMENT);
btnRemove.setFont(new Font("Calibri", Font.PLAIN, 18));
getContentPane().add(jpEast, BorderLayout.EAST);
getContentPane().add(jpWest, BorderLayout.WEST);
getContentPane().add(jpSouth);
jpSouth.add(lblAcknowledgement);
add(lblAcknowledgement, BorderLayout.SOUTH);
lblAcknowledgement.setText(FetchWeatherForecast.getAcknowledgement());
lblAcknowledgement.setHorizontalAlignment(SwingConstants.CENTER);
lblAcknowledgement.setFont(new Font("Tahoma", Font.ITALIC, 12));
getContentPane().add(jpNorth);
jpNorth.add(lblTitle);
add(lblTitle, BorderLayout.NORTH);
lblTitle.setText("Your Favourite Locations");
lblTitle.setHorizontalAlignment(SwingConstants.CENTER);
lblTitle.setFont(new Font("Calibri", Font.PLAIN, 32));
lblTitle.setForeground(Color.DARK_GRAY);
getContentPane().add(jpCenter);
}
private void initializeEvents() {
// TODO: Add action listeners, etc
}
public class Actions implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
command = command == null ? "" : command;
// TODO: add if...if else... for action commands
}
}
public void dispose() {
// TODO: Save settings
// super.dispose();
System.exit(0);
}
public void setVisible(boolean b) {
initialize();
super.setVisible(b);
}
public static void main(String[] args) {
new MainFrame().setVisible(true);
}
public void actionPerformed(ActionEvent evt){
if (evt.getSource() == btnAdd) {
showNewFrame();
//OPEN THE SEARCH WINDOW
}
}
private void showNewFrame() {
JFrame frame = new JFrame("Search Window" );
frame.setSize( 500,120 );
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}

Although you have implemented the actionPerformed method as per the ActionListener interface, you class is not of that that type as you haven't implemented the interface. Once you implement that interface and register it with the JButton btnAdd,
btnAdd.addActionListener(this);
the method will be called.
A more compact alternative might be to use an anonymous interface:
btnAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// handle button ActionEvent & display dialog...
}
});
Side notes:
Using more than one JFrame in an application creates a lot of overhead for managing updates that may need to exist between frames. The preferred approach is to
use a modal JDialog if another window is required. This is discussed more here.

Use this :
btnAdd.addActionListener(this);
#Override
public void actionPerformed(ActionEvent e)
{
MainFrame frame = new MainFrame();
frame.setVisible(true);
}

Type this inside the button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
ActionListener ActList = new ActionListener();
ActList.setVisible(true);
}

see my last line
{
ActList.setVisible(true);
}

Related

Swing window doesn't return value after x time

I'm trying to do a call simulator in Swing and for some reason the window won't budge.
My goal is to open a seperate window that returns true or false if a button is pressed or another has been pressed. The user should have 15 seconds to do something, otherwise it returns false and performs an action.
When it returns, it should finish it's execution. This function is called by another function part of main.
However, due to my lack of experience and idiocy, it doesn't work. Instead, it opens a window (blank) that never closes by itself when it should...
Here's the code:
public static boolean callWindow(Telephone src, Telephone dst) {
Timer t1 = new Timer(15000, e-> {
DateTime date = new DateTime();
Call c = new Call(date, src.getTelephone(), dst.getTelephone(), 0);
dst.addLostCall(c);
});
//Janela para atender
JFrame window = new JFrame();
window.setTitle("Incoming Call");
JLabel telephones = new JLabel();
telephones.setText("From: " + src.getTelephone() + " To: " + dst.getTelephone() );
JButton answerCall = new JButton("Answer");
JButton denyCall = new JButton("Decline");
JLabel status = new JLabel();
answerCall.addActionListener( e -> status.setText("answer") );
denyCall.addActionListener( e -> status.setText("no answer") );
answerCall.setBackground(Color.GREEN);
denyCall.setBackground(Color.RED);
JPanel callInfo = new JPanel();
callInfo.add(telephones);
JPanel callOptions = new JPanel();
callOptions.add(answerCall);
callOptions.add(denyCall);
Container container = window.getContentPane();
container.add(callInfo, BorderLayout.NORTH);
container.add(callOptions);
window.setSize(350,120);
window.setVisible(true);
t1.start();
while (t1.isRunning()) {
if (status.getText().equals("answer")) return true;
if (status.getText().equals("no answer")) return false;
}
return false;
}
I would appreciate to know how this could work and how to despaghettify this horrible code.
I used a JDialog to demonstrate how to close a window after 15 seconds.
Here's the GUI JFrame I created.
Here's the JDialog I created
The JDialog will dispose after 15 seconds. The isAnswered method will return true if the call was answered or false if the call was declined, the JDialog was closed by left-clicking on the X, or when the 15 seconds runs out.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Color;
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.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class JDialogTimedGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JDialogTimedGUI());
}
private JFrame frame;
#Override
public void run() {
frame = new JFrame("JDialog Timed GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(
75, 100, 75, 100));
panel.setPreferredSize(new Dimension(400, 200));
JButton button = new JButton("Open JDialog");
button.addActionListener(new ButtonListener());
panel.add(button);
return panel;
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
IncomingCall ic = new IncomingCall(frame, "Incoming Call",
"555-1212", "555-2323");
System.out.println("Incoming call: " + ic.isAnswered());
}
}
public class IncomingCall extends JDialog {
private static final long serialVersionUID = 1L;
private boolean answered;
private Timer timer;
public IncomingCall(JFrame frame, String title,
String sourcePhone, String destinationPhone) {
super(frame, true);
this.answered = false;
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setTitle(title);
add(createMainPanel(frame, sourcePhone, destinationPhone));
pack();
setLocationRelativeTo(frame);
timer = new Timer(15000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
setVisible(false);
dispose();
timer.stop();
}
});
timer.start();
setVisible(true);
}
private JPanel createMainPanel(JFrame frame,
String sourcePhone, String destinationPhone) {
JPanel panel = new JPanel(new BorderLayout(5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
String s = "From: " + sourcePhone + " To: " + destinationPhone;
JLabel telephones = new JLabel(s);
panel.add(telephones, BorderLayout.BEFORE_FIRST_LINE);
JPanel callOptions = new JPanel();
CallButtonListener listener = new CallButtonListener(this);
JButton answerCall = new JButton("Answer");
answerCall.addActionListener(listener);
answerCall.setBackground(Color.GREEN);
callOptions.add(answerCall);
JButton denyCall = new JButton("Decline");
denyCall.addActionListener(listener);
denyCall.setBackground(Color.RED);
callOptions.add(denyCall);
panel.add(callOptions, BorderLayout.CENTER);
return panel;
}
public void setAnswered(boolean answered) {
this.answered = answered;
}
public boolean isAnswered() {
return answered;
}
}
public class CallButtonListener implements ActionListener {
private IncomingCall incomingCall;
public CallButtonListener(IncomingCall incomingCall) {
this.incomingCall = incomingCall;
}
#Override
public void actionPerformed(ActionEvent event) {
JButton button = (JButton) event.getSource();
if (button.getText().equals("Answer")) {
incomingCall.setAnswered(true);
} else {
incomingCall.setAnswered(false);
}
incomingCall.dispose();
}
}
}

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 dynamically add components to Java JScrollPane

I am trying to make a GUI application in Java but I am having trouble in adding/updating components dynamically in JScrollPane. I have two JPanels (P1 and P2) in which P1 has a form to set parameters for application and the P2 contains some GUI components, which are updated dynamically based on the values in the P1. I need a JScrollPane on P2 to scroll, so I added JScrollPane in P2. I added both P1 and P2 to a main panel "main" and then added the main panel to a frame. But the components are not updated in P2. Can someone suggest what is the problem? I have called revalidate(), repaint() and some other methods but GUI is not updated. Below is a sample code I have written just to illustrate my problem. I need GroupLayout in my application so here I also used GroupLayout
import java.awt.event.ActionEvent;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class JframeExample extends JFrame {
private final JPanel P1;
private final JPanel P2;
private final JPanel main;
private final JScrollPane scrol;
private final JButton jButton;
private final JButton jButton2;
public JframeExample() {
P1 = new JPanel();
P2 = new JPanel();
main = new JPanel();
jButton = new JButton("Add");
jButton2 = new JButton("Remove");
scrol = new JScrollPane();
initialize();
this.add(main);
this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.setSize(400, 400);
this.setVisible(true);
}
public static void main(String[] args) {
JframeExample jframeExample = new JframeExample();
}
private void addPressed(ActionEvent evt) {
System.out.println("Add Pressed");
scrol.add(new JButton());
revalidate();
}
private void removePressed(ActionEvent evt) {
System.out.println("Remove Pressed");
scrol.removeAll();
revalidate();
}
private void initialize() {
GroupLayout layout = new GroupLayout(P1);
P1.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
hGroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
.addComponent(jButton).addComponent(jButton2));
layout.setHorizontalGroup(hGroup);
GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
vGroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(jButton))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(jButton2));
layout.setVerticalGroup(vGroup);
P2.add(scrol);
jButton.addActionListener((ActionEvent evt) -> {
addPressed(evt);
});
jButton2.addActionListener((ActionEvent evt) -> {
removePressed(evt);
});
GroupLayout layoutMain = new GroupLayout(main);
main.setLayout(layoutMain);
layoutMain.setAutoCreateGaps(true);
layoutMain.setAutoCreateContainerGaps(true);
layoutMain.setHorizontalGroup(layoutMain.createSequentialGroup()
.addComponent(P1).addComponent(P2));
layoutMain.setVerticalGroup(layoutMain
.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(P1)
.addComponent(P2));
}
}
Wrapping P2 inside JScrollPane also does not work.
Yes it does, because that's the way it work. If you take the time to read through the How to use scroll panes, examine the examples and maybe even consult the JavaDocs it would provide you with the basic information you'd need to get you UI up and running.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class JframeExample extends JFrame {
private final JPanel P1;
private final JPanel P2;
private final JPanel main;
private final JScrollPane scrol;
private final JButton jButton;
private final JButton jButton2;
public JframeExample() {
P1 = new JPanel();
P2 = new JPanel();
main = new JPanel();
jButton = new JButton("Add");
jButton2 = new JButton("Remove");
scrol = new JScrollPane(P2);
initialize();
this.add(main);
this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.setSize(400, 400);
this.setVisible(true);
}
public static void main(String[] args) {
JframeExample jframeExample = new JframeExample();
}
private void addPressed(ActionEvent evt) {
System.out.println("Add Pressed");
P2.add(new JButton());
revalidate();
}
private void removePressed(ActionEvent evt) {
System.out.println("Remove Pressed");
P2.removeAll();
revalidate();
}
private void initialize() {
main.setLayout(new GridLayout(1, 2));
main.add(P1);
main.add(scrol);
jButton.addActionListener((ActionEvent evt) -> {
addPressed(evt);
});
jButton2.addActionListener((ActionEvent evt) -> {
removePressed(evt);
});
P1.add(jButton);
P1.add(jButton2);
}
}
Word of warning GroupLayout really isn't meant for hand coding, it's really designed for UI editors.

JButton Wont Display JPanel

I want to call My JPanel with button. My Jpanel is actually a sub JPanel from main Panel with card layout.
to do that, i am using card layout api method HERE to show the JPanel after a button was clicked.
JButton btnCallPanel1 = new JButton("Call PanelOne");
btnCallPanel1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout card = (CardLayout)mainPanel.getLayout();
card.show(mainPanel, "PanelOne"); //call Panel One
}
output :
nothing appear, panel not called and no error pop out.
My Code is HERE
package wan.dev.sample.cardlayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class HowToUseCardLayout {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
HowToUseCardLayout window = new HowToUseCardLayout();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public HowToUseCardLayout() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 688, 358);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel mainPanel = new JPanel();
mainPanel.setBounds(0, 0, 672, 260);
frame.getContentPane().add(mainPanel);
mainPanel.setLayout(new CardLayout(0, 0));
JPanel PrePanel = new JPanel();
mainPanel.add(PrePanel, "name_246268073832057");
PrePanel.setLayout(null);
JLabel lblPanel_1 = new JLabel("Pre Panel");
lblPanel_1.setBounds(280, 115, 57, 20);
PrePanel.add(lblPanel_1);
JPanel panelOne = new JPanel();
mainPanel.add(panelOne, "name_246268067657434");
panelOne.setLayout(null);
JLabel lblPanel = new JLabel("panel 1");
lblPanel.setBounds(279, 118, 46, 14);
panelOne.add(lblPanel);
JButton btnPan1 = new JButton("Call PanelOne");
btnPan1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout card = (CardLayout) mainPanel.getLayout();
card.show(mainPanel, "PanelOne");
}
});
btnPan1.setBounds(262, 286, 144, 23);
frame.getContentPane().add(btnPan1);
}
}
ANSWER
The reason i cant call my panel because i did not call it by using identifier.
i have to give identifier name to my desire jpanel and use the identifier on my cardLayout.show(..)
Public Static final String PANEL_ONE = "panel one"; //Name of JPanel Identifier
//add panel to main panel and declare panelOne identifier
mainPanel.add(panelOne, PANEL_ONE); //PANEL_ONE function like
//an identifier
JButton btnCallPanel1 = new JButton("Call PanelOne");
btnCallPanel1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout card =
(CardLayout)mainPanel.getLayout();
card.show(mainPanel, PANEL_ONE); //call panelOne using PANEL_ONE
//instead of JPanel name
}
As I suspected — You're calling the CardLayout.show(...) method with the String parameter "PanelOne", but yet you've not added any component to the CardLayout-using container using this same String, so it makes sense that it won't work. Solution: don't do this. Use the Same String that you add the component to the CardLayout using container as the one that you use to display it.
i.e., If you want to display container foo and use the String "bar" to add it to the CardLayout-using container, then you must pass "bar" into the CardLayout's show(...) method. Again, use String constants for this so that you reduce the chances of messing up.
Other issues: You're using null layout and setBounds — Don't. Doing this makes for very inflexible GUI's that while they might look good on one platform look terrible on most other platforms or screen resolutions and that are very difficult to update and maintain.
e.g.,
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class CardLayoutFoo extends JPanel {
public static final String BAR = "bar";
public static final String BUTTON_PANEL = "button panel";
private CardLayout cardlayout = new CardLayout();
public CardLayoutFoo() {
setLayout(cardlayout);
JLabel fooLabel = new JLabel("Foo", SwingConstants.CENTER);
add(fooLabel, BAR); // added using String constant, BAR
JButton showFooBtn = new JButton(new AbstractAction("Show Foo") {
#Override
public void actionPerformed(ActionEvent evt) {
// use same String, BAR, to get the fooLabl shown
cardlayout.show(CardLayoutFoo.this, BAR);
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(showFooBtn);
add(btnPanel, BUTTON_PANEL);
cardlayout.show(this, BUTTON_PANEL);
}
private static void createAndShowGui() {
CardLayoutFoo mainPanel = new CardLayoutFoo();
JFrame frame = new JFrame("CardLayoutFoo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Adding Text In a New Window

I'm in a bit of a situation here.I'm making a new program, when you click on the menu bar it opens a new window for the Licence, now here is the problem, how would I add text into that new window, here is my code for the new window:
JFrame frame = new JFrame("Licence");
frame.setSize(500,120);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
I know this is a easy question, I just can't think of the correct code for it.
You can try something like
JDialog dialog = new JDialog(your_frame_reference, "Licence");
dialog .setModal(true);
dialog .setLocationRelativeTo(null);
dialog. getContentPane().add(new JLabel(your_text);
dialog .setVisible(true);
You can use label
JFrame frame = new JFrame("Licence");
JLabel label = new JLabel("Text-Only Label");
label.setFont(new Font("Serif", Font.PLAIN, 36));
frame.add(label);
You can add text by creating JLabels like so:
JLabel label = new JLabel("Hello World");
This can then be added to your JFrame.
Try this Example
import java.awt.BorderLayout;
import java.awt.Window;
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.SwingUtilities;
public class TestDialog {
protected static void initUI() {
JPanel pane = newPane("Label in frame");
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane);
frame.pack();
frame.setVisible(true);
}
public static JPanel newPane(String labelText) {
JPanel pane = new JPanel(new BorderLayout());
pane.add(newLabel(labelText));
pane.add(newButton("Open dialog"), BorderLayout.SOUTH);
return pane;
}
private static JButton newButton(String label) {
final JButton button = new JButton(label);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window parentWindow = SwingUtilities.windowForComponent(button);
JDialog dialog = new JDialog(parentWindow);
dialog.setLocationRelativeTo(button);
dialog.setModal(true);
dialog.add(newPane("Label in dialog"));
dialog.pack();
dialog.setVisible(true);
}
});
return button;
}
private static JLabel newLabel(String label) {
JLabel l = new JLabel(label);
l.setFont(l.getFont().deriveFont(24.0f));
return l;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
initUI();
}
});
}
}

Categories