Switch Card Layout in Java [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Here's how to change card layouts from a menu item. I asked how to do it earlier but no luck. I have figured out the answer so here's what it does; 1. Builds your main frame when running the java file. Then in the menu bar it allows you to switch JPanels (For this example welcome is a different public class inside of a package.) 2. Now you can build as many public classes as you want and still be able to go to that JPanel.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class ArmyQuestions {
CardLayout cards;
JPanel cardPanel;
public static void main(String[] args) throws IOException {
//Use the event dispatch thread for Swing components
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new ArmyQuestions();
}
});
}
public ArmyQuestions()
{
JFrame mainFrame = new JFrame();
//make sure the program exits when the frame closes
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setTitle("Army Questions");
mainFrame.setSize(797,510);
//This will center the JFrame in the middle of the screen
mainFrame.setLocationRelativeTo(null);
mainFrame.getContentPane().setLayout(new BorderLayout());
//Adds a menu bar
JMenuBar menuBar = new JMenuBar();
mainFrame.getContentPane().add(menuBar, BorderLayout.NORTH);
//Adds a menu option
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
//Adds an item to the menu option
JMenuItem mntmNew = new JMenuItem("New");
mnFile.add(mntmNew);
mntmNew.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
cards.show(cardPanel, "Welcome");
}
});
//Adds cardpanel to getContentPane
cards = new CardLayout();
cardPanel = new JPanel();
cardPanel.setLayout(cards);
mainFrame.getContentPane().add(cardPanel,BorderLayout.CENTER);
//Adds a JPanel to your cardpanel
Welcome welcome = new Welcome();
cardPanel.add(welcome, "Welcome");
mainFrame.setVisible(true);
}
}

Two things I see going on.
You have SuggestedQuesion_2 declared globally then you create a whole new one in you method. JPanel SuggestedQuestion_2 = new JPanel();
I see a CardLayout for your Welcome - Welcome.setLayout(new CardLayout(0, 0));, but not for you SuggestedQuestion_2. Yet you're trying to access SuggestedQuestions's CardLayout
You should learn how to post an SSCCE So it is easier for us to see the problem. Also, in trying to recreate the problem into a smaller, runnable version you sometimes figure out the solution yourself.
And please follow Java naming convention using lowercase letters first letter of reference variable

Related

JPanel not showing inside JFrame in Java

I know this question has been asked a lot and I have done my research but still can not find anything. Below is proof of this before anyone gets upset:
I found this link:
https://coderanch.com/t/563764/java/Blank-Frame-Panel
and this:
Adding panels to frame, but not showing when app is run
and this:
Why shouldn't I call setVisible(true) before adding components?
and this:
JPanel not showing in JFrame?
But the first question says use repaint which I tried with no fix and the second and third to last questions talk about putting setVisible after components added which I have.
The last one talks about making the users JPanelArt a extension (done so) of JPanel instead of JFrame and not to make a frame in a frame constructor (also have not done)
When ever I run this I just get a blank frame, as if the panel was never added in.
I apologise if I have missed something in those links. Anyway below is my classes:
GUI.java (extends JFrame)
package javaapplication2;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GUI extends JFrame{
public GUI(String name) {
super(name);
getContentPane().setLayout(null);
JPanel myPanel1 = new GUIPanel();
myPanel1.setLocation(20, 20);
getContentPane().add(myPanel1);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setResizable(true);
}
public static void main(String[] args) {
JFrame frame = new GUI("Game");
frame.setVisible(true);
}
}
GUIPanel.java (extends JPanel)
package javaapplication2;
import java.awt.*;
import javax.swing.*;
public class GUIPanel extends JPanel {
JButton start;
JButton inspect1;
JButton inspect2;
JButton inspect3;
JButton suspect;
public GUIPanel() {
setLayout(new BorderLayout());
start = new JButton("Start Game");
inspect1 = new JButton("Inspect 1");
inspect2 = new JButton("Inspect 2");
inspect3 = new JButton("Inspect 3");
suspect = new JButton("Choose Suspect");
add(start, BorderLayout.WEST);
add(inspect1, BorderLayout.WEST);
add(inspect2, BorderLayout.WEST);
add(inspect3, BorderLayout.WEST);
add(suspect, BorderLayout.WEST);
}
}
I know it is very simple, but that is because I am following a tutorial from my lecturer to get the hang of things as I previously used a GUI builder which someone in this community pointed out to me is not good to start with (very correct!)
The issue lies in your GUI class when you call getContentPane().setLayout(null). Because of this method call, your JFrame is not displaying anything. If you remove it, your elements should show up.
I also noticed that you were setting each JButton to have a constraint of BorderLayout.WEST. This will most likely put your JButtons on top of each other and render only one of them.

I created my GUI in a GUI class' constructor. How would I access its Frames, Panels etc. from another class?

