JTable in eclipse not showing column names - java

Neither JTable is showing column names as title nor I have scrollBar when I add data manually.
code for JTable and JScrollPane:
private JPanel contentPane = new JPanel();
Object[] title = {"ISBN", "Name", "Author", "Shelf No", "Row No", "Col No"};
DefaultTableModel dtm = new DefaultTableModel();
dtm.setColumnIdentifiers(title);
table = new JTable(dtm);
table.setBounds(23, 55, 435, 217);
table.setModel(dtm);
JScrollPane scroll = new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
table.setForeground(Color.gray);
table.setRowHeight(30);
contentPane.add(scroll);
contentPane.add(table);
Object[] row = {"hi", "2", "3", "5", "r", "we" };
ActionListener to add data in table:
btnSearch.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
dtm.addRow(row);
}
});
As you can see in image below, I don't have those columns(title) and scrollbar.

Do following changes into your code,
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import com.my.classes.Validation;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class SearchBooks extends JFrame {
private JPanel contentPane;
private JTextField txtIsbn;
private Validation v = new Validation();
private JTable table;
DefaultTableModel dtm ;
Object[] row = {"hi", "2", "3", "5", "r", "we" };
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SearchBooks frame = new SearchBooks();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SearchBooks() {
setTitle("Search Books from Database");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//setBounds(100, 100, 502, 341); instead of it use pack() see below it's uses at right place not here...
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
//contentPane.setLayout(null);
JLabel lblBookName = new JLabel("Book Name: ");
lblBookName.setFont(new Font("Tahoma", Font.BOLD, 11));
lblBookName.setBounds(23, 11, 80, 14);
contentPane.add(lblBookName);
txtIsbn = new JTextField();
txtIsbn.setBounds(113, 8, 202, 20);
contentPane.add(txtIsbn);
txtIsbn.setColumns(10);
JButton btnSearch = new JButton("Search");
btnSearch.setFont(new Font("Tahoma", Font.BOLD, 11));
btnSearch.setBounds(338, 7, 103, 23);
contentPane.add(btnSearch);
Object[] title = {"ISBN", "Name", "Author", "Shelf No", "Row No", "Col No"};
dtm = new DefaultTableModel();
dtm.setColumnIdentifiers(title);
table = new JTable(dtm);
table.setBounds(23, 55, 435, 217);
table.setModel(dtm);
//JScrollPane scroll = new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JScrollPane scroll = new JScrollPane(table);
table.setFillsViewportHeight(true);
table.setForeground(Color.RED);
table.setRowHeight(30);
contentPane.add(scroll);
// contentPane.add(table); //comment it...
//dtm.addRow(title); doesn't required because already header is there...
pack();
txtIsbn.addKeyListener(
new KeyAdapter() {
public void keyPressed(KeyEvent ev) {
if(ev.getKeyCode() == KeyEvent.VK_ENTER) {
if(v.validateIsbn(txtIsbn.getText()) || v.validateAddress(txtIsbn.getText())) {
}else {
JOptionPane.showMessageDialog(null, "Error! Please check your input");
}
}
}
});
btnSearch.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
table.setForeground(Color.BLACK);
dtm.addRow(row);
}
});
}
}
Otu-Put :

You are not adding your JTable to the scrollpane but to your contentpane. Try this instead:
contentPane.add(scroll);
scroll.add(table); //instead of contentPane.add(table)

The JTable column headers are displayed in the JScrollPane, so this is correct:
contentPane.add(scroll);
Don't immediately then replace the scroll pane with the table:
//contentPane.add(table);
Instead of setBounds(), override getPreferredScrollableViewportSize(), as suggested here. Because the default layout of JPanel is FlowLayout, the table will remain a fixed size. Consider GridLayout, which will allow the display to reflect changes as the enclosing frame is resized.
JPanel contentPane = new JPanel(new GridLayout());

Related

How do you add a JPanel from another class to a panel with CardLayout?

I'm working on a group project and I'm the one making the GUI figuring it'd be good to practice with it. The program is supposed to be a pizza ordering system (pretty standard stuff) and what I'm trying to accomplish is that I have a main class that creates an application window. Inside this window is a panel that uses CardLayout with a button that when pressed calls another JPanel from another class dedicated specifically to that panel and places it as a card in the layout to be swapped back and forth from as normal.
What I have so far are the different panels I wish to call and the main class which has the window and main card panel. I can have it swap easily between panels created within the main class but when I try to use the panels from the other classes it just swaps to a blank panel when it should show the other class's panel.
The main class
package PizzaGUI;
import java.awt.EventQueue;
import java.awt.CardLayout;
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Font;
public class PizzaSystem {
private JFrame frame;
Toppings toppingsPanel;
MainMenu menuPanel;
JButton loginBtn;
JPanel mainPanel;
CardLayout cl;
//MAIN
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaSystem window = new PizzaSystem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Constructor
public PizzaSystem() {
initialize();
}
//Initialize the GUI
private void initialize() {
cl = new CardLayout();
frame = new JFrame();
frame.setBounds(100, 100, 893, 527);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
mainPanel = new JPanel();
mainPanel.setBounds(10, 10, 859, 470);
frame.getContentPane().add(mainPanel);
mainPanel.setLayout(cl);
JPanel panel_2 = new JPanel();
mainPanel.add(panel_2, "test");
panel_2.setLayout(null);
JLabel lblNewLabel = new JLabel("It Worked");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 45));
lblNewLabel.setBounds(282, 118, 312, 103);
panel_2.add(lblNewLabel);
JPanel panel_1 = new JPanel();
loginBtn = new JButton();
loginBtn.setText("Login");
loginBtn.setBounds(175, 72, 199, 154);
loginBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCard("menu");
}
});
panel_1.add(loginBtn);
mainPanel.add(panel_1, "loginPanel");
JPanel menuPanel = new MainMenu();
mainPanel.add(menuPanel, "menu");
showCard("loginPanel");
}
//Call card matching the key
public void showCard(String key) {
cl.show(mainPanel, key);
}
}
and one of the classes with the panel (format is messed up but should work still)
package PizzaGUI;
import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.BevelBorder;
public class MainMenu extends JPanel {
public MainMenu() {
JPanel panel1 = new JPanel();
panel1.setBounds(100, 100, 893, 572);
panel1.setBackground(Color.PINK);
panel1.setLayout(null);
panel1.setVisible(true);
JLabel logoLabel = new JLabel("");
logoLabel.setBounds(10, 10, 100, 110);
panel1.add(logoLabel);
ImageIcon image1 = new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\MamaJane1.png");
logoLabel.setIcon(new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\MamaJane.png"));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(133, 113, 548, 402);
tabbedPane.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
tabbedPane.setBackground(Color.PINK);
tabbedPane.setForeground(Color.GRAY);
tabbedPane.setFont(new Font("Tahoma", Font.PLAIN, 20));
tabbedPane.setToolTipText("");
panel1.add(tabbedPane);
JPanel panel = new JPanel();
tabbedPane.addTab("MENU", null, panel, null);
panel.setLayout(null);
//*******************************************************************************************************
//Pepperoni menu section
JLabel pizza1Image = new JLabel("IMAGE");
pizza1Image.setBounds(6, 25, 100, 100);
panel.add(pizza1Image);
ImageIcon image2 = new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\Pepperoni.jpg");
Image pizza1 = image2.getImage();
Image pepperoni = pizza1.getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH);
image2 = new ImageIcon(pepperoni);
pizza1Image.setIcon(image2);
JLabel pepperoniLabel = new JLabel("PEPPERONI");
pepperoniLabel.setHorizontalAlignment(SwingConstants.CENTER);
pepperoniLabel.setBounds(110, 25, 86, 48);
pepperoniLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
panel.add(pepperoniLabel);
JButton pepperoniOrderBtn = new JButton("ORDER");
pepperoniOrderBtn.setBounds(110, 79, 86, 47);
panel.add(pepperoniOrderBtn);
pepperoniOrderBtn.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
//Pepperoni End
JButton accountButton = new JButton("Account");
accountButton.setBounds(10, 414, 113, 39);
accountButton.setBackground(Color.WHITE);
panel.add(accountButton);
JButton checkoutButton = new JButton("Checkout");
checkoutButton.setBounds(713, 438, 138, 31);
panel.add(checkoutButton);
JButton logoutButton = new JButton("Logout");
logoutButton.setBounds(10, 463, 113, 52);
panel.add(logoutButton);
JTextArea txtrOrderInfoGoes = new JTextArea();
txtrOrderInfoGoes.setBounds(703, 10, 154, 418);
txtrOrderInfoGoes.setText("Order Info\r\nGoes Here\r\n\r\nPepperoni Pizza x1\r\n$6.50");
panel.add(txtrOrderInfoGoes);
JButton clearOrderButton = new JButton("Clear");
clearOrderButton.setBounds(723, 479, 113, 36);
panel.add(clearOrderButton);
JLabel titleLabel = new JLabel("MAMA JANE'S PIZZERIA");
titleLabel.setBounds(147, 10, 534, 65);
panel.add(titleLabel);
titleLabel.setFont(new Font(titleLabel.getFont().getName(), Font.PLAIN, 50));
JLabel storeInfoLabel = new JLabel("<html>1234 Fakelane Rd <br> 10001, Faketopia, USA <br> 111-11-PIZZA <br> Mon-Fri 11AM to 10pm <br> Sat-Sun 10AM to 11pm");
storeInfoLabel.setBounds(10, 130, 113, 274);
panel.add(storeInfoLabel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(406, 85, 2, 2);
panel.add(scrollPane);
logoutButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
}
I can't tell where I've gone wrong and I've spent roughly the last three hours trying to fix this and searching the internet for answers to no avail so thank you in advance if you can help me out.
Also I apologize in advance, I know I end up misusing the proper terminology for programming alot, I understand what things are just forget what to properly call them sometimes.
So, basically, I took out all the null layouts and "manual" layout code, as it's just going to mess with you to no end AND added add(panel1); to the end of the MainMenu constructor - as, I've said, NOTHING was added to MainMenu, so, nothing was going to get displayed.
Before you tell me that "this isn't the layout I want", understand that I understand that, but my point is, null layouts are a really bad idea, as almost the entire Swing API relies the layout managers in one way or another.
I appreciate that layout management can seem like a complex subject, but it solves some very complex problems and it's worth taking the time to learn them. Remember, you're not stuck to a single layout manager, you can use component components to adjust individual containers to their individual needs.
You can take a look at:
Layout using Java Swing
Which Layout Manager to use?
How I can do swing complex layout Java
How to use Java Swing layout manager to make this GUI?
*Which java swing layout should I use
to some ideas how you might approach designing a complex UI.
You should also take a look at Laying Out Components Within a Container
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagLayout;
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.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
public class PizzaSystem {
private JFrame frame;
// Toppings toppingsPanel;
MainMenu menuPanel;
JButton loginBtn;
JPanel mainPanel;
CardLayout cl;
//MAIN
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaSystem window = new PizzaSystem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Constructor
public PizzaSystem() {
initialize();
}
//Initialize the GUI
private void initialize() {
cl = new CardLayout();
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel(cl);
frame.getContentPane().add(mainPanel);
JPanel panel_1 = new JPanel(new GridBagLayout());
loginBtn = new JButton();
loginBtn.setText("Login");
loginBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCard("menu");
}
});
panel_1.add(loginBtn);
mainPanel.add(panel_1, "loginPanel");
JPanel menuPanel = new MainMenu();
mainPanel.add(menuPanel, "menu");
frame.pack();
showCard("loginPanel");
}
//Call card matching the key
public void showCard(String key) {
cl.show(mainPanel, key);
}
public class MainMenu extends JPanel {
public MainMenu() {
JPanel panel1 = new JPanel(new BorderLayout());
JLabel logoLabel = new JLabel("Logo");
panel1.add(logoLabel, BorderLayout.NORTH);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setToolTipText("");
panel1.add(tabbedPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
tabbedPane.addTab("MENU", null, panel, null);
//*******************************************************************************************************
//Pepperoni menu section
JLabel pizza1Image = new JLabel("IMAGE");
panel.add(pizza1Image);
JLabel pepperoniLabel = new JLabel("PEPPERONI");
pepperoniLabel.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(pepperoniLabel);
JButton pepperoniOrderBtn = new JButton("ORDER");
pepperoniOrderBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
//Pepperoni End
JButton accountButton = new JButton("Account");
panel.add(accountButton);
JButton checkoutButton = new JButton("Checkout");
panel.add(checkoutButton);
JButton logoutButton = new JButton("Logout");
panel.add(logoutButton);
JTextArea txtrOrderInfoGoes = new JTextArea(10, 20);
txtrOrderInfoGoes.setText("Order Info\r\nGoes Here\r\n\r\nPepperoni Pizza x1\r\n$6.50");
panel.add(txtrOrderInfoGoes);
JButton clearOrderButton = new JButton("Clear");
panel.add(clearOrderButton);
JLabel titleLabel = new JLabel("MAMA JANE'S PIZZERIA");
panel.add(titleLabel);
titleLabel.setFont(new Font(titleLabel.getFont().getName(), Font.PLAIN, 50));
JLabel storeInfoLabel = new JLabel("<html>1234 Fakelane Rd <br> 10001, Faketopia, USA <br> 111-11-PIZZA <br> Mon-Fri 11AM to 10pm <br> Sat-Sun 10AM to 11pm");
panel.add(storeInfoLabel);
JScrollPane scrollPane = new JScrollPane();
panel.add(scrollPane);
logoutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
add(panel1);
}
}
}

How to add some row's specific info to JTexFields using MySQL

I have been trying to add a table rows' info to JTextField components after clicking with the mouse however it doesn't work. I have used the DefaultTableModel and JTable as shown below.
Here is the code I have been using.
package scrCode;
import java.util.*;
import java.sql.*;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import net.proteanit.sql.DbUtils;
import javax.swing.JTable;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import java.awt.SystemColor;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JComboBox;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class BorrowABook extends JFrame {
private JPanel contentPane;
private JTable table;
private JButton button;
private JLabel lblBookId;
private JTextField textFieldBookID;
private JLabel lblMemberId;
private JTextField textFieldMemberID;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BorrowABook frame = new BorrowABook();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public BorrowABook() {
setTitle("Library system");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 971, 594);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
String data [][]=null;
String column []=null;
DefaultTableModel model = new DefaultTableModel();
try {
//code to receive data from the database
Connection con=DB.login();
PreparedStatement ps=con.prepareStatement("select * from book",ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
int cols=rsmd.getColumnCount();
column=new String[cols];
for(int i=1;i<=cols;i++){
column[i-1]=rsmd.getColumnName(i);
}
rs.last();
int rows=rs.getRow();
rs.beforeFirst();
data=new String[rows][cols];
int count=0;
while(rs.next()){
for(int i=1;i<=cols;i++){
data[count][i-1]=rs.getString(i);
}
count++;
}
con.close();
}catch (Exception e){
System.out.println(e);
}
contentPane.setLayout(null);
table = new JTable(data,column);
JScrollPane sp = new JScrollPane(table);
sp.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
int selectedRowIndex = table.getSelectedRow();
textFieldBookID.setText(model.getValueAt(selectedRowIndex, 0).toString());
textFieldMemberID.setText(model.getValueAt(selectedRowIndex, 1).toString());
}
});
sp.setBounds(5, 5, 936, 402);
contentPane.add(sp);
button = new JButton("Back");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
UserSection.main(new String [] {});
dispose();
}
});
button.setForeground(Color.BLACK);
button.setBackground(SystemColor.info);
button.setBounds(856, 509, 85, 25);
contentPane.add(button);
lblBookId = new JLabel("Book ID:");
lblBookId.setHorizontalAlignment(SwingConstants.RIGHT);
lblBookId.setFont(new Font("Sitka Display", Font.BOLD, 22));
lblBookId.setBounds(28, 420, 141, 29);
contentPane.add(lblBookId);
textFieldBookID = new JTextField();
textFieldBookID.setColumns(10);
textFieldBookID.setBounds(181, 420, 257, 29);
contentPane.add(textFieldBookID);
lblMemberId = new JLabel("Memeber ID:");
lblMemberId.setHorizontalAlignment(SwingConstants.RIGHT);
lblMemberId.setFont(new Font("Sitka Display", Font.BOLD, 22));
lblMemberId.setBounds(28, 469, 141, 29);
contentPane.add(lblMemberId);
textFieldMemberID = new JTextField();
textFieldMemberID.setColumns(10);
textFieldMemberID.setBounds(181, 469, 257, 29);
contentPane.add(textFieldMemberID);
}
}
Suggestions:
Add your MouseListener to your JTable, not to the JScrollPane. You need notification for when the table has been clicked.
You're using the wrong model in your listener as you never fill the DefaultTableModel with data. Be safe and get the model in the listener via table.getModel()
No null layouts. While this is not causing your current problem, it forces you to code against the library rather than with it.
For example (database code removed for simplicity, null layout removed as well, and posted a MCVE):
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class BorrowABook extends JFrame {
private JPanel contentPane;
private JTable table;
private JButton button;
private JLabel lblBookId;
private JTextField textFieldBookID;
private JLabel lblMemberId;
private JTextField textFieldMemberID;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BorrowABook frame = new BorrowABook();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public BorrowABook() {
setTitle("Library system");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 971, 594);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
String data[][] = {{"1", "2", "3"}, {"4", "5", "6"}, {"7", "8", "9"}};
String column[] = {"One", "Two", "Three" };
DefaultTableModel model = new DefaultTableModel();
// !! contentPane.setLayout(null);
contentPane.setLayout(new BorderLayout());
table = new JTable(data, column);
JScrollPane sp = new JScrollPane(table);
table.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
int selectedRowIndex = table.getSelectedRow();
textFieldBookID.setText(table.getModel().getValueAt(selectedRowIndex, 0).toString());
textFieldMemberID.setText(table.getModel().getValueAt(selectedRowIndex, 1).toString());
}
});
//!! sp.setBounds(5, 5, 936, 402);
contentPane.add(sp);
JPanel bottomPanel = new JPanel();
lblBookId = new JLabel("Book ID:");
lblBookId.setHorizontalAlignment(SwingConstants.RIGHT);
lblBookId.setFont(new Font("Sitka Display", Font.BOLD, 22));
bottomPanel.add(lblBookId);
textFieldBookID = new JTextField();
textFieldBookID.setColumns(10);
textFieldBookID.setBounds(181, 420, 257, 29);
bottomPanel.add(textFieldBookID);
lblMemberId = new JLabel("Memeber ID:");
lblMemberId.setHorizontalAlignment(SwingConstants.RIGHT);
lblMemberId.setFont(new Font("Sitka Display", Font.BOLD, 22));
lblMemberId.setBounds(28, 469, 141, 29);
bottomPanel.add(lblMemberId);
textFieldMemberID = new JTextField();
textFieldMemberID.setColumns(10);
textFieldMemberID.setBounds(181, 469, 257, 29);
bottomPanel.add(textFieldMemberID);
contentPane.add(bottomPanel, BorderLayout.PAGE_END);
}
}

JPanel won't show up in JFrame

Why does my JPanel not show in JFrame after button is clicked.
There's my code:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.DefaultListModel;
import javax.swing.AbstractListModel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
public class Main {
private JFrame frame;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Main() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
{"1", "Marcin Zelek", "537573656"},
{"2", "Krzysztof Tomala", "324159103"},
{"3", "Zbigniew S", "324159104"},
},
new String[] {
"#", "Name", "Phone number"
}
));
table.getColumnModel().getColumn(1).setPreferredWidth(214);
table.getColumnModel().getColumn(2).setPreferredWidth(246);
table.setBounds(12, 103, 426, 185);
frame.getContentPane().add(table);
JButton btnDodajNowy = new JButton("Dodaj nowy");
btnDodajNowy.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
JPanel panel = new JPanel(null);// Creating the JPanel
panel.setBounds(0, 243, 286, 150);
panel.setVisible(true);
JButton button = new JButton("New button");
button.setBounds(12, 12, 117, 25);
panel.add(button);
frame.getContentPane().add(panel);
}
});
btnDodajNowy.setBounds(12, 30, 117, 25);
frame.getContentPane().add(btnDodajNowy);
JButton btnUsuZaznaczone = new JButton("UsuĊ„ zaznaczone");
btnUsuZaznaczone.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
int[] selection = table.getSelectedRows();
for (int i = 0; i < selection.length; i++)
{
model.removeRow(selection[i]-i);
}
}
});
btnUsuZaznaczone.setBounds(141, 30, 204, 25);
frame.getContentPane().add(btnUsuZaznaczone);
}
}
Thanks.
You should use actionListener instead:
btnDodajNowy.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel panel = new JPanel();// Creating the JPanel
panel.setBounds(0, 243, 286, 150);
JButton button = new JButton("New button");
button.setBounds(12, 12, 117, 25);
panel.add(button);
frame.getContentPane().add(panel);
frame.repaint();
}
});
and also:
You don't need to pass null as a parameter to the JPanel constructor
You might want to add a frame.repaint()
You don't need to set the JPanel to visible via setVisible().
If you looking to present the panel in same jframe where you added the button you probably should use CardLayout here is the link http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html
It is being added, however, it is hiding below the JTable. The quickest fix is this:
public void mouseReleased(MouseEvent arg0) {
//...
panel.setBounds(0, 300, 286, 150); // 300 is on the y axis
//...
// then render the frame again:
frame.revalidate();
frame.repaint();
}
However, I suggest to rewrite it a little:
this.generalPanel = new JPanel();
frame.getContentPane().add(generalPanel);
...
generalPanel.add(table);
This way you'll get a good Layout for the topmost container.

After adding a JTable to a JScrollPane, the button can't be clicked, why?

public JFrame myUI = new JFrame();
public Container pane = myUI.getContentPane() ;
private JTabbedPane tabbedPane = new JTabbedPane();
private void makeTabbedPane(){
JPanel tabs = new JPanel();
String tabsName = "tags";
Object columnNames[] = { "id", "name"};
Object rowData[][] = {
{ "1", "Jean"},
{ "2", "Annie"}
};
DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
JTable tagsTable = new JTable(model);
tagsTable.setRowHeight(24);
JTableHeader header = tagsTable.getTableHeader();
header.setFont(new Font("", Font.BOLD,20));
JScrollPane jsp = new JScrollPane(tagsTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tabs.setLayout(new BorderLayout());
tabs.add(header, BorderLayout.NORTH);
tabs.add(jsp, BorderLayout.CENTER);
tabs.add(new JButton("OK"), BorderLayout.SOUTH);
tabbedPane.addTab(tabsName, tabs);
}
myUI.add(tabbedPane);
}
After I create a JScrollPane and add it to BorderLayout.CENTER, the JButton"OK" can't be clicked!
(The button looks enabled, but when you can't click on it)
If I don't create JScrollPane, just add the JTable to JPanel tabs, the JButton"OK" will be clickable.
Why is that and how to solve it?
Problem has to do with you adding the table header to the panel. Can't really explain why. Have to look into it. But when you add a table to a scroll pane, it adds the table header for you implicitly. So just get rid of
//tabs.add(header, BorderLayout.NORTH);
Here's an MCVE for others to test out. Maybe someone else has an explanation :-)
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
public class TestTable {
public JFrame myUI = new JFrame();
private JTabbedPane tabbedPane = new JTabbedPane();
public TestTable() {
makeTabbedPane();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new TestTable();
}
});
}
private void makeTabbedPane() {
JPanel tabs = new JPanel();
String tabsName = "tags";
Object columnNames[] = {"id", "name"};
Object rowData[][] = {
{"1", "Jean"},
{"2", "Annie"}
};
DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
JTable tagsTable = new JTable(model);
tagsTable.setRowHeight(24);
JTableHeader header = tagsTable.getTableHeader();
header.setFont(new Font("", Font.BOLD, 20));
JScrollPane jsp = new JScrollPane(tagsTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tabs.setLayout(new BorderLayout());
//tabs.add(header, BorderLayout.NORTH);
tabs.add(jsp, BorderLayout.CENTER);
tabs.add(new JButton("OK"), BorderLayout.SOUTH);
tabbedPane.addTab(tabsName, tabs);
myUI.add(tabbedPane);
myUI.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
myUI.pack();
myUI.setLocationRelativeTo(null);
myUI.setVisible(true);
}
}

MigLayout resizing with JScrollPane

I searched a little bit and did not find a good answer to my problem.
I am working on a gui that has to be resizable. It contains a status JTextArea that is inside a JScrollPane. And this is my problem. As long as I don't manually resize my JFrame, the "initial" layout is kept and everything looks fine. As soon as I manually resize (if the JTextArea is already in scrolled mode), the layout gets messed up.
Here is a SSCCE (I got rid of most of the parts while keeping the structure of the code. I hope it's more readable that way):
import java.awt.Color;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import net.miginfocom.swing.MigLayout;
public class Tab extends JFrame {
private static final long serialVersionUID = 1L;
private JTextArea messageTextArea;
private JPanel optionPanel, messagePanel;
private JTabbedPane plotTabPane;
public static void main(String[] args) {
final Tab tab = new Tab();
tab.setSize(1000, 600);
tab.setVisible(true);
new Thread(new Runnable() {
#Override
public void run() {
int count = 0;
tab.printRawMessage("start");
while (true) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {}
tab.printRawMessage("\ntestMessage" + count++);
}
}
}).start();
}
public Tab() {
super();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
}
private void initComponents() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new MigLayout("insets 0", "", ""));
mainPanel.add(getLeftTopPanel(), "shrinky, top, w 450!");
mainPanel.add(getRightPanel(), "spany 5, wrap, grow, pushx, wmin 400");
mainPanel.add(getMessagePanel(), "pushy, growy, w 450!");
JScrollPane contentScrollPane = new JScrollPane(mainPanel);
contentScrollPane.setBorder(BorderFactory.createEmptyBorder());
setContentPane(contentScrollPane);
}
protected JPanel getLeftTopPanel() {
if (optionPanel == null) {
optionPanel = new JPanel();
optionPanel.setBorder(BorderFactory.createTitledBorder(null, "Configuration", TitledBorder.LEFT, TitledBorder.TOP, new Font("null", Font.BOLD, 12), Color.BLUE));
optionPanel.setLayout(new MigLayout("insets 0", "", "top, align 50%"));
JLabel label = new JLabel("Choose");
label.setHorizontalAlignment(JLabel.RIGHT);
optionPanel.add(label, "w 65!");
optionPanel.add(new JSeparator(JSeparator.VERTICAL), "spany 5, growy, w 2!");
optionPanel.add(new JComboBox(new String[] {"option1", "option2", "option3"}), "span, growx, wrap");
optionPanel.add(new JLabel("Type"), "right");
optionPanel.add(new JTextField("3"), "w 65!, split 2");
optionPanel.add(new JLabel("Unit"), "wrap");
optionPanel.add(new JLabel("Slide"), "right");
optionPanel.add(new JSlider(0, 100), "span, growx, wrap");
}
return optionPanel;
}
protected JTabbedPane getRightPanel() {
if (plotTabPane == null) {
plotTabPane = new JTabbedPane();
plotTabPane.add("Tab1", new JPanel());
plotTabPane.add("Tab2", new JPanel());
}
return plotTabPane;
}
protected JPanel getMessagePanel() {
if (messagePanel == null) {
messagePanel = new JPanel();
messagePanel.setBorder(BorderFactory.createTitledBorder(null, "Status Console", TitledBorder.LEFT, TitledBorder.TOP, new Font("null", Font.BOLD, 12), Color.BLUE));
messagePanel.setLayout(new MigLayout("insets 0", "", "top, align 50%"));
messagePanel.add(new JScrollPane(getMessageTextArea()), "push, grow");
}
return messagePanel;
}
protected JTextArea getMessageTextArea() {
if (messageTextArea == null) {
messageTextArea = new JTextArea();
messageTextArea.setEditable(false);
messageTextArea.setFont(new Font(null, Font.PLAIN, 20));
messageTextArea.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
}
return messageTextArea;
}
public void printRawMessage(String rawMessage) {
getMessageTextArea().append(rawMessage);
getMessageTextArea().setCaretPosition(getMessageTextArea().getText().length());
}
}
The layout stuff basically happens in initComponents().
To see the problem:
Start the Application (I used miglayout-4.0-swing.jar).
Wait a bit (don't resize the window), until there are enough messages to create the scrollbar in the status text area.
Now this is what I want. The JTextArea goes all the way to the bottom of the JFrame and is scrolled if neccessary.
Now resize the window. As you can see, everything gets messed up. It will only be fine, if the window is maximized.
Here are two screenshots. The first one is how I want it to be:
The second one is after resizing:
My question: Can somebody tell me, how I keep the layout the way it is before resizing? I want to have the JTextArea go all the way down to the bottom of the window. And if neccessary, the scrollbar should appear. The only way, the status panel can go below the bottom of the window is, if the window is too small (because the configuration panel has a fixed height).
I hope I made myself clear. If not, please ask. ;)
EDIT: You can see the behaviour I want, if you remove the top JScrollPanel (the one that holds all the components). Just change
JScrollPane contentScrollPane = new JScrollPane(mainPanel);
contentScrollPane.setBorder(BorderFactory.createEmptyBorder());
setContentPane(contentScrollPane);
to
setContentPane(mainPanel);
to see what I mean. Unfortunately, this way I loose the scrollbars if the window is very small.
Focusing on your status area and using nested layouts produces the result shown below. Note in particular,
Use invokeLater() to construct the GUI on the EDT.
Use javax.swing.Timer to update the GUI on the EDT.
Use pack() to make the window fit the preferred size and layouts of its subcomponents.
Use the update policy of DefaultCaret to control scrolling.
Avoid needless lazy instantiation in public accessors.
Avoid setXxxSize(); override getXxxSize() judiciously.
Critically examine the decision to extend JFrame.
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.border.TitledBorder;
import javax.swing.text.DefaultCaret;
public class Tab extends JFrame {
private JTextArea messageTextArea;
private JPanel optionPanel, messagePanel;
private JTabbedPane plotTabPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
final Tab tab = new Tab();
tab.setVisible(true);
Timer t = new Timer(200, new ActionListener() {
int count = 0;
#Override
public void actionPerformed(ActionEvent e) {
tab.printRawMessage("testMessage" + count++);
}
});
t.start();
}
});
}
public Tab() {
initComponents();
}
private void initComponents() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel(new GridLayout(1, 0));
Box leftPanel = new Box(BoxLayout.Y_AXIS);
leftPanel.add(getLeftTopPanel());
leftPanel.add(getMessagePanel());
mainPanel.add(leftPanel);
mainPanel.add(getRightPanel());
this.add(mainPanel);
this.pack();
this.setLocationRelativeTo(null);
}
protected JPanel getLeftTopPanel() {
optionPanel = new JPanel();
optionPanel.setBorder(BorderFactory.createTitledBorder(null,
"Configuration", TitledBorder.LEFT, TitledBorder.TOP,
new Font("null", Font.BOLD, 12), Color.BLUE));
JLabel label = new JLabel("Choose");
label.setHorizontalAlignment(JLabel.RIGHT);
optionPanel.add(label);
optionPanel.add(new JSeparator(JSeparator.VERTICAL));
optionPanel.add(new JComboBox(
new String[]{"option1", "option2", "option3"}));
optionPanel.add(new JLabel("Type"));
optionPanel.add(new JTextField("3"));
return optionPanel;
}
protected JTabbedPane getRightPanel() {
plotTabPane = new JTabbedPane();
plotTabPane.add("Tab1", new JPanel());
plotTabPane.add("Tab2", new JPanel());
return plotTabPane;
}
protected JPanel getMessagePanel() {
messagePanel = new JPanel(new GridLayout());
messagePanel.setBorder(BorderFactory.createTitledBorder(null,
"Status Console", TitledBorder.LEFT, TitledBorder.TOP,
new Font("null", Font.BOLD, 12), Color.BLUE));
final JScrollPane sp = new JScrollPane(getMessageTextArea());
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
messagePanel.add(sp);
return messagePanel;
}
protected JTextArea getMessageTextArea() {
messageTextArea = new JTextArea("", 10, 19);
messageTextArea.setEditable(false);
messageTextArea.setFont(new Font(null, Font.PLAIN, 20));
messageTextArea.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
DefaultCaret caret = (DefaultCaret) messageTextArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
return messageTextArea;
}
public void printRawMessage(String rawMessage) {
messageTextArea.append(rawMessage + "\n");
}
}
Add size constraints to your mainPanel in the initComponents method. For instance :
mainPanel.setMinimumSize(new Dimension(400, 400));
mainPanel.setPreferredSize(new Dimension(400, 400));
mainPanel.setMaximumSize(new Dimension(400, 400));

Categories