swing and GUI components not appearing - java

I'm a complete noobie with swing. I'm trying to set a few JPanels and TextAreas to show up but after spending 2 days reading the APIs and trying to add panels to frames and textareas to panels and nothing is showing up.. I'm utterly confused. If anyone could explain how is the best way to do this I would be very grateful
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GUI {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(new FlowLayout()); // J FRAME
JPanel panel = new JPanel(); // first panel on the left
panel.setLayout(new BoxLayout(panel, 1));
// frame.getContentPane().setBackground(Color.red);
frame.add(panel);
JLabel surname = new JLabel();
JLabel initial = new JLabel();
JLabel ext = new JLabel();
surname.setOpaque(true);
initial.setOpaque(true);
ext.setOpaque(true);
frame.add(surname);
panel.add(initial);
panel.add(ext);
JTextArea table = new JTextArea();
table.setEditable(false);
panel.add(table);
table.setVisible(true);

You're adding stuff to the JFrame after it's already visible. If you do that, you need to revalidate your JFrame so it knows to redo its layout.
You could also just wait to show your JFrame until after you've added everything.
Edit: Here is an example program that shows what I'm talking about. Try running this, then take out the call to revalidate() to see the difference.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Test {
public static void main(String[] args) {
final JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton show = new JButton("Show");
show.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent showE) {
frame.add(new JLabel("Test"), BorderLayout.SOUTH);
frame.revalidate(); //tell the JFrame to redo its layout!
}
});
frame.add(show);
frame.setSize(200, 200);
frame.setVisible(true);
}
}

You are adding an empty elements like:
JLabel surname = new JLabel();
Your elements is already added but have nothing to be display.
Try :
JLabel surname = new JLabel("UserName");
JLabel initial = new JLabel("Iinitial");
JLabel ext = new JLabel("Ext");
JTextArea table = new JTextArea(10, 5);

Related

How to add JTextField whenever the button is clicked?

I am practising Java Swing and I am trying to create a GPA calculator. I am having a hard time with my code, how can I add text fields whenever the JButton "add" is clicked? I also want the text fields to align vertically when the button is clicked. Should I use a layout or something?
You can check my screenshot as well.
Here is my code:
import java.awt.event.ActionEvent;
import javax.swing.*;
public class gwa implements ActionListener, java.awt.event.ActionListener{
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
//button
JButton buttonAdd = new JButton("Add");
buttonAdd.setBounds(30, 30, 80, 34);
buttonAdd.addActionListener(new gwa());
//textfield
JTextField gradeField = new JTextField();
gradeField.setBounds(150, 30, 100, 35);
JTextField unitsField = new JTextField();
unitsField.setBounds(300, 30, 100, 35);
//panel
panel.setLayout(null);
panel.add(buttonAdd);
panel.add(gradeField);
panel.add(unitsField);
//frame
frame.add(panel);
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
}
One way – but not the only way – is to use GridBagLayout.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class GwaAdder {
private static final int COLUMNS = 10;
private GridBagConstraints gbc;
private JPanel textFieldsPanel;
private void addTextField(ActionEvent event) {
JTextField textField = new JTextField(COLUMNS);
gbc.gridy++;
textFieldsPanel.add(textField, gbc);
textFieldsPanel.revalidate();
textFieldsPanel.repaint();
}
private void createAndDisplayGui() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTextFieldsPanel(), BorderLayout.CENTER);
frame.add(createButtons(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtons() {
JPanel panel = new JPanel();
JButton button = new JButton("Add");
button.addActionListener(this::addTextField);
panel.add(button);
return panel;
}
private JScrollPane createTextFieldsPanel() {
textFieldsPanel = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridy = 0;
JTextField textField = new JTextField(COLUMNS);
textFieldsPanel.add(textField, gbc);
JScrollPane scrollPane = new JScrollPane(textFieldsPanel);
scrollPane.setPreferredSize(new Dimension(140, 200));
return scrollPane;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new GwaAdder().createAndDisplayGui());
}
}
The ActionListener is implemented using method references. When you change the GUI after it is initially displayed (as the above code does in method addTextField), you usually need to call method revalidate (in class javax.swing.JComponent) followed by method repaint (in class java.awt.Component).
How it looks when I run the above code:
You should first give your button's Action event the panel, and then do the Action
My English is not good, so I use translation software to answer, please forgive me

