Java Gui won't display panels and components - java

im trying to make a program to add an admin to a ms access database
I researched many times, figured out all the components need to be in a panel, and only the same type of J stuff can be in a panel, so i made many panels and combined them in a big panel
//frame details
final int FRAME_WIDTH = 1000;
final int FRAME_HEIGHT = 1000;
JFrame aFrame = new JFrame("Add admin");
aFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
aFrame.setVisible(true);
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//panel declaration
JPanel BigPanel = new JPanel();
JPanel adminnameenter = new JPanel();
JPanel typeadminname = new JPanel();
JPanel adminlastnameenter = new JPanel();
JPanel typeadminlastname = new JPanel();
JPanel buttonaddadmin = new JPanel();
//labels, textfields, and buttons
JLabel newAdminName = new JLabel("Enter admin name");
JTextField adminName = new JTextField(7);
JLabel newadminlastname = new JLabel("Enter admin last name");
JTextField adminlastname = new JTextField(7);
JButton addadmin = new JButton("Add Admin");
//add things to panel
adminnameenter.add(newAdminName);
typeadminname.add(adminName);
adminlastnameenter.add(newadminlastname);
typeadminlastname.add(adminlastname);
buttonaddadmin.add(addadmin);
//add things to big jPanel
BigPanel.add(adminnameenter);
BigPanel.add(typeadminname);
BigPanel.add(adminlastnameenter);
BigPanel.add(typeadminlastname);
BigPanel.add(buttonaddadmin);
//add things to frame
aFrame.add(BigPanel);
the only thing that popped up was a frame that said add admin

Add this code to the end of your function:
aFrame.setVisible(false);
aFrame.setVisible(true);
Or alternatively put
aFrame.setVisible(true);
at the end of your function instead of the beginning.
And all the components will appear. This is because whenever you change anything to your JFrame, it will only change on the user side once it is told to resize or refresh the frame. Also you don't need to put every single component in it's own JPanel, you can simply insert them directly in your BigPanel (small nitpick, but the b in bigPanel, shouldn't be capitalized, seeing as variables start with non-capitalized letters).
Also look into LayoutManagers, they will probably be useful for your application.
https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

Related

Java JPanel .updateUI() removes my setBound data

I'm having a problem when i use .updateUI() in my JPanels, The bounds i set return to default.
//Set my Frame
frame = new JFrame();
frame.setSize(1600,900);
frame.setLayout(null);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//Set Panel
JPanel menuInput = new JPanel();
menuInput.setBounds(100,100,500,500);
//Set Button
JButton buttonSolve = new JButton();
buttonSolve.setBounds(30,30,400,200);
menuInput .add(buttonSolve);
frame.add(menuInput);
//If i updateUI, the bound returns to default.
menuInput.updateUI();
However if i place my menuInput.updateUI before frame.add(menuInput) it will not affect the bounds, but i need to refresh my Panel every time new data comes in.
I use MigLayout, and i have no problem with setting the positions of each object now.

Creating a board game layout using JLayeredPane

I have an assignment which requires me to create the layout that you see in the image as part of the development of a game. I've never worked with Java for desktop applications before so i'm a complete noob when it comes to using the Swing & AWT libraries. The image suggests that we use a JLayeredPane as our root container and then add the rest on top of it. My issue is that i've tried starting with the background image and the gridLayout but i can't seem to make anything other than the background show up. The grid doesn't show up at all (no border line, no background of the cells) and any other component i've added to it has failed. Can somebody point me in the right direction here? I've read the docs & saw some example of various layouts,containers and components but i can't seem to make all of them work together.
Here's my code so far:
public class BoardView extends JFrame{
// Constructor
public BoardView() {
JFrame window = new JFrame("Sorry Game"); // create a new Jwindow instance
ImageIcon appIcon = new ImageIcon(getClass().getClassLoader().getResource("res/icon.png")); // create the icon for the app
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when the 'X' button is clicked, the app stops
window.setSize(new Dimension(1000, 700)); // setting the size of the window
window.setResizable(false); // Window won't be resizable
window.setIconImage(appIcon.getImage()); // set the icon for the app
window.setLayout(new BorderLayout());
JLayeredPane layeredPane = new JLayeredPane();
JLabel background = new JLabel();
background.setSize(1000,700);
background.setIcon(new ImageIcon(getClass().getClassLoader().getResource("res/background.png"))); for the JLabel
layeredPane.add(background,0);
JPanel gridPanel = new JPanel(new GridLayout(16,16));
gridPanel.setSize(650,700);
layeredPane.add(gridPanel);
for(int i = 0; i < 256; i++) {
JLabel tile = new JLabel();
tile.setBackground(Color.red);
tile.setBorder(new LineBorder(Color.black));
gridPanel.add(tile);
}
JLabel logo = new JLabel();
logo.setIcon(new ImageIcon(getClass().getClassLoader().getResource("res/sorryImage.png")));
layeredPane.add(logo);
window.add(layeredPane);
window.setLocationRelativeTo(null); // centers the window to the screen
window.setVisible(true); // make the window visible
}
}
My thought process was that i could set the JFrame's layout to a BorderLayout so that i can brake the final layout down into two parts, the West one and the East one. The West one would contain the Grid and the various JLabels and Buttons and the East one would contain the rest of the components. I've tried using the BorderLayout.WEST & EAST parameters when adding components to the JFrame but none has worked or changed a single thing. I've also tried using an index for the depth when adding components to the JLayeredPane as per the docs but again nothing changes.
P.S. Please note that i'm not looking for someone to create the layout for me. I want someone to help me understand what i'm doing wrong and what the best way of creating such layouts is.
In order to initialize the cells of the grid that i want to have images in, don't i need to add them manually in those positions?
If you use a GridLayout every cell must have a component and the components must be added in sequential order. That is as components are added they will wrap automatically to the next row as required.
So even if you don't want an image in a cell you would need to add a dummy component, lets say a JLabel with no text/icon.
An easier approach might be to use a GridBagLayout. The GridBagLayout can be configured to "reserve" space for cells that don't have components. So you can add a component to a specific cell.
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
public class GridBagLayoutSparse extends JPanel
{
public GridBagLayoutSparse()
{
setBorder( new LineBorder(Color.RED) );
GridBagLayout gbl = new GridBagLayout();
setLayout( gbl );
/*
// Set up a grid with 5 rows and columns.
// The minimimum width of a column is 50 pixels
// and the minimum height of a row is 20 pixels.
int[] columns = new int[5];
Arrays.fill(columns, 50);
gbl.columnWidths = columns;
int[] rows = new int[5];
Arrays.fill(rows, 20);
gbl.rowHeights = rows;
*/
// Add components to the grid at top/left and bottom/right
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
addLabel("Cell 0:0", gbc);
gbc.gridx = 3;
gbc.gridy = 4;
addLabel("Cell 3:4", gbc);
}
private void addLabel(String text, GridBagConstraints gbc)
{
JLabel label = new JLabel(text);
label.setBorder( new LineBorder(Color.BLUE) );
add(label, gbc);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("GridBagLayoutSparse");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout( new GridBagLayout() );
frame.add(new GridBagLayoutSparse());
frame.setSize(300, 300);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
}
}
Run the code as is and the components will be grouped together in the center.
Uncomment the block comment and run again. The components will be positioned in the appropriate cell.

JComboBox showing only if it has a single item

I have a JPanel with a CardLayout and a JComboBox inside it. They are dinamically filled with data taken from a JTable. If the JComboBox has a single item it shows just fine, but if I fill it with more than one it doesn't show.
JPanel intervalPanel = new JPanel;
CardLayout intervalLayout = new CardLayout();
intervalPanel.setLayout(intervalLayout);
JComboBox intervalComboBox = new JComboBox();
for (int i = 0; i < table.getRowCount(); i++) {
String name = (String) table.getValueAt(i, 0);
intervalComboBox.addItem(name);
JPanel p = new JPanel();
p.setName(name);
p.add(intervalComboBox);
p.add(new JLabel(name));
intervalPanel.add(p, name);
}
A Swing component can only have a single parent.
p.add(intervalComboBox);
The above statement keeps removing the combo box from the previous panel and adds it to the current panel.
but if I fill it with more than one it doesn't show.
So the reason it doesn't show is because it is only visible on the last card, but you current see the first card.
The better solution is to NOT add the combo box to the panel in the CardLayout. Instead your main panel should use a BorderLayout. Then the basic logic would be something like:
JPanel main = new JPanel( new BorderLayout() );
JComboBox comboBox = new JComboBox(...);
main.add(comboBox, BorderLayout.PAGE_START);
JPanel card = new JPanel( intervalLayout );
main.add(card, BorderLayout.CENTER);
frame.add( main );
Then you just add child panels to the "card" panel as required.
Read the section from the Swing tutorial on How to Use CardLayout for a complete working demo that uses the above design concept.

How can I display a JTable on a JFrame

I've spent hours online and I'm afraid I can't quite figure out how to make my JTable show up next to my JButton on a JFrame, if anyone has a simple or comprehensive way to explain why and how to fix the problem Id really appreciate it.
Extensive online research including downloading samples and applying various suggestions; also reached out to my teacher for help but she doesn't have much experience with java.
public class canvas extends JTable{
static void displayJFrame(){
//set variables
int i = 0;
String[][] strArray = new String[3][i];
String[] labelArray = new String[3];
labelArray[0] = "Name: ";
labelArray[1] = "Subject: ";
labelArray[2] = "Average: ";
//create JFrame
JFrame f = new JFrame("Test Average");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setBackground(Color.WHITE);
f.setPreferredSize(new Dimension(600, 600));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
//create JButton
JButton button=new JButton("Enter New Grade");
button.setBounds(450,15,140, 40);
button.addActionListener(e -> average(strArray, i));//gets info from user and adds to strArray
button.addActionListener(e -> count(i));//increases counter
f.add(button);
//create JTable
JTable j = new JTable(strArray, labelArray);
JScrollPane scrollPane = new JScrollPane(j);
j.setBounds(30, 40, 200, 300);
j.setSize(500, 200);
j.setVisible(true);
}
}
all of my code runs as expected except there is no table, I've also tried so many things that didn't work so this basically where I started so that its not crowded by tons of incorrect stuff
You have several problems. First, by default a JFrame uses a BorderLayout. Using the default add(component) method places that component in the center. Using the same add() method again just replaces the new component at the center.
Second, do not pack or set the frame visible until AFTER you have created the entire GUI.
You would do better to create a JPanel and add the components to that panel, then add the panel to the frame. The default layout manager for JPanel is a FlowLayout.

Rearranging buttons and jlist in a panel

I created buttons and a jlist. All my buttons are in another panel called buttonPanels, and I wanted to add that panel and the jList to another panel called jPanelSouth. I tried positioning my buttons by using the ______.setLocation(x,y) but the buttons don't seem to move anywhere within the panel (same with jlist).
//southPanel and stuff
jPanelSouth = new JPanel();
jPanelSouth.setBorder(BorderFactory.createLineBorder(Color.black, 5));
//buttons
buttonPanel = new JPanel(new GridLayout(3,1));
drawCardBtn = new JButton("Draw Card");
moveBtn = new JButton("Move");
playCardBtn = new JButton("Play Card");
buttonPanel.add(drawCardBtn);
buttonPanel.add(moveBtn);
buttonPanel.add(playCardBtn);
roomList = new JList(roomNumbers);
roomList.setVisibleRowCount(4);
roomList.setFixedCellWidth(100);
roomList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jPanelSouth.add(buttonPanel);
jPanelSouth.add(roomList);
This is how my window looks right now
This is how I want it to look like
I'm not really sure what layout I should be using in this case
You should change a layout in your jPanelSouth. For example, try add this line to your code.
jPanelSouth.setLayout(new BoxLayout(jPanelSouth, BoxLayout.Y_AXIS));
Read some more about swing layouts here.
Try using the setBounds( x, y, height, width) in your buttons.
buttonPanel = newJPanel();
buttonPanel.setBounds(x, y, height, width);

Categories