Unable to fill JTable component created with IntelliJ GUI Designer - java

I have a JTable component I made in IntelliJ's GUI Designer. The class is bound to the GUI Form and compiles without problem, but the table stays empty. I've tried to use some other code as well, but im a bit new to java and really want to know the answer to this. please dont give me a half answer or point me to a page to go figure it out. I am here cause I did try that.
package com.company;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
/**
* Created by User on 3/8/2016.
*/
public class TableGUI {
private static JFrame frame;
private JTable table1;
private JPanel panel1;
public TableGUI() {
DefaultTableModel model = new DefaultTableModel();
table1.setAutoCreateRowSorter(true);
table1.setFillsViewportHeight(true);
table1.setPreferredScrollableViewportSize(new Dimension(550, 200));
model.addColumn("Id");
model.addColumn("First Name");
model.addColumn("Last Name");
model.addColumn("Company Name");
table1.setModel(model);
}
public static void main(String[] args) {
frame = new JFrame("TableGUI");
frame.setContentPane(new TableGUI().panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setSize(new Dimension(600, 400));
}
}

I figured it out, the answer was I was lacking a JScrollPane. I had to drop in a component called JScrollPane via the IntelliJ Designer and drop the JTable inside it. This allowed for the column-names to show on the JTable.

Related

JPanel not showing inside JFrame in Java

I know this question has been asked a lot and I have done my research but still can not find anything. Below is proof of this before anyone gets upset:
I found this link:
https://coderanch.com/t/563764/java/Blank-Frame-Panel
and this:
Adding panels to frame, but not showing when app is run
and this:
Why shouldn't I call setVisible(true) before adding components?
and this:
JPanel not showing in JFrame?
But the first question says use repaint which I tried with no fix and the second and third to last questions talk about putting setVisible after components added which I have.
The last one talks about making the users JPanelArt a extension (done so) of JPanel instead of JFrame and not to make a frame in a frame constructor (also have not done)
When ever I run this I just get a blank frame, as if the panel was never added in.
I apologise if I have missed something in those links. Anyway below is my classes:
GUI.java (extends JFrame)
package javaapplication2;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GUI extends JFrame{
public GUI(String name) {
super(name);
getContentPane().setLayout(null);
JPanel myPanel1 = new GUIPanel();
myPanel1.setLocation(20, 20);
getContentPane().add(myPanel1);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setResizable(true);
}
public static void main(String[] args) {
JFrame frame = new GUI("Game");
frame.setVisible(true);
}
}
GUIPanel.java (extends JPanel)
package javaapplication2;
import java.awt.*;
import javax.swing.*;
public class GUIPanel extends JPanel {
JButton start;
JButton inspect1;
JButton inspect2;
JButton inspect3;
JButton suspect;
public GUIPanel() {
setLayout(new BorderLayout());
start = new JButton("Start Game");
inspect1 = new JButton("Inspect 1");
inspect2 = new JButton("Inspect 2");
inspect3 = new JButton("Inspect 3");
suspect = new JButton("Choose Suspect");
add(start, BorderLayout.WEST);
add(inspect1, BorderLayout.WEST);
add(inspect2, BorderLayout.WEST);
add(inspect3, BorderLayout.WEST);
add(suspect, BorderLayout.WEST);
}
}
I know it is very simple, but that is because I am following a tutorial from my lecturer to get the hang of things as I previously used a GUI builder which someone in this community pointed out to me is not good to start with (very correct!)
The issue lies in your GUI class when you call getContentPane().setLayout(null). Because of this method call, your JFrame is not displaying anything. If you remove it, your elements should show up.
I also noticed that you were setting each JButton to have a constraint of BorderLayout.WEST. This will most likely put your JButtons on top of each other and render only one of them.

How do I set the size of a JTextArea?

I'm fairly new to working with graphics in Java, and have been trying to make a simple console to display text based games in a window. I have a test class, where I'm working on the console, but when I add a JTextArea to my console window, it either takes up the entire window or doesn't display at all.
Here is my code:
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.Event;
public class GUI {
public static void main(String[] args) {
JFrame frame = new JFrame("AoA");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(1020,760);
frame.setBackground(Color.LIGHT_GRAY);
frame.setResizable(false);
JTextArea jta = new JTextArea(100,100);
jta.setEditable(false);
jta.setBackground(Color.WHITE);
frame.add(jta);
}
}
I know that some of my imports aren't used in this file, but they will used in the final game. I am also aware that the JTextArea is set to size 100,100, which I am unsure whether it is too large or small. I could really use some help on this, though.
Your problem is the installed by default BorderLayout in your frame. The easiest way to solve your problem is to set another layout manager.
public static void main(String[] args) {
SwingUtilities.invokeLater(GUI::startUp);
}
private static void startUp() {
JFrame frame = new JFrame("AoA");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1020,760);
frame.setBackground(Color.LIGHT_GRAY);
frame.setResizable(false);
frame.setLayout(new FlowLayout()); // FlowLayout is required
JTextArea jta = new JTextArea(40,40);
jta.setEditable(false);
jta.setBackground(Color.WHITE);
// JScrollPane to get the scroll bars when required
frame.add(new JScrollPane(jta));
// setVisible should be last operation to get a correct painting
frame.setVisible(true);
}
Please take a look for layout managers in Swing