Saving variables in swing Text field

I know how to make a text field but I have no idea how to take the info inputted un the text field and save it into a variable. also be able to save only after pressing enter.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class scratch1 {
public static void main(String args[]) {
JFrame frame = new JFrame("Chat Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
JPanel panel = new JPanel(); // the panel is not visible in output
JLabel label = new JLabel("Enter Base:");
JTextField tf = new JTextField(2); // accepts upto 2 characters
panel.add(label); // Components Added using Flow Layout
panel.add(tf);
frame.getContentPane().add(BorderLayout.SOUTH, panel);
frame.setVisible(true);
}
Try this code, read the comments to understand the code. I hope this code helps you.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
class main {
static String var; // The text input gets stored in this variable
public static void main(String args[]) {
JFrame frame = new JFrame("Chat Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
JPanel panel = new JPanel();
JLabel label = new JLabel("Enter Base:");
JTextField tf = new JTextField(2);
panel.add(label);
panel.add(tf);
frame.getContentPane().add(BorderLayout.SOUTH, panel);
frame.setVisible(true);
tf.addActionListener(new ActionListener() { // Action to be performed when "Enter" key is pressed
#Override
public void actionPerformed(ActionEvent e) {
var = tf.getText(); // Getting text input from JTextField(tf)
}
});
}
}

java not displaying jpanel in jframe after button press

I am simply making a user interface and all i want it to do after the button is pressed is display thanks... I am pretty new to this but from what i see there are no errors? I have tried playing around with the set visible and to no avail...Any help is great thanks
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JList;
public class GuiApp1 {
public static void main(String args[]) {
String title = (args.length == 0 ? "CheckBox Sample" : args[0]);
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(new GridLayout(0, 1));
Border border = BorderFactory.createTitledBorder("Pizza Toppings");
panel.setBorder(border);
JLabel label1 = new JLabel("Enter name below:");
panel.add(label1);
JTextField field = new JTextField(20);
panel.add(field);
JCheckBox check = new JCheckBox("Car0");
panel.add(check);
check = new JCheckBox("Car1");
panel.add(check);
check = new JCheckBox("Car2");
panel.add(check);
check = new JCheckBox("Car3");
panel.add(check);
check = new JCheckBox("Car4");
panel.add(check);
JButton button = new JButton("Submit");
final JPanel listPanel = new JPanel();
listPanel.setVisible(false);
JLabel listLbl = new JLabel("Vegetables:");
listPanel.add(listLbl);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
}
});
Container contentPane = frame.getContentPane();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.setResizable(true);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
The reason for the vegetables panel not appearing is simple: Xou never add ist to the contentPane.
For the code to function properly you need to add/remove the panels in the ActionListener of the button:
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
if (listPanel.isVisible()) {
contentPane.remove(panel); // Vegetables are visible, so remove the Cars
contentPane.add(listPanel, BorderLayout.CENTER); // And add the Vegetables
} else {
contentPane.remove(listPanel); // Vice versa
contentPane.add(panel, BorderLayout.CENTER);
}
}
});
Then, you need to move the ActionListener below the contentPane declaration and make it final.
Also you should consider putting the different checkboxes is different variables, so you can read the state of them. If you don't want to have so many variables hanging you could put them into an array.
JCheckBox[] checks = new JCheckbox[5];
checks[0] = new JCheckBox("Car0");
panel.add(checks[0]);
...

Blank JPanel after adding a JTextField

Working on adding a GUI to my simple craps simulation program.
Made a new JPanel and added a few JTextFields to it with a default text value. I get no error, and the code runs, but all I get is a blank window with nothing in it.
Here is the code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CrapsGUI extends JFrame
{
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JTextField die1 = new JTextField("Die 1",30);
JTextField die2 = new JTextField("Die 2",30);
JTextField sum = new JTextField("Sum",30);
JTextField point = new JTextField("Point",30);
JTextField status = new JTextField("Status",30);
public CrapsGUI()
{
setTitle("Craps Simulator 2013");
setVisible(true);
setSize(400, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
jp.add(die1);
jp.add(die2);
jp.add(sum);
jp.add(point);
jp.add(status);
}
public static void main(String[] args)
{
Craps craps = new Craps();
CrapsGUI crapsGUI = new CrapsGUI();
}
}
Thanks in advance!
You haven't added the JPanel that contains the visible components.
add(jp);
Three things come to mind
Make sure you are starting your UI's from within the context of the Event Dispatching Thread. See Initial Threads for more details
Call setVisible only after you have finished creating your UI
It would also be helpful if you added something to you frame. Try using add(jp)
try this one:
public static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("Sample Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// first text box
JPanel textbox1Panel = new JPanel();
textbox1Panel.setLayout(new BoxLayout(textbox1Panel, 0));
textbox1Panel.setOpaque(true);
textbox1Panel.setBackground(new Color(100, 0, 131));
textbox1Panel.setPreferredSize(new Dimension(300, 300));
textbox1Panel.add(die1);
textbox1Panel.add(die2);
textbox1Panel.add(sum);
textbox1Panel.add(point);
// Set the menu bar and add the label to the content pane.
frame.getContentPane().add(textbox1Panel, BorderLayout.SOUTH);
// Display the window.
frame.pack();
frame.setVisible(true);
}

How can I replace one of two JPanels with another JPanel in Java?

I designed an interface for the welcome screen with one JFrame included two JPanels (JPanel1 on right and JPanel2 on left). The buttons on the left is to switch the Panels in JPanel1. I want to press on a button to replace JPanel1 content with another JPanel but I don`t know how. Please help.
Here is a very simple example of something that should approximate your description. On the left, we have a hug button to toggle the content of the right panel. On the right, you have a panel with a given border and a label. When you press the button, the content on the right is swapped with the other panel.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
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.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestCardLayout2 {
protected void initUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel leftPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Left panel");
leftPanel.add(label, BorderLayout.NORTH);
JButton button = new JButton("Toggle right panel");
leftPanel.add(button);
frame.add(leftPanel, BorderLayout.WEST);
final CardLayout cardLayout = new CardLayout();
final JPanel rightPanel = new JPanel(cardLayout);
rightPanel.setPreferredSize(new Dimension(200, 500));
JPanel rightPanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
rightPanel1.setBorder(BorderFactory.createLineBorder(Color.RED));
JPanel rightPanel2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
rightPanel2.setBorder(BorderFactory.createLineBorder(Color.BLUE));
JLabel label1 = new JLabel("Right panel 1 with a red border");
JLabel label2 = new JLabel("Right panel 2 with a blue borer");
rightPanel1.add(label1);
rightPanel2.add(label2);
rightPanel.add(rightPanel1, "panel1");
rightPanel.add(rightPanel2, "panel2");
frame.add(rightPanel, BorderLayout.EAST);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.next(rightPanel);
}
});
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestCardLayout2().initUI();
}
});
}
}
An alternative to CardLayout would be JRootPane and its JRootPane.setContentPane() method. Here's an example:
final JPanel panel1 = ...;
final JPanel panel2 = ...;
boolean showingPanel1 = true;
final JRootPane rootPane = new JRootPane();
rootPane.setContentPane(panel1);
JButton switchButton = new JButton("Switch");
switchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (showingPanel1) {
rootPane.setContentPane(panel2);
} else {
rootPane.setContentPane(panel1);
}
showingPanel = !showingPanel;
}
});
Add the rootPane and switchButton components to your window, and then clicking switchButton will switch out the panels.
Here's a tutorial. You should mostly be concerned with JRootPane.setContentPane, the other stuff in the tutorial isn't relevant.
The best answer I found is that I will create one JFrame only and gonna make one big JPanel include two JPanels (JPanelLeft include the buttons and JPanelRight include what the button do) then I will copy the main JPanel for each JButton.
When I press on any button I will do (JFrame.getContentPane.removeAll) to remove the old JPanel then (JFrame.getContentPane.Add(NewJPanel).
This works for me and keep my design as I Want. Thanks for every body.

Categories