Hello all I am having a bit of an issue with this. I created a JPanel and added components to it and then added the JPanel to container. Now when I call this class from main a window pops up but it only displays the first component of the JPanel. Why is it only showing the first item and not all of them? Thanks.
Note: this code is not complete, I am simply trying to figure out why my components are not showing up before moving on to other things, please just address the components issue.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class Player extends JFrame implements ActionListener
{
private CardLayout playerCard;
private JPanel cardPanel;
public String player1;
public String player2;
// Constructor:
public Player()
{
setTitle("Game");
setSize(300,200);
setLocation(10,200);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
//set up the panel
cardPanel = new JPanel();
playerCard = new CardLayout();
cardPanel.setLayout(playerCard);
//get player one name
JLabel p1Name = new JLabel("Player 1 Name:");
JTextField oneName = new JTextField();
//get the name for player 2
JLabel p2Name = new JLabel("Player 2 Name:");
JTextField twoName = new JTextField();
//the button to start the game
JButton start = new JButton("Start");
//add the components << Why is only the first component shown??
cardPanel.add(start);
cardPanel.add(p1Name);
cardPanel.add(oneName);
cardPanel.add(p2Name);
cardPanel.add(twoName);
contentPane.add("startCard",cardPanel);
}
#Override
public void actionPerformed(ActionEvent arg0)
{
// TODO Auto-generated method stub
}
}
You're not using your layouts correctly. You use the String constant when adding components to the CardLayout using component, not the FlowLayout using component. And the String constant goes after the component in the add method. Please read the layout manager tutorial since this is all explained quite well there. It looks like you're using CardLayout where it shouldn't be used, and this is why you're only seeing one component. In other words, your program is using layouts completely bass ackwards.
In other words, the container that uses CardLayout can only show one component at a time, meaning, since cardPanel uses CardLayout, it can only display one component, here twoName will likely be the only thing showing on it.
Related
I'm fairly new to JFrame and I want to know why my items are not showing up on the window. I know i dont have a ActionHandler but I just want my textfield's to show up on my window. Here's my code:
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class FirstGUI extends JFrame{
public void GUI(){
setTitle("Welcome");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(600,600);
JLabel title = new JLabel();
title.setText("Apple Inc. Member Login Port");
title.setFont(new Font("Arial", Font.PLAIN, 24));
JTextField login = new JTextField("Login",10);
JPasswordField pass = new JPasswordField("Password");
add(title);
add(login);
add(pass);
}
public static void main(String[] args){
FirstGUI a = new FirstGUI();
a.GUI();
}
}
but when i run it i get this:
but when i run it i get this:
You get an empty screen because you add the components to the frame after the frame is visible.
As has already been suggested you need to use an appropriate layout manager. FlowLayout is the easiest to start with.
invoke setVisible(true) AFTER adding the components to the frame.
So the code should be more like:
panel.add(...);
panel.add(...);
add(panel);
pack();
setVisible(true);
I agree to MadProgrammer's suggestions (+1)
Well, lets take a look at your program though
You actually have created a JFrame with components in it. Its working fine as well, but your question of "why are my items not showing up in the JFrame" is not because you did something wrong but because missed out something i.e. revalidate()
Try:
public static void main(String[] args){
FirstGUI a = new FirstGUI();
a.GUI();
a.revalidate();
}
I'm not saying this will give you perfect UI.. what I'm trying to say is this will help you understand the Swing better. Learn about Swing Layout managers and then work on your UI to have better results
revalidate(): This component and all parents above it are marked as needing to be laid out. This means the Layout Manager will try to realign the components. Often used after removing components. It is possible that some really sharp swing people may miss this. I would think that you will only know this if you are actually using Swing.
The default layout manager for JFrame is BorderLayout.
This means that your components are essentially all been added ontop of each other.
Try changing the layout manager to something like FlowLayout (for example)...
Take a look at A Visual Guide to Layout Managers and Using Layout Managers for more details.
Also, avoid setSize where possible, use Window#pack instead
Update
I'd also like to introduce you to Initial Threads which should be used to launch your UI code...
The only one reason :
setVisible(True); method for the frame should be put on the end of the code.
if you give this line on the top of the code that is when you create a frame. This will cause that problem.
Don't add the components directly to your frame. Instead add to the content pane, which is where a JFrame stores all of the components that it draws. Usually this is a JPanel.
Here is an example:
public class GUI
{
private JPanel content;
public void GUI
{
/*Other code*/
content = new JPanel();
add(content); //make content the content pane
content.add(title);
content.add(login);
content.add(pass);
}
If that fails, call setVisible(true) and setEnabled(true) on all of your components.
On a side note you may want to make your GUI function a constructor.
import javax.swing.*;
import java.awt.*;
class Myframec extends JFrame
{
Myframec()
{
Container c = this.getContentPane();
c.setLayout(null);
this.setBounds(10,10,700,500);
this.setTitle("Welcome");
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBounds(0,0,700,500);
panel.setBackground(Color.gray);
panel.setLayout(null);
c.add(panel);
Font f = new Font("Arial",Font.BOLD,25);
Font f1 = new Font("Arial",Font.BOLD,20);
JLabel lable = new JLabel();
lable.setBounds(130,10,400,100);
lable.setText("Apple Inc. Member Login Port");
lable.setFont(f);
panel.add(lable);
JTextField login = new JTextField("Login",10);
login.setBounds(120,150,400,30);
login.setFont(f1);
panel.add(login);
JPasswordField pass =new JPasswordField("Password");
pass.setBounds(120,200,400,30);
pass.setFont(f1);
lable.setFont(f);
panel.add(pass);
c.setVisible(true);
this.setVisible(true);
}
public static void main(String[] argm)
{
Myframec frame = new Myframec();
frame.setVisible(true);
}
}
I have a Jframe that the user enters new information through a Joptionpane, it is added to an array which is then appended and displayed to a contentpane.. the cycle then repeats till the user enters "STOP". Currently the program is outputting the new array under the old one. How would I clear away the old array in the content pane and only display the new values?
import java.awt.*;
import java.util.LinkedList;
import java.util.List;
public class Project1GUI {
static JFrame Frame;
static TextArea unsorted_words, sorted_words, linked_words;
public Project1GUI(String title){
//All this does is make an empty GUI FRAME.
Frame=new JFrame();//i made a new variable from the JFrame class
Frame.setSize(400,400);//Used the Variable from JFrame and used some of it functions. This function sets the hieght and width of the Frame
Frame.setLocation(200,200);//This sets where the Empty Frame should be
Frame.setTitle(title);//This puts a title up top of the Frame
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//places an x box that closes when clicked on
Frame.setVisible(true);//This activates the JFram when is set true.
Frame.setLayout(new GridLayout(1,2));//This sets the layout of the Frame and since i want a Grid i used a GirdLayout
//Functions and placed it inside the setlayout functions. to get 2 grids i places 1 meaning 1 row and 2 for 2 cols
unsorted_words=new TextArea(); //From the TextArea class i made three variables
sorted_words= new TextArea();
linked_words= new TextArea();
Container panel=new Container();
panel=Frame.getContentPane();
panel.add(unsorted_words);
panel.add(sorted_words);
panel.add(linked_words);
}
public void add_unsorted(String words){
unsorted_words.append(words+"\n");//add words to GUI
}
public void add_sorted(String words){
sorted_words.append(words+"\n");
}
public void add_linked(List<String> linked_words2){
linked_words.append(linked_words2+"\n");
}
}
For a more definitive answer, post an MCVE
Seeing as you haven't posted any code, I'm guessing you are using a JLabel or a JList or something of that sort to display the array. No matter which one you are doing, you need to tell the component to update it's content, it doesn't just do it itself. To do that, you need to call the components .setText() or similar method.
If you have a JLabel or JTextArea it could look like this.
labelOrTextArea.setText("New Text");
If you are using a JList you should update the lists Default List Model like this
dlm.addElement("New Text");
UPDATE
I see a couple things wrong with your code. First off JFrame Frame = new JFrame conventionally, variables should start with a lower case letter and they should not contain underscores '_'. You are also using AWT Components instead of Swing components. You should be using the likes of JTextArea, JPanel (Theres no JContainer), JLabel etc.
You are also never adding the panel to the frame.
frame.add(panel);
You should also not be adding stuff to the frame or panels after you set its visibility to true. So you should setup your frame like this
import javax.swing.*;
import java.awt.*;
import java.util.List;
public class Project1GUI
{
JTextArea unsorted_words, sorted_words, linked_words;
public Project1GUI()
{
JFrame frame = new JFrame("Title");
JPanel panel = new JPanel(new GridLayout(2, 1));
unsorted_words = new JTextArea();
sorted_words = new JTextArea();
linked_words = new JTextArea();
panel.add(unsorted_words);
panel.add(sorted_words);
panel.add(linked_words);
frame.add(panel);
frame.setSize(400,400);
frame.setLocation(200,200);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
You can then implement the methods you currently have and call them in an ActionListener or such.
Result:
On top of all of that, you should not rely on the use of static as it takes away from the main points of OOP.
I'm fairly new to JFrame and I want to know why my items are not showing up on the window. I know i dont have a ActionHandler but I just want my textfield's to show up on my window. Here's my code:
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class FirstGUI extends JFrame{
public void GUI(){
setTitle("Welcome");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(600,600);
JLabel title = new JLabel();
title.setText("Apple Inc. Member Login Port");
title.setFont(new Font("Arial", Font.PLAIN, 24));
JTextField login = new JTextField("Login",10);
JPasswordField pass = new JPasswordField("Password");
add(title);
add(login);
add(pass);
}
public static void main(String[] args){
FirstGUI a = new FirstGUI();
a.GUI();
}
}
but when i run it i get this:
but when i run it i get this:
You get an empty screen because you add the components to the frame after the frame is visible.
As has already been suggested you need to use an appropriate layout manager. FlowLayout is the easiest to start with.
invoke setVisible(true) AFTER adding the components to the frame.
So the code should be more like:
panel.add(...);
panel.add(...);
add(panel);
pack();
setVisible(true);
I agree to MadProgrammer's suggestions (+1)
Well, lets take a look at your program though
You actually have created a JFrame with components in it. Its working fine as well, but your question of "why are my items not showing up in the JFrame" is not because you did something wrong but because missed out something i.e. revalidate()
Try:
public static void main(String[] args){
FirstGUI a = new FirstGUI();
a.GUI();
a.revalidate();
}
I'm not saying this will give you perfect UI.. what I'm trying to say is this will help you understand the Swing better. Learn about Swing Layout managers and then work on your UI to have better results
revalidate(): This component and all parents above it are marked as needing to be laid out. This means the Layout Manager will try to realign the components. Often used after removing components. It is possible that some really sharp swing people may miss this. I would think that you will only know this if you are actually using Swing.
The default layout manager for JFrame is BorderLayout.
This means that your components are essentially all been added ontop of each other.
Try changing the layout manager to something like FlowLayout (for example)...
Take a look at A Visual Guide to Layout Managers and Using Layout Managers for more details.
Also, avoid setSize where possible, use Window#pack instead
Update
I'd also like to introduce you to Initial Threads which should be used to launch your UI code...
The only one reason :
setVisible(True); method for the frame should be put on the end of the code.
if you give this line on the top of the code that is when you create a frame. This will cause that problem.
Don't add the components directly to your frame. Instead add to the content pane, which is where a JFrame stores all of the components that it draws. Usually this is a JPanel.
Here is an example:
public class GUI
{
private JPanel content;
public void GUI
{
/*Other code*/
content = new JPanel();
add(content); //make content the content pane
content.add(title);
content.add(login);
content.add(pass);
}
If that fails, call setVisible(true) and setEnabled(true) on all of your components.
On a side note you may want to make your GUI function a constructor.
import javax.swing.*;
import java.awt.*;
class Myframec extends JFrame
{
Myframec()
{
Container c = this.getContentPane();
c.setLayout(null);
this.setBounds(10,10,700,500);
this.setTitle("Welcome");
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBounds(0,0,700,500);
panel.setBackground(Color.gray);
panel.setLayout(null);
c.add(panel);
Font f = new Font("Arial",Font.BOLD,25);
Font f1 = new Font("Arial",Font.BOLD,20);
JLabel lable = new JLabel();
lable.setBounds(130,10,400,100);
lable.setText("Apple Inc. Member Login Port");
lable.setFont(f);
panel.add(lable);
JTextField login = new JTextField("Login",10);
login.setBounds(120,150,400,30);
login.setFont(f1);
panel.add(login);
JPasswordField pass =new JPasswordField("Password");
pass.setBounds(120,200,400,30);
pass.setFont(f1);
lable.setFont(f);
panel.add(pass);
c.setVisible(true);
this.setVisible(true);
}
public static void main(String[] argm)
{
Myframec frame = new Myframec();
frame.setVisible(true);
}
}
im trying to design java GUI frame which contains labels, textfields, radio buttons and button..
i want to position each component in specific place tried setBounds() but it didn't work..
also im trying to change background color of the frame using getContentPane().setBackground(Color.white) and setBackground(Color.white) but didnt work too.
how to do it ?
this is my code :
import javax.swing.*;
import java.awt.*;
import java.applet.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class test extends JFrame{
public static void main(String[] args) {
JFrame guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("WHO IS THE WINNER");
guiFrame.setSize(700,500);
guiFrame.setLocationRelativeTo(null);
final JPanel first = new JPanel();
JLabel un = new JLabel("UserName:");
JTextField textField = new JTextField(20);
JLabel sn = new JLabel("Server Name:");
JTextField textField2 = new JTextField(20);
un.setLabelFor(textField);
sn.setLabelFor(textField2);
first.add(un);
first.add(textField);
first.add(sn);
first.add(textField2);
final JPanel second = new JPanel();
JLabel level = new JLabel("Level:");
JLabel score = new JLabel("Score:");
JLabel question = new JLabel("Question:");
CheckboxGroup radioGroup = new CheckboxGroup();
Checkbox radio1 = new Checkbox("True", radioGroup,false);
Checkbox radio2 = new Checkbox("False", radioGroup,true);
second.add(score);
second.add(level);
second.add(question);
second.add(radio1);
second.add(radio2);
JButton next = new JButton( "Next");
next.addActionListener(
new ActionListener() {
#Override public void actionPerformed(ActionEvent event) {
first.setVisible(false);
} });
guiFrame.add(first, BorderLayout.NORTH);
guiFrame.add(second, BorderLayout.CENTER);
guiFrame.add(next,BorderLayout.SOUTH);
guiFrame.setVisible(true);
}
}
for the positioning for example i want the first label and text field under them the other label and text field not beside them.. same for other labels and radio buttons i don't want them it be beside each other i want o give them a specific position to be in..
can someone please help ?
Thanks :)
This answer is just for Eclipse IDE.
An easy way to place all the widgets is doing it from the Design tab, placed at the bottom-left side of the window. Just change from Source perspective to Design perspective. It will open a simple panel with everything you need. Just drag the different widgets and place them in their position.
To change the background of the frame, do it from the properties of the frame in the Design tab or add the following code to the constructor of the panel:
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
So, I have been working on a Java Memory/Concentration Game assignment. I've not gotten as far as I wanted, it's only half finished, but I did have the GUI mostly working... Until I tried to add radio buttons to my Frame. I think the problem might be because I changed a JFrame(CardButtonPanelFrame) into a JPanel. I'm trying to add 3 JPanels to a larger JPanel which I add to a JFrame. I'm just getting a small blank window popping up when I used to have all 52 cards pop up.
Basically when I work on projects things can get out of control in their complexity so I thought I'd come here to make sure I'm heading in the right direction.
Here's my main:
import javax.swing.*;
public class Project3{
public static void main(String[] args){
JFrame frame = new JFrame();
Grid game = new Grid();
frame.pack();
frame.add(game);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Then this is outermost JPanel I'd like to hold the radio buttons at the top, the cards in the middle, and eventually the score at the bottom.
import java.awt.*;
import javax.swing.*;
public class Grid extends JPanel{
public Grid(){
JPanel panel = new JPanel(); //construct a frame
CardButtonPanelFrame buttons = new CardButtonPanelFrame();
wtf choices = new wtf();
panel.setLayout(new GridLayout(3,1)); //that panel uses GridLayout
panel.add(choices);//add the panels to the Frame
panel.add(buttons);
//frame.add(scores);
add(panel);
setVisible(true);
}
}
This is the radiobuttons panel... named wtf because I had some compiling issues and experimented with changing the name. I've not even gotten to the stage of figuring out how to implement the different player amounts yet.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class wtf extends JPanel implements ActionListener {
static String zerostring = "Zero Player Game";
static String onestring = "One Player Game";
static String twostring = "Two Player Game";
public wtf() {
super(new BorderLayout());
//Create the radio buttons.
JRadioButton zeroButton = new JRadioButton(zerostring);
zeroButton.setMnemonic(KeyEvent.VK_C);
zeroButton.setActionCommand(zerostring);
JRadioButton oneButton = new JRadioButton(onestring);
oneButton.setMnemonic(KeyEvent.VK_B);
oneButton.setActionCommand(onestring);
oneButton.setSelected(true);
JRadioButton twoButton = new JRadioButton(twostring);
twoButton.setMnemonic(KeyEvent.VK_D);
twoButton.setActionCommand(twostring);
//Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(zeroButton);
group.add(oneButton);
group.add(twoButton);
//Register a listener for the radio buttons.
zeroButton.addActionListener(this);
oneButton.addActionListener(this);
twoButton.addActionListener(this);
//Put the radio buttons in a column in a panel.
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
radioPanel.add(zeroButton);
radioPanel.add(oneButton);
radioPanel.add(twoButton);
add(radioPanel, BorderLayout.LINE_START);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
/** Listens to the radio buttons. */
public void actionPerformed(ActionEvent e) {
//do something with e.getActionCommand()
}
}
So I have two more classes but I think the current problem is here and I'm afraid of making this a giant wall of code. I have more questions but I think I'll take it one at a time so I don't end up posting pages and pages of code that no one wants to read.
One problem you're doing is calling pack() on your JFrame before adding components. Don't do that, but instead add all components that you can first, then call pack(), then setVisible(true)