First of all, this is a more specific question than it seems to be. To start off: I am currently doing a small application with a rather small GUI, so I decided to make a GUI class, and initialize my whole GUI in this constructor.
This would look like this:
public class GUI extends JFrame{
public GUI{
//Initialize GUI here, including its Frames, Panels, Buttons etc.
}
}
How can I now access the GUIs frame etc. from an external class? If I would create an object of the GUI class, I would simply duplicate my GUI window. I did not come across any other ideas than making the frame, panel and so on static.
I'm somewhat lost right now. Also I'm pretty sure that I am not thinking the right way into this case, but I need someone to point me to the right direction. If someone could help me out, I would be very thankful.
First of all, using static is the worst solution possible, even if your GUI class is a singleton (buf if it is, at least it will work fine).
Why don't you simply create getters and/or setters ? And finally, it is usually not normal that external classes need to access the components of another graphic class. You should wonder if your design is the most fitted for your needs.
Here's a simple GUI to change the background color of a JPanel with a JButton. Generally, this is how you construct a Swing GUI.
package com.ggl.testing;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ChangeDemo implements Runnable {
private boolean isYellow;
private JFrame frame;
public static void main(String[] args) {
SwingUtilities.invokeLater(new ChangeDemo());
}
#Override
public void run() {
frame = new JFrame("Change Background Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
JPanel namePanel = new JPanel();
JLabel nameLabel = new JLabel(
"Click the button to change the background color");
nameLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
namePanel.add(nameLabel);
mainPanel.add(namePanel);
final JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBackground(Color.YELLOW);
isYellow = true;
JButton changeButton = new JButton("Change Color");
changeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
isYellow = !isYellow;
if (isYellow) buttonPanel.setBackground(Color.YELLOW);
else buttonPanel.setBackground(Color.RED);
}
});
buttonPanel.add(changeButton);
mainPanel.add(buttonPanel);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
You don't access the Swing components of the GUI from other classes. You create other classes to hold the values of the GUI.
Generally, you use the model / view / controller pattern to construct a Swing GUI. That way, you can focus on one part of the GUI at a time.
Take a look at my article, Java Swing File Browser, to see how the MVC pattern works with a typical Swing GUI.
You don't need to make it static or to create a new JFrame object every time.
Have a look at this simple code :
class UseJFrame {
public static void main(String...args) {
Scanner sc = new Scanner(System.in);
JFrame frame = new GUI();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
System.out.println("Press E to exit");
String ip;
while(true) {
System.out.println("Show GUI (Y/N/E)? : ");
ip = sc.nextLine();
if(ip.equalsIgnoreCase("y") {
frame.setVisible(true);
} else if(ip.equalsIgnoreCase("n") {
frame.setVisible(false);
} else { // E or any other input
frame.dispose();
}
}
}
}
Note : Don't make GUI visible through constructor or it will show window at the very starting of creation of JFrame object.
If you want to use the same JFrame object at other places too then pool architecture would be better approach.

How to put button in top right og jpane [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
According to your instruction i decided to use GridBagLayout, but i also face a problem in positioning buttons in a panel the button expected to be at top right, But it is displayed in the center, Please tell me what is the problem in my code`
import java.awt.ComponentOrientation;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
public class Test extends JFrame {
private JPanel contentPane;
private JButton button2;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 573, 410);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new GridBagLayout());
contentPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
setContentPane(contentPane);
button2 = new JButton("button2");
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
contentPane.add(button2, c);
}
}
this the the output
http://postimg.org/image/bhnzskznj/
Since the answer just asks for a Layout - it's layout recommendation time!
My favourite - http://www.miglayout.com/ which satisfied all my layout needs for my last Swing project. wrap, span x and center layout arguments should be all that is needed to do what your picture does.
This is exactly why absolute layouts are not recommended.
Your best approach will be to use something like GridBagLayout which will position the elements and then let them move as the screen resizes and reshapes.
There are plenty of good documentation and tutorials online for GridBagLayout that will get you started. You can also use tools built into some IDEs (NetBeans has a good one for example) to let you lay things out graphically.

Simple Jframe with a combobox and a textfield and a result in a label [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am a Java newbie so this question maybe foolish for some. I am using Eclipse with the swing window builder, but i can't figure out how to make my Jframe work.
What i want to achieve is rather simple.
I want a combobox with a number of options (lateron two columns, but i start with one), representing a bankcode.
A textbox for entering a bankaccountnumber.
a button that needs to use the selected value from the box and the accountnumber from the textbox to call a method createIban(code,number).
This method returns a String with the full IBAN.
I want this string presented in a label or something (maybe also copied to the clipboard or some).
I hope someone can help me to get further in this quest.
Here you have a code to begin with... but you should check some tutorials and google a little bit to know how to make it prettier.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test extends JPanel {
private static JComboBox comboBox;
private static JTextField textField;
// Create a form with the fields
public Test() {
super(new BorderLayout());
// Panel for the labels
JPanel labelPanel = new JPanel(new GridLayout(2, 1)); // 2 rows 1 column
add(labelPanel, BorderLayout.WEST);
// Panel for the fields
JPanel fieldPanel = new JPanel(new GridLayout(2, 1)); // 2 rows 1 column
add(fieldPanel, BorderLayout.CENTER);
// Combobox
JLabel labelCombo = new JLabel("Bank Code");
// Options in the combobox
String[] options = { "Option1", "Option2", "Option3", "Option4", "Option15" };
comboBox = new JComboBox(options);
comboBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Do something when you select a value
}
});
// Textfield
JLabel labelTextField = new JLabel("Bank account number");
textField = new JTextField();
// Add labels
labelPanel.add(labelCombo);
labelPanel.add(labelTextField);
// Add fields
fieldPanel.add(comboBox);
fieldPanel.add(textField);
}
public static void main(String[] args) {
final Test form = new Test();
// Button submit
JButton submit = new JButton("Submit Form");
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
createIban((String) comboBox.getSelectedItem(), textField.getText());
}
});
// Frame for our test
JFrame f = new JFrame("Text Form Example");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(form, BorderLayout.NORTH);
// Panel with the button
JPanel p = new JPanel();
p.add(submit);
f.getContentPane().add(p, BorderLayout.SOUTH);
// Show the frame
f.pack();
f.setVisible(true);
}
private static void createIban(String selectedItem, String text) {
// Do stuff with your data
System.out.println("Im in createIban with the values: " + selectedItem + " and " + text);
}
}

Dynamically adding toolbars in Java Swing GUI

I am developing a Java Desktop Application. In the GUI, I want that user can add as many toolbars dynamically as he wants. To implement this, the following are the things that I have done already:
Have taken a mainPanel and set its layout as BorderLayout
Then taken a topPanel and added it to the mainPanel's BorderLayout.NORTH
set the topPanel's layout as BoxLayout
Then taken 5 panels named toolbar1Panel, toolbar2Panel, ....
Afterthat, have added one toolbar to each of the toolbarPanel created in the previous steps.
Have added only one toolbarPanel i.e toolbar1Panel on the topPanel
Now there is a button named "Add" on the first toolbar which is added on the "toolbar1Panel" which in turn is added to the topPanel.
Now I have implemented the "actionPerformed()" method of the above "Add" button as follows:
// to add second toolbar Panel to the topPanel dynamically
topPanel.add(toolbar2Panel);
But the problem is that it is not working. Means there is no toolbar added to the topPanel.
Is there anything which I am missing.
The code is Netbeans Generated so I think it would only add mess for others, that's why I haven't pasted any code here.
After adding another toolbar to the BoxLayout, you may need to (re|in)?validate the panel.
I've done this repeatedly but I can't understand the logic behind the 3 or so method calls; so I just try them until I hit on the one that works:
topPanel.validate();
topPanel.invalidate();
topPanel.revalidate();
topPanel.layout();
(at least) one of those should force your GUI to re-calculate its layout, making the north panel larger and thus showing the 2nd (and successive) toolbar(s) you've added.
Without specifying the layout for the top panel, it might be assuming the incorrect one.
Adding two toolbar panels to it might just be replacing the first with the second, or ignoring the second.
Just for testing set the topPanel's layout to FlowLayout and try again.
I think you are trying to do too much before testing. the way I would approach this is to start with something very simple, for example one panel, one static label. When that appears as you expect add a toolbar with a menu item. Does that work. Then incrmentally add the pieces.
Quite likely you'll have problems with a simple case and can then figure it out, or you'll have a simple case to post here.
Alterntively, as starting point pinck some working example from the net. Cut it down and then build up to your case.
Does it help ?
Is it what you want to achieve ?
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
public class AddingToolbars {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
AddingToolbars me = new AddingToolbars();
me.initGui();
}
});
}
private JPanel topPanel;
private JPanel mainPanel;
private JFrame frame;
private void initGui() {
frame = new JFrame();
mainPanel = new JPanel(new BorderLayout());
frame.setContentPane(mainPanel);
topPanel = new JPanel();
BoxLayout bLayout = new BoxLayout(topPanel,BoxLayout.Y_AXIS);
topPanel.setLayout(bLayout);
mainPanel.add(topPanel,BorderLayout.NORTH);
JButton addButton = new JButton("Add toolbar");
mainPanel.add(addButton,BorderLayout.CENTER);
addButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
addNewToolBar();
}
});
frame.setSize(500,500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
protected void addNewToolBar() {
JToolBar tb = new JToolBar();
tb.add(new JButton("b1"));
tb.add(new JButton("b2"));
tb.add(new JButton("b3"));
topPanel.add(tb);
mainPanel.validate();
}
}

Categories

Resources