JTable in User Interface - java

I need help understanding how JTable can be implemented. My JTable does not show up when given header names and data, I have tried pack() (makes my everything but my menu disappear), I have tried setFillsViewportHeight(true) and nothing updated. Any help or guidance would be appreciated.
// Main
public static void main(String[] args) {
Main window = new Main("A Project");
window.setBounds(30, 30, 700, 500);
window.setVisible(true);
}
// Displays a box with a menu bar that has file and about options(code not shown):
public Main(String title) {
JMenuBar menuBar = new JMenuBar(); // Window menu bar
setTitle(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setJMenuBar(menuBar); // Add the menu bar to the window
}
// This section of code is inside action listener when you click menu bar's file then load a file:
// Nothing appears:
String[] columnNames = {"ID","First Name","Last Name","Program","Level","USERNAME"};
ArrayList[][] data = loadFileRoster.getRosterData();
JTable table = new JTable(data,columnNames);
JScrollPane scrollPane = new JScrollPane();
table.add(scrollPane);
table.setVisible(true);

ArrayList[][] data = loadFileRoster.getRosterData();
JTable table = new JTable(data,columnNames);
I'm not aware that you can create a JTable using an ArrayList containing your data (unless is new in JDK 14)
JScrollPane scrollPane = new JScrollPane();
table.add(scrollPane);
You don't add a scroll pane to a table. You add a JTable to the JViewport of a JScrollPane. This is done by using:
JScrollPane scrollPane = new JScrollPane( table );
You then add the scroll pane to the frame.
table.setVisible(true);
Swing components are visible by default. The setVisible(true) is unnecessary.
Read the section from the Swing tutorial on How to Use Tables for working examples.
Download the example and modify them. They will show you how to better structure your code.

Related

how to display table when the menu bar is is clicked?

may I know how to display out the table when the menu bar is clicked?
Below is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
public class Exercise03 extends JFrame {
public Exercise03() {
String[] columns = {
"No", "DO NUMBERS", "INVOICE NUMBERS", "OUTLET", "SUBMITTED BY", "CHECKED BY"
};
Object [][] input = new Object[][] {
{"1", "NKK/DO200100001", "NKK/IV200100001", "K", "A", "B"}
};
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem1;
menuBar = new JMenuBar();
menu = new JMenu ("Menu");
menu.setMnemonic(KeyEvent.VK_A);
menuBar.add(menu);
menuItem1 = new JMenuItem("Invoice", KeyEvent.VK_I);
menu.add(menuItem1);
menuItem1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JTable menuItem1 = new JTable(input, columns);
JScrollPane pane = new JScrollPane(menuItem1);
pane.add(menuItem1);
pane.setVisible(true);
}
});
setJMenuBar(menuBar);
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Documentation Checklist");
setSize(300,100);
setVisible(true);
}
public static void main (String[]args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Exercise03();
}
});
}
}
Right now I am able to display out the "menu" bar and when I clicked it, it shows one submenus which is "Invoice" but when I clicked the submenu "Invoice", it does not shows out the table below the menu bar.
My expected output is when I click the submenu "Invoice", it will shows up a table below the menu bar.
So may I know how to code to display such result ?
First of all you need to learn how to use a JScrollPane:
JScrollPane pane = new JScrollPane(menuItem1);
//pane.add(menuItem1);
Only the first statement is needed. The scroll pane has a "viewport" to display the component. So the table needs to be added to the viewport, which is done automatically when you create the scroll pane with the table as the parameter in the constructor.
Read the section from the Swing tutorial on How to Use Scroll Panes for more details on how the scroll pane works.
Then to dynamically add the scroll pane to the frame:
Don't change the layout to a FlowLayout. The default BorderLayout will be a better layout manager for the frame. It will allow components to resize dynamically as the frame is resized.
You create a JScrollPane, but you never add it to the frame. So you need to add the scroll pane to the frame. The setVisible() statement is not needed since all Swing components are visible by default
Once you add the scroll pane to the frame you need to invoke revalidate() on the panel you add the scroll pane to. In this case since you add it to the content pane you can just invoke revalidate() on the frame. The revalidate() will invoke the layout manager to give the scroll pane a size and location.
The other solution is to create the JScrollPane in the constructor of your class and add it to the frame. You would then need to save the scroll pane as an instance variable of your class. Then when you click on the menu item you can create the JTable and add the table to the scroll pane using:
scrollPane.setViewportView( menuItem1 );
then you don't need to worry about the revalidate().

How do I resize JScrollPane after resizing a JTextArea

My JFrame Consists of three main parts a banner at top scrollpane containing a JTextArea center and a JTextField at the bottom. When I re-size the frame I adjust the columns and rows in my JTextArea. When making the frame larger the JTextArea expands visually but removes the scroll-bar. Then if I make the frame smaller the JTextArea stays the same size. This Is where I attempt to re-size my JTextArea.
frame.addComponentListener(new ComponentAdapter() {//Waits for window to be resized by user
public void componentResized(ComponentEvent e) {
uneditTextArea.setRows(((int)((frame.getHeight()-140)/18.8)));//sets Textarea size based on window size
uneditTextArea.setColumns(((int)((frame.getWidth()-100)/10.8)));
frame.revalidate();//refreshes screen
}
});
Why would the ScrollPane not re adjust to the change in size of the TextField.
The Rest of the code is below in case it is needed.
public class window extends JFrame
{
private static JFrame frame = new JFrame("Lillian");
private static JButton inputButton = new JButton("Send");
private static JTextField editTextArea = new JTextField(46);
private static JTextArea uneditTextArea = new JTextArea(26,50);
private static JPanel logoPanel = new JPanel();//Input text window
private static JPanel itextPanel = new JPanel();//Input text window
private static JPanel submitPanel = new JPanel();//Submit Button
private static JPanel bottom = new JPanel();//will contain scrollpane
private static JPanel middle = new JPanel();//willcontain itextpanel & submitbutton
private static JPanel otextPanel = new JPanel();//Text Output
public static void runWindow()
{
ImageIcon logo = new ImageIcon("Lillian_resize.png");//banner
ImageIcon icon = new ImageIcon("Lillian_icon.png");//application icon
frame.setIconImage(icon.getImage());
frame.setSize(660,640);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
logoPanel.setSize(10,10);
JLabel logoLabel = new JLabel(logo);
final JScrollPane scrollPane = new JScrollPane(otextPanel);//adds text to panel will scrollbar
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);//scrollbar only apears when more text than screen
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);//scrollbar never apears
scrollPane.setBorder(BorderFactory.createEmptyBorder());
logoPanel.add(logoLabel);
submitPanel.add(inputButton);
itextPanel.add(editTextArea);
otextPanel.add(uneditTextArea);
frame.getContentPane().add(logoPanel,"North");
frame.getContentPane().add(middle);
frame.getContentPane().add(bottom,"South");
middle.add(scrollPane,"North");//adds panels to outer panel
bottom.add(itextPanel, "West");
bottom.add(submitPanel, "East");
uneditTextArea.setLineWrap(true);
uneditTextArea.setWrapStyleWord(true);
uneditTextArea.setEditable(false);
uneditTextArea.setCaretPosition(uneditTextArea.getDocument().getLength());
frame.revalidate();//refreshes screen
//---------------wait for action------------
frame.addComponentListener(new ComponentAdapter() {//Waits for window to be resized by user
public void componentResized(ComponentEvent e) {
uneditTextArea.setRows(((int)((frame.getHeight()-140)/18.8)));//sets Textarea size based on window size
uneditTextArea.setColumns(((int)((frame.getWidth()-100)/10.8)));
frame.revalidate();//refreshes screen
}
});
}
}
There should be no need to use a ComponentListener to resize components. That is the job of the layout managers that you use to dynamically resize the components.
You should not be adding the text area to a JPanel first. Instead when using text areas you would generally add the text area directly to the viewport of a JScrollPane by using code like:
JScrollPane scrollPane = new JScrollPane( textArea );
Then you add the scrollpane to the frame with code like:
frame.add(scrollPane, BorderLayout.CENTER);
As you have noticed you should also NOT use hardcoded literals like "Center". Instead use the variables provided by the layout manager. Since you are using a BorderLayout, use the variables defined in the BorderLayout class.
Also, you should NOT be using static variable to create your GUI. I suggest you read the section from the Swing tutorial on Layout Manager. The tutorial will give you more information and the example code will show you how to better structure your program so that you don't need to use static variables.

How to make jtable on full jframe window

i am trying to create a jtable using java swing and little bit i am able to do this but problem is this that i want to create that jtable on full jframe window how can i do this here is my code given below
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
public class ScrollableJTable{
public static void main(String[] args) {
new ScrollableJTable();
}
public ScrollableJTable(){
JFrame frame = new JFrame("Creating a Scrollable JTable!");
JPanel panel = new JPanel();
String data[][] = {{"001"},
};
String col[] = {"Roll"};
JTable table = new JTable(data,col);
JTableHeader header = table.getTableHeader();
header.setBackground(Color.yellow);
Toolkit tk = Toolkit.getDefaultToolkit();
int xSize = ((int) tk.getScreenSize().getWidth());
int ySize = ((int) tk.getScreenSize().getHeight());
JScrollPane pane = new JScrollPane(table);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
panel.add(pane);
frame.add(panel);
frame.setSize(xSize,ySize);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
How can i achieve my desired output?
hanks in advance
Simple, set the layout manager for panel as BorderLayout or simple add the JScrollPane (pane) directly to the frame, which uses a BorderLayout by default
Take a look at Laying Out Components Within a Container for more details
cool..you do not need to write so many lines of code to display a file.Just download the jar file rs2xml and add it to your project library.
Note: This will be useful if you are using netbeans
How to use it?
create the table in backend
download rs2xml jar file
Add it to the project library
drag the jtable from the swing controls to your jframe
Now write the following code as follows:
write ur query:
ps=con.prepareStatement("select * from register");
ResultSet r=ps.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(r)); //display the register table

Updating JPanel's within a JScrollPane not working

I created a JScrollPane and want to display a different JPanel within that JScrollPane depending on input I get from the user. For some reason, my JScrollPane remains blank and never paints what is in the Panel.
private JScrollPane panelView;
// Creating my ScrollPane with a blank JPanel
panelView = new JScrollPane(new JPanel());
// Scenario1 is my top level JPanel, also contains a JTree
scenario1.add(panelView, BorderLayout.CENTER);
My code when I get the action to update the JPanel displayed. I've confirmed through the debugger that I'm hitting this code properly.
// Remove previous displayed JPanel within JScrollPane
panelView.removeAll();
if(node.equals(nodes.loginDefaultUser))
{
loginDefaultUserPanel = new LoginDefaultUserPanel();
panelView.add(loginDefaultUserPanel);
}
else if(node.equals(nodes.addUsers))
{
addUsersPanel = new AddUsersPanel();
panelView.add(addUsersPanel);
}
else if(node.equals(nodes.getVersions))
{
getVersionsPanel = new GetVersionsPanel();
panelView.add(getVersionsPanel);
}
panelView.revalidate();
panelView.repaint();
Use JScrollPane#setViewportView instead of add
You might find reviewing How to use Scroll Panes of use

JScrollBar Vertical/Horizontal setting problem- Java Swing

I am just trying to add a vertical scroll bar to my TextField and TextArea.
I am using a ScrollPane and it should create avertical/horizontal scroll bar by default.
Problem:
I need a vertical scroll bar to see the data which is not visible.
In the start a vertical scrollbar appears but when the data increases the vertical scrollbar changes to a horizontal scroll bar.
Also the TextField disappears and only a horizontal scrollbar appears in its place.
I guess it is because how I have set the bounds but I tried changing the bounds and it ends up completely doing away with the TextField.
My code snippet:
public JTextField inputField = new JTextField();
public JTextArea talkArea = new JTextArea();
public JScrollPane inputFieldScroll = new JScrollPane(inputField);
public JScrollPane talkAreaScroll = new JScrollPane(talkArea);
talkArea.setEditable(false);
talkArea.setBackground(Color.white);
talkAreaScroll.setBounds(new Rectangle(TALK_LEFT, TALK_TOP, TALK_WIDTH, TALK_HEIGHT));
this.getContentPane().add(talkAreaScroll, null);
//set input area
inputField.setBackground(Color.white);
inputField.setBounds(new Rectangle(INPUT_LEFT, INPUT_TOP, INPUT_WIDTH, INPUT_HEIGHT));
inputFieldScroll.setVerticalScrollBar(new JScrollBar());
inputFieldScroll.setBounds(new Rectangle(INPUT_LEFT, INPUT_TOP, INPUT_WIDTH, INPUT_HEIGHT));
Question:
Is there some parameter I need to set so that it remains a vertical scroll bar?
Why does the input scroll bar occupy the whole inputfield when the data becomes a huge line? It appears as a proper vertical scrollbar in the start.
Any advice appreciated.
Thanks
Below is a small compilable code snippet I mentioned above. I agree with camickr that you should not be using absolute positioning but rather use the layout managers. If you absolutely need to have a horizontal scrollbar for the JTextField, then one way to get it to work is to have it show up always, using the JScrollPane constructor that allows for this. i.e,
JScrollPane inputPane = new JScrollPane(inputField, JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
For e.g.,
import java.awt.*;
import javax.swing.*;
public class FuSwing1b extends JPanel {
private static final int TA_ROWS = 25;
private static final int TA_COLS = 60;
private JTextField inputField = new JTextField();
private JTextArea talkArea = new JTextArea(TA_ROWS, TA_COLS);
public FuSwing1b() {
talkArea.setEditable(false);
talkArea.setFocusable(false);
talkArea.setBackground(Color.white);
//talkArea.setPreferredSize(new Dimension(TALK_WIDTH, TALK_HEIGHT));
JScrollPane talkPane = new JScrollPane(talkArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JScrollPane inputPane = new JScrollPane(inputField, JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
int gap = 10;
setLayout(new BorderLayout(gap, gap));
add(talkPane, BorderLayout.CENTER);
add(inputPane, BorderLayout.SOUTH);
setBorder(BorderFactory.createEmptyBorder(gap , gap, gap, gap));
}
private static void createAndShowUI() {
JFrame frame = new JFrame("FuSwing1b");
frame.getContentPane().add(new FuSwing1b());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Don't play with the bounds. Use a layout manager and you won't have to worry about this.
When you create the text field use something like:
JTextField textField = new JTextField(10);
This will create a text field that will hold a minimum of 10 characters. If the number of characters exceeds the display width of the text field the use can see the remaining characters by using the right/left arrow keys. That is the normal UI used by all applications I have ever seen. Don't try to create your own UI by using a horizontal scrollbar. Users are not accustomed to that.
for the text area you can create it using:
JTextArea textArea = new JTextArea(5, 30);
JScrollPane scrollPane = new JScrollPane( textArea );
to create a text area with 5 rows and approximately 30 character per row.
Now add the text field and the scrollpane to your frame "using layout managers" and then pack the frame. The layout managers will determine the best size for the compoents. Scrollbars will automatically appear on the text area as you add text to it and the text exceeds 5 lines.

Categories

Resources