How can I display a JTable on a JFrame - java

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.

Related

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.

Java Gui won't display panels and components

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

How can i add JButtons to a panel in vertical way? [duplicate]

This question already has answers here:
Java: vertical alignment within JPanel
(3 answers)
Closed 4 years ago.
the task i am trying to do is simple. I want to add JButtons to a panel in a vertical way, but using a loop to adding it, i tried to do it using .setBounds() and .setLocation() mehtod, but i dont have any results.
In a simple way, i want to do this but adding the buttons vertically and keeping the JScroll bar...:
public class NewMain {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setLayout(null);
for (int i = 0; i < 10; i++) {
JButton asd=new JButton("HOLA "+i);
asd.setLocation(i+20, i+20);
panel.add(asd);
}
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBounds(50, 30, 300, 50);
JPanel contentPane = new JPanel(null);
contentPane.setPreferredSize(new Dimension(500, 400));
contentPane.add(scrollPane);
frame.setContentPane(contentPane);
frame.pack();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
Give the JPanel that holds the JButtons an appropriate layout manager that adds components in a vertical manner. A GridLayout(0, 1) would work, the parameters referring to 0 rows -- meaning variable number of rows, and 1 column. This will add the JButtons into a vertical grid, column of one
Other possible solutions include BoxLayout and GridBagLayout, both of which are a little more complex than the GridLayout.
Also avoid using null layouts as you're doing as this leads to inflexible GUI's painful debugging and changes.

How to make a main window large enough to show the full title

I mean the following:
JFrame frame = new JFrame("Hello swing");
JPanel panel = new JPanel();
panel.add(new JButton("A"));
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
But this code displays this
Is there a way to display something like this right after starting up?
I mean so that the whole title can be seen.
Use the length of the title and apply it to the new dimension used. However I haven't tested it, you have to play with the numbers yourself. Just giving you the idea.
JFrame frame = new JFrame("Hello swing");
JPanel panel = new JPanel();
int len = frame.getTitle().length();
Dimension dimension = new Dimension(200 + 7*len, 200);
panel.setPreferredSize(dimension);
I guess using the number 7 as the constant would be the best. However be aware of using wide (wwww..) or narrow letters (iiii...) mostly, because they appear in different widths. To get the exact length, you have to use method of such as Graphics.getFontMetrics and FontMetrics.stringWidth are.
Take a look at the example acording my code on the top:
Use:
panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
to expand your frame

Grid layout not working?

I am trying to make a 2x2 grid layout that has a JLabel on the top left, and three buttons on the other three spaces. When I do this, I get the unexpected result of one big button (filling up the entire JDialog) that says "Do you want to push me". I don't know why this result shows up, please help, Thanks!
public void sinceyoupressedthecoolbutton() {
JDialog replacementwindow = new JDialog(); //Like a window
JButton best = new JButton("best");
JButton first = new JButton("FIRST");
JButton second = new JButton("Second");
replacementwindow.setLayout(new GridLayout(2,3,0,0)); //Row, column, distance horizontally, distance vertical
JPanel panel = new JPanel();
replacementwindow.add(panel); //adding the JPanel itself
replacementwindow.add(first);
replacementwindow.add(second);
replacementwindow.add(best);
replacementwindow.setSize(500, 500);
replacementwindow.setTitle("NEW WINDOW!");
replacementwindow.setVisible(true);
}
It's because you set the layout of your JButton, and not of your JDialog
Change
label.setLayout(new GridLayout(2,2,0,0));
to
YES.setLayout(new GridLayout(2,2,0,0));
Also, your variable called label is a JButton, you probably want to change that.
Don't add components to a button. You add components to a panel.
So the basic code should be:
JDialog dialog = new JDialog(...);
JPanel panel = new JPanel( new GridLayout(...) );
panel.add(label);
panel.add(button1);
...
dialog.add(panel);
Also, variable names should NOT start with an upper case character! "Yes" does not follow Java standards. The other variables do. Be consistent!

Categories