Reusing a Button in Java Makes Nothing Display - java

I am really new to GUI programming in Java so please forgive me if this code is really basic. In short, I want to have 2 panels that are the same design. After I press the "A" button on the panel 1, I want to make panel 2 appear with the same design. Making the GUI efficient or pretty doesn't currently matter to me. I just want it to work. I have parts of the code listed below.
JButton buttonA = new JButton("a");
JButton buttonB = new JButton("b");
JButton buttonC = new JButton("c");
JButton buttonD = new JButton("d");
JPanel pan1 = new JPanel();
JPanel pan2 = new JPanel();
setTitle ("Test");
setSize (640, 640);
setResizable(false);
GridLayout grid1 = new GridLayout();
setLayout (grid1);
FlowLayout flow1 = new FlowLayout();
pan1.setLayout (flow1);
pan1.add(buttonA);
pan1.add(buttonB);
pan1.add(buttonC);
pan1.add(buttonD);
buttonA.addActionListener(this);
buttonB.addActionListener(this);
buttonC.addActionListener(this);
buttonD.addActionListener(this);
FlowLayout flow2 = new FlowLayout();
pan2.setLayout (flow2);
pan2.add(buttonA);
pan2.add(buttonB);
pan2.add(buttonC);
pan2.add(buttonD);
add(pan1);
add(pan2);
pan1.setVisible(true);
pan2.setVisible(false);
setVisible(true);
public void actionPerformed(ActionEvent event) {
if (command.equals("a")){//i want to show the panel 2 after button a is pressed
System.out.println("HelloA");
pan1.setVisible(false);
pan2.setVisible(true);
}
Currently, it just shows nothing in the window. Any help guys?

Short answer is, you can't.
Long answer is, a component can only reside on a single parent. Adding a component to a second container will automatically remove it from the first container before its added to the new one.
Instead, you will need to create individual buttons for both containers.
Also, understand that BorderLayout can't support what you're trying to do, it will only manage one component at a time (in each of the 5 available positions)
A better solution would be to make use of the CardLayout which is designed to facilitate the action you are trying to achieve

Related

Create a blue colored rectangular java bean [duplicate]

public void start_Gui() {
JFrame window = new JFrame("Client Program");
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
window.setContentPane(panel);
panel.setLayout(new GridLayout(1,2));
JLabel leftside = new JLabel();
leftside.setLayout(new GridLayout(2, 1));
JTextArea rightside = new JTextArea();
rightside.setEditable(false); //add scroll pane.
rightside.setBorder(BorderFactory.createLineBorder(Color.BLACK));
rightside.setLayout(new FlowLayout());
JTextArea client_text_input = new JTextArea();
client_text_input.setBorder(BorderFactory.createLineBorder(Color.BLACK));
leftside.add(client_text_input);
JLabel buttons_layer = new JLabel();
JButton login = new JButton("Login");
JButton logout = new JButton("Logout");
buttons_layer.setBorder(BorderFactory.createLineBorder(Color.BLACK));
buttons_layer.setLayout(new GridLayout(2, 1));
buttons_layer.add(login);
buttons_layer.add(logout);
leftside.add(buttons_layer);
panel.add(leftside);
panel.add(rightside);
window.setSize(300, 400);
window.setResizable(false);
window.setVisible(true);
}
I am working on a simple java chat client gui application. (the server etc, is done by others).
It is not a big project, but my only problem is that whatever I do to try to resize any components on the above GUI, won't work.
For example:
JTextArea client_text_input = new JTextArea();
client_text_input.setSize(100,200);
Won't work.
Thanks for the help.
In Swing, you have two options for layout: do everything manually or let a LayoutManager handle it for you.
Calling setSize() will only work when you're not using a LayoutManager. Since you're using a GridLayout you'll have to use other ways to specify what you want.
Try calling setPreferredSize() and setMinimumSize().
Two things - firstly you should be setting the preferredSize of the scrollpane, but secondly, trying to resize it inside the componentResized handler isn't a very effective technique because the 'resized' events aren't continuous.
check resizing text area in a JFrame
but setXxxSize (for ContainersChilds) works as chaims if you change from setSize() (for TopLayoutContainer) to setPreferredSize() and you have to call pack() before setVisible()

GUI, JComboBox and opening a new window

I am new to Java and especially new to GUI and it's super confusing to me right now.
I'm making a program for class that is supposed to have a menu (JComboBox I'm assuming) that opens a new window when an option is selected. I am just working on the first option where you click "The Matrix" and a new window pops up with two buttons called "Red Pill" & "Blue Pill" and thats where I've hit a wall.
I got to the point where I am able to create a new window (not sure if this is even the right route to take for opening the new window) but, When I try to add Buttons to the new pop up window nothing shows up....
Thanks for any help or pointers in the right direction!
public class MultiForm extends JFrame{
private JComboBox menu;
private JButton bluePill;
private JButton redPill;
private static String[] fileName = {"", "The Matrix", "Another Option"};
public MultiForm() {
super("Multi Form Program");
setLayout(new FlowLayout());
menu = new JComboBox(fileName);
add(menu);
TheHandler handler = new TheHandler();
menu.addActionListener(handler);
}
private class TheHandler implements ActionListener{
public void actionPerformed(ActionEvent event) {
********************************************************************
//Create a new window when "The Matrix" is clicked in the JCB
JFrame newFrame = new JFrame();
JPanel panel = new JPanel();
newFrame.setLayout(new FlowLayout());
newFrame.setSize(500, 300);
newFrame.setDefaultCloseOperation(newFrame.EXIT_ON_CLOSE);
Icon bp = new ImageIcon(getClass().getResource("Blue Pill.png"));
bluePill = new JButton("Blue Pill", bp);
newFrame.add(bluePill);
Icon rp = new ImageIcon(getClass().getResource("Red Pill.png"));
redPill = new JButton("Red Pill", rp);
newFrame.add(redPill);
add(panel);
newFrame.setVisible(true);
}
}
public static void main(String[] args) {
MultiForm go = new MultiForm();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(400, 200);
go.setVisible(true);
}
}
I tried doing newFrame.add(BluePill) and it created a button that was the size of the entire window and it would not allow me to add both buttons that way
That's because the frame uses a BorderLayout by default. Unless you specify otherwise, the component's will be added to the CENTER position, BUT, BorderLayout will only allow a single component to be managed at each of the it's five available positions, so you are only seeing the last component you added.
See How to Use BorderLayout for more details
so I figured that wasn't the correct way
It's the right approach, you just need to use a layout manager which can accommodate more components or change the position which you are adding the buttons
In this little example, I've just use a FlowLayout, but you can use what ever is going to give you the effect you desire
JFrame newFrame = new JFrame();
newFrame.setLayout(new FlowLayout());
newFrame.setDefaultCloseOperation(newFrame.EXIT_ON_CLOSE);
bluePill = new JButton("Blue Pill");
newFrame.add(bluePill);
redPill = new JButton("Red Pill");
newFrame.add(redPill);
newFrame.pack();
newFrame.setVisible(true);
As a general rule of thumb, I don't like adding components like this directly to a top level container, I prefer to use a intermediate container, like a JPanel, this gives me more possibilities for re-use, but that's me.
You should also only make the frame visible when it's actually ready, otherwise you may find that some times, the components won't show up
See Laying Out Components Within a Container for more details
You are not using the getContentPane() method from the new JFrame.
You have to actually use getContentPane() first because you're not adding any component to the JFrame itself but to an intermediate "panel".
JFrame newFrame = new JFrame();
JPanel panel = new JPanel();
newFrame.setSize(300, 200);
newFrame.setDefaultCloseOperation(newFrame.EXIT_ON_CLOSE);
bluePill = new JButton("Blue Pill");
panel.add(bluePill);
redPill = new JButton("Red Pill");
panel.add(redPill);
newFrame.getContentPane().add(panel);
newFrame.setVisible(true);
You'll have to add a Layout to the JPanel or/and the JFrame and play with the sizes of the component but with this you're on the right path.
I always put the setVisible method a the end, after adding all the components to the frame.
You made some mistakes.
add(bluePill);
will not do what you want, even if it would, it would still be wrong.
(sounds weird, but I'll explain it)
First the "right" way to do it:
//Create a new window when "The Matrix" is clicked in the JCB
JFrame newFrame = new JFrame();
newFrame.setSize(300, 200);
newFrame.setDefaultCloseOperation(newFrame.EXIT_ON_CLOSE);
bluePill = new JButton("Blue Pill");
newFrame.getContentPane().add(bluePill);
redPill = new JButton("Red Pill");
newFrame.getContentPane().add(redPill);
newFrame.setVisible(true);
Notice I added "newFrame", because you were calling the method of MultiForm.
That's because "add()" is the same as "this.add()" and "this" points to MultiForm. Check it with this line if you want:
System.out.println(this.toString());
The "getContentPane()" is best explained with this image:
You were adding it directly to the JFrame (I don't even know what exactly happens then).
It is also good practice to set the frame visible when it is ready to be visible. Your frame did not contain anything when you made it visible.
Now to the JPanel. A JPanel can hold some elements like JButton,etc. and it can also have a layout. Since you didn't use the JPanel at all, i removed the line from your code. You can still add the JPanel to your ContentPane and add a Layout to the JPanel. (You can also add JPanels to JPanels to create complex layouts)
I hope this was clear for you.

Which Layout should be used?

I'm kind of new to the whole "how to arrange your components" thing in JAVA and I couldn't figure out how to realise the following JFrame (I can't post images so I just put the link)
I tried to be as precise as possible about what I already did.
I would like your advice about how to arrange the green part.
Thanks!
EDIT: as some people rightfully said, I didn't put the code of what I did. Here it is:
public Frame(){
this.setTitle("Small application");
this.setSize(445, 500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setVisible(true);
this.setResizable(false);
JPanel container = new JPanel();
container.setLayout(new BorderLayout());
//Title
JLabel title = new JLabel("Welcome to this application");
title.setHorizontalAlignment(JLabel.CENTER);
title.setPreferredSize(new Dimension(200,50));
title.setFont(new Font("Courrier",Font.BOLD,20));
container.add(title, BorderLayout.NORTH);
//Center part
JPanel centerPart = new JPanel();
JLabel cell1 = new JLabel("Enter all measurements:");
cell1.setPreferredSize(new Dimension(150,20));
JLabel cell2 = new JLabel("Please, select the files...");
cell2.setPreferredSize(new Dimension(150,20));
cell2.setBackground(Color.white);
cell2.setBorder(BorderFactory.createLineBorder(Color.black));
cell2.setOpaque(true);
JButton cell3 = new JButton("Browse");
cell3.setPreferredSize(new Dimension(100,20));
centerPart.add(cell1);
centerPart.add(cell2);
centerPart.add(cell3);
container.add(centerPart, BorderLayout.CENTER);
/*
* I need your help here :)
* I can't figure out how to put the image and the text next to it
*/
//Bottom part
JPanel bottom = new JPanel();
JButton graph = new JButton("Graph");
JButton exit = new JButton("Exit");
bottom.add(graph);
bottom.add(exit);
container.add(bottom, BorderLayout.SOUTH);
this.setContentPane(container);
}
For most practical cases, you use multiple, nested containers, with a LayoutManager suited to the layout within each container.
Each LayoutManager does one specific job, in practice you often want differnt regions of a UI layouted in different ways. So for each region use a separate Container (e.g. JPanel) and set a LayoutManager that suits your layout requirements.
The big hurdle for beginners seems to be to get the point that LayoutManagers can (and often must) be used with nested containers.
Try using a JPanel
Create the JPanel
Place your JPanel into your JFrame
Position the labels, button, textfield onto the newly created JPanel.
It should do the trick. and it is pretty basic. You should be able to do the code on your own!

How to put 6 same sized JButtons into JPanel?

I am trying to put into my JPanel 6 JButtons in such a way that there will be 3 JButtons in one line and beneath another 3 JButtons. Since I know that explicitly JPanel works with Flow Layout Manager, I got such an idea:
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.getContentPane().add(panel);
JButton button1 = new JButton();
JButton button2 = new JButton();
JButton button3 = new JButton();
JButton button4 = new JButton();
JButton button5 = new JButton();
JButton button6 = new JButton();
button1.setSize((panel.WIDTH)/3,(panel.HEIGHT)/2);
button2.setSize((panel.WIDTH)/3,(panel.HEIGHT)/2);
button3.setSize((panel.WIDTH)/3,(panel.HEIGHT)/2);
button4.setSize((panel.WIDTH)/3,(panel.HEIGHT)/2);
button5.setSize((panel.WIDTH)/3,(panel.HEIGHT)/2);
button6.setSize((panel.WIDTH)/3,(panel.HEIGHT)/2);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
panel.add(button6);
Unfortunately, this does not work, I can not succeed in changing the size of the button. Does anybody have an idea? Thank you so much.
this is job for GridLayout
override getPreferredSize for JPanel
call JFrame.pack(); before JFrame.setVisible(true);
see Initial Thread
You should use a GridLayout for that, if you want more control you can also use GridBagLayout.
If you do not want to use any layout manager, then first make frame.setLayout(null) and also use button1.setBounds(x,y,width,height) for every button instead of setSize(). Lastly frame.setVisible(true).
You should check out some other Layouts, such as the GridLayout, or the GridBagLayout.
This tutorial, from Oracle, might prove useful.
However, when working with Layouts, use setPreferredSize(Dimension size), instead of setSize.
GridLayout is a good idea but if you don't plan to add more components to the panel or only in group of 3, SpringLayout with its makeGrid methods would do the trick too.

set size wont work in java

public void start_Gui() {
JFrame window = new JFrame("Client Program");
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
window.setContentPane(panel);
panel.setLayout(new GridLayout(1,2));
JLabel leftside = new JLabel();
leftside.setLayout(new GridLayout(2, 1));
JTextArea rightside = new JTextArea();
rightside.setEditable(false); //add scroll pane.
rightside.setBorder(BorderFactory.createLineBorder(Color.BLACK));
rightside.setLayout(new FlowLayout());
JTextArea client_text_input = new JTextArea();
client_text_input.setBorder(BorderFactory.createLineBorder(Color.BLACK));
leftside.add(client_text_input);
JLabel buttons_layer = new JLabel();
JButton login = new JButton("Login");
JButton logout = new JButton("Logout");
buttons_layer.setBorder(BorderFactory.createLineBorder(Color.BLACK));
buttons_layer.setLayout(new GridLayout(2, 1));
buttons_layer.add(login);
buttons_layer.add(logout);
leftside.add(buttons_layer);
panel.add(leftside);
panel.add(rightside);
window.setSize(300, 400);
window.setResizable(false);
window.setVisible(true);
}
I am working on a simple java chat client gui application. (the server etc, is done by others).
It is not a big project, but my only problem is that whatever I do to try to resize any components on the above GUI, won't work.
For example:
JTextArea client_text_input = new JTextArea();
client_text_input.setSize(100,200);
Won't work.
Thanks for the help.
In Swing, you have two options for layout: do everything manually or let a LayoutManager handle it for you.
Calling setSize() will only work when you're not using a LayoutManager. Since you're using a GridLayout you'll have to use other ways to specify what you want.
Try calling setPreferredSize() and setMinimumSize().
Two things - firstly you should be setting the preferredSize of the scrollpane, but secondly, trying to resize it inside the componentResized handler isn't a very effective technique because the 'resized' events aren't continuous.
check resizing text area in a JFrame
but setXxxSize (for ContainersChilds) works as chaims if you change from setSize() (for TopLayoutContainer) to setPreferredSize() and you have to call pack() before setVisible()

Categories