I created my GUI in a GUI class' constructor. How would I access its Frames, Panels etc. from another class?

First of all, this is a more specific question than it seems to be. To start off: I am currently doing a small application with a rather small GUI, so I decided to make a GUI class, and initialize my whole GUI in this constructor.
This would look like this:
public class GUI extends JFrame{
public GUI{
//Initialize GUI here, including its Frames, Panels, Buttons etc.
}
}
How can I now access the GUIs frame etc. from an external class? If I would create an object of the GUI class, I would simply duplicate my GUI window. I did not come across any other ideas than making the frame, panel and so on static.
I'm somewhat lost right now. Also I'm pretty sure that I am not thinking the right way into this case, but I need someone to point me to the right direction. If someone could help me out, I would be very thankful.
First of all, using static is the worst solution possible, even if your GUI class is a singleton (buf if it is, at least it will work fine).
Why don't you simply create getters and/or setters ? And finally, it is usually not normal that external classes need to access the components of another graphic class. You should wonder if your design is the most fitted for your needs.
Here's a simple GUI to change the background color of a JPanel with a JButton. Generally, this is how you construct a Swing GUI.
package com.ggl.testing;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ChangeDemo implements Runnable {
private boolean isYellow;
private JFrame frame;
public static void main(String[] args) {
SwingUtilities.invokeLater(new ChangeDemo());
}
#Override
public void run() {
frame = new JFrame("Change Background Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
JPanel namePanel = new JPanel();
JLabel nameLabel = new JLabel(
"Click the button to change the background color");
nameLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
namePanel.add(nameLabel);
mainPanel.add(namePanel);
final JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBackground(Color.YELLOW);
isYellow = true;
JButton changeButton = new JButton("Change Color");
changeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
isYellow = !isYellow;
if (isYellow) buttonPanel.setBackground(Color.YELLOW);
else buttonPanel.setBackground(Color.RED);
}
});
buttonPanel.add(changeButton);
mainPanel.add(buttonPanel);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
You don't access the Swing components of the GUI from other classes. You create other classes to hold the values of the GUI.
Generally, you use the model / view / controller pattern to construct a Swing GUI. That way, you can focus on one part of the GUI at a time.
Take a look at my article, Java Swing File Browser, to see how the MVC pattern works with a typical Swing GUI.
You don't need to make it static or to create a new JFrame object every time.
Have a look at this simple code :
class UseJFrame {
public static void main(String...args) {
Scanner sc = new Scanner(System.in);
JFrame frame = new GUI();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
System.out.println("Press E to exit");
String ip;
while(true) {
System.out.println("Show GUI (Y/N/E)? : ");
ip = sc.nextLine();
if(ip.equalsIgnoreCase("y") {
frame.setVisible(true);
} else if(ip.equalsIgnoreCase("n") {
frame.setVisible(false);
} else { // E or any other input
frame.dispose();
}
}
}
}
Note : Don't make GUI visible through constructor or it will show window at the very starting of creation of JFrame object.
If you want to use the same JFrame object at other places too then pool architecture would be better approach.

Putting everything into a JFrame

I want to know how to put put console output into a JFrame. For example, putting this output into a JFrame:
import static java.lang.System.out;
public class frame{
public static void main(String [] args){
out.println("hello");
}
}
How is it possible?
You need to set up the JFrame first.
JFrame frame = new JFrame("title");
Then, set the properties of the JFrame:
frame.setSize(1280,720); //Sets the program's size
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Tells the program to exit on close
frame.setResizable(true); //Tells the program if resizing is enabled
Then, create a panel to store the components:
JPanel p = new JPanel();
After that, you must add the panel to the JFrame like so:
frame.add(p);
Then, with that done, you can use the components supplied in the swing framework, and add them to the panel. A reference for these components can be found here: http://docs.oracle.com/javase/tutorial/uiswing/components/componentlist.html.
To create a component, use the following code:
JLabel label = new JLabel();
Then, use it's build in functions to change it:
label.setText("new text");
Then, once again, to add a component to a panel, use the panel's add() method:
panel.add(label);
Those are just the basics of making a GUI with java. A full tutorial can be viewed here:
http://docs.oracle.com/javase/tutorial/uiswing/
Good Luck!
I can help you with this, but let me please fix some syntax errors you have. When you put the import, an import can't be static (that I know of) and when you want to print out something using "System.out.print" or "System.out.println" you MUST include the "System" part of the line. If you want to add text to a a JFrame use the JLabel to import both just do this bit of code:
import javax.swing.*;
That should import all of your swing elements such as JLabel and JFrame and JPanel, and try this code it will make a window that will have a button and a label. The button doesn't do anything in this code:
import javax.swing.*;
public class main{
public static void main(String[] args)
{
/*
* Creates the frame, makes it visible, and makes
* appear in the center of the screen. While also making it have a close operation
*/
JFrame frame = new JFrame("Button");
frame.setVisible(true);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
//Creates the panel, and adds it to the frame
JPanel panel = new JPanel();
frame.add(panel);
//Creates the label and adds it to the panel, also sets the text
JLabel label = new JLabel();
label.setText("Welcome" + "\n" + "\n");
panel.add(label);
//Creates the button and adds it to the panel
JButton button1 = new JButton("Button 1");
panel.add(button1);
}
}
1.If you want to use JFrame you have to extend your class to a subclass of JFrame:
public class frame extends JFrame {}
2.a)If you want to put Text in your Frame use JLabel and add it to your frame:
JLabel hello = new JLabel("Hello");
add(hello);
2.b)If you want a console output just call System.out.println() in the constructor
Here is a small example class:
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Frame extends JFrame {
public static void main(String args[]) {
new Frame();
}
Frame() {
System.out.println("Hello");
JLabel hello = new JLabel("Hello");
add(hello);
this.setSize(100, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
have a look to the oracle lessons... or any java book!
If that is the case, I don't want to get into GUI just yet. (Learning from a book) Can I convert my current project to a jar file and have it automatically open a command prompt window upon double click?

JScrollPane Problems

If I add a JTable to a JPanel and then add that JPanel to a JScrollPane, whenever that JTable gains focus, the scroll pane automatically scrolls to the very bottom, which is bad.
I have many reasons for doing it like this, so I'm hoping for some kind solution to stop this auto-scrolling.
OH, and here's the kicker...It only seems to happen when running the app through JNLP/WebStart, and it does NOT do it in Eclipse, which is even more frustrating.
Here's a quick example that if you launch through JLNP, click the text field, click the table, then it auto-scrolls to the bottom:
import java.awt.*;
import javax.swing.*;
public class ScrollDemo extends JPanel{
private static final long serialVersionUID = 1L;
public ScrollDemo()
{
this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
JTable table = new JTable(100,6);
this.add(new JTextField());
JPanel panel = new JPanel();
panel.add(table);
JScrollPane scroll = new JScrollPane(panel);
this.add(scroll);
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("ScrollDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JComponent newContentPane = new ScrollDemo();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
frame.setPreferredSize(new Dimension(500, 500));
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I am unable to reproduce the problem, but I can offer a few observations:
The frame's add() method forwards the component to the contentPane automatically.
Instead of setting the frame's preferred size, use setPreferredScrollableViewportSize() on the table.
If the unwanted scrolling is due to updating the table's model, see this example of how to temporarily suspend scrolling.
Kudos for using the event dispatch thread.
Addendum: The nested panel having a (default) FlowLayout is superfluous.
import java.awt.*;
import javax.swing.*;
/** #see https://stackoverflow.com/questions/8319388 */
public class ScrollDemo extends JPanel {
public ScrollDemo() {
this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
JTable table = new JTable(100, 6);
table.setPreferredScrollableViewportSize(new Dimension(320, 240));
this.add(new JTextField());
this.add(new JScrollPane(table));
}
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("ScrollDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
frame.add(new ScrollDemo());
frame.pack();
// Display the window.
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
Just in case anyone cares, the problem was that the eclipse launcher and the JNLP launcher for the app had a different KeyboardFocusManager, and the JNLP one had some quirks.
I was unaware of a custom KeyboardFocusManager being added on the JLNP side, but at least it explains things.
Thanks everyone.
I have had auto scrolling issue on JTables when I place them on an intermediary JPanel instead of placing them directly as the JScrollPane's viewport. In those cases, removing the extraneous panel and putting the table directly on the scrollpane has solved my issues.
Well, I ended up having to rework how I was adding my objects to the scroll pane to avoid this issue. Specifically, if the table is going to be taller than the viewport height, then I just have to add the table directly to the scrollpane then change how I was using the intermediary panel.
Thanks to everyone for your input!
According to this, to change the selection for your JTable you need to change the selection model. Try using the following to set the selected item to the very first one.
ListSelectionModel selectionModel = table.getSelectionModel();
selectionModel.setSelectionInterval(start, end);
See if that gives the focus to the top of the JTable?
EDIT: I have not done this before, so not sure what start and end will need to be, try 0,0 or 0,1 maybe?

Categories

Resources