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);
}
}
Related
I tried to add a button to the JFrame, but it won't appear for some reason. How do I make it appear?
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Container;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.*;
public class GraficoconArreglo extends javax.swing.JFrame {
JPanel pan = (JPanel) this.getContentPane();
JLabel []lab = new JLabel[6];
JTextField []text = new JTextField[6];
Border border = BorderFactory.createLineBorder(Color.pink,1);
JButton b = new JButton("Calculate");
public GraficoconArreglo() {
initComponents();
pan.setLayout(null);
pan.setBackground(Color.GRAY);
for(int i=0; i<lab.length ;i++){
lab[i] = new JLabel();
text[i] = new JTextField();
lab[i].setBounds(new Rectangle(15,(i+1)*40, 60, 25));
lab[i].setText("Data " + (i+1));
lab[i].setBorder(border);
text[i].setBounds(new Rectangle(100,(i+1)*40, 60, 25));
pan.add(lab[i],null);
pan.add(text[i],null);
setSize(200,330);
setTitle("Arrays in forums.");
add(b);
b.addActionListener((ActionListener) this);
}
}
You are creating only one button and adding it to 6 different places. Therefore, you only would see it on the last place you added.
You should add the button to the contentPane, not the JFrame. A working code for this, provided from SwingDesigner from Eclipse Marketplace would be:
public class Window extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window frame = new Window();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Window() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(170, 110, 89, 23);
contentPane.add(btnNewButton);
}
}
My JTextField and JLabel are not Transparent in JPanel When JTable is visible it overlap between JTextField and JLabel. I want to show JTable when i Search something in Search (JTextField) but it overlap and JTable is not visible properly. Please Help here is my code:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.border.BevelBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import com.alee.laf.WebLookAndFeel;
import java.awt.Color;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.JTable;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JScrollPane;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLayeredPane;
public class ButtonBarExample1 {
private JFrame frame;
private JTextField Search;
private JTable CategoryTable;
private DefaultTableModel model;
private static Connection con;
private String query;
private PreparedStatement PStat;
private ResultSet res;
private JScrollPane scrollPane;
private int Enter=0;
private JPanel panel;
private JLabel label;
private JLabel label_1;
private JTextField CategoryID;
private JTextField CategoryName;
private JPanel panel_1;
/**
* Launch the application.
*/
public static void main(String\[\] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WebLookAndFeel.install();
ButtonBarExample1 window = new ButtonBarExample1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ButtonBarExample1() {
initialize();
con=Database.Database();
}
public void remove(){
while(CategoryTable.getRowCount()>0) {
model.removeRow(0);
}
}
public void changed(){
if(Search.getText().length()==0){
panel.remove(scrollPane);
panel.repaint();
panel.revalidate();
}else{
try{
panel.add(scrollPane);
scrollPane.setViewportView(CategoryTable);
remove();
query="Select * from CategoryEntry where Category_Name like '"+Search.getText().trim()+"%'";
PStat=con.prepareStatement(query);
res=PStat.executeQuery();
model=(DefaultTableModel)CategoryTable.getModel();
model.setRowCount(0);
CategoryTable.setRowHeight(30);
while(res.next()){
String CatID=res.getString("Category_ID");
String CatName=res.getString("Category_Name");
Object\[\] row= {CatID,CatName};
model.addRow(row);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
PStat.close();
res.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 934, 601);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(panel, GroupLayout.PREFERRED_SIZE, 917, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(panel, GroupLayout.PREFERRED_SIZE, 562, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panel.setLayout(null);
Search = new JTextField();
Search.getDocument().addDocumentListener(new DocumentListener(){
public void changedUpdate(DocumentEvent e){
changed();
}
public void removeUpdate(DocumentEvent e){
changed();
}
public void insertUpdate(DocumentEvent e){
changed();
}
});
Search.setBounds(90, 11, 402, 31);
panel.add(Search);
Search.setColumns(10);
scrollPane = new JScrollPane();
scrollPane.setBounds(90, 41, 402, 127);
CategoryTable = new JTable();
CategoryTable.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
int row=CategoryTable.getSelectedRow();
String TableClicked=(CategoryTable.getModel().getValueAt(row, 0)).toString();
try{
query="Select * from CategoryEntry where Category_ID='"+TableClicked+"'";
PStat=con.prepareStatement(query);
res=PStat.executeQuery();
if(res.next()){
String CatID=res.getString("Category_ID");
CategoryID.setText(CatID);
String CatName=res.getString("Category_Name");
CategoryName.setText(CatName);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
PStat.close();
res.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
});
CategoryTable.setModel(new DefaultTableModel(
new Object\[\]\[\] {
},
new String\[\] {
"CategoryID", "CategoryName"
}
));
JLabel lblNewLabel = new JLabel("Search");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 13));
lblNewLabel.setBounds(21, 19, 46, 14);
panel.add(lblNewLabel);
panel_1 = new JPanel();
panel_1.setBounds(31, 53, 317, 76);
panel_1.setOpaque(false);
panel.add(panel_1);
panel_1.setLayout(null);
label_1 = new JLabel("Category ID");
label_1.setBounds(10, 14, 97, 18);
panel_1.add(label_1);
label_1.setFont(new Font("Tahoma", Font.BOLD, 11));
CategoryID = new JTextField();
CategoryID.setBounds(117, 11, 157, 25);
CategoryID.setBackground(new Color(255,255,255,128));
CategoryID.setOpaque(false);
panel_1.add(CategoryID);
CategoryID.setEditable(false);
CategoryID.setColumns(10);
label = new JLabel("Category Name");
label.setBounds(10, 42, 97, 18);
panel_1.add(label);
label.setFont(new Font("Tahoma", Font.BOLD, 11));
CategoryName = new JTextField();
CategoryName.setBounds(117, 39, 157, 25);
panel_1.add(CategoryName);
CategoryName.setEditable(false);
CategoryName.setColumns(10);
frame.getContentPane().setLayout(groupLayout);
}
}
Screenshot
I have solved it. Actually I made scrollpane transparency to true and also make it viewport to transparency to true like this.
scrollPane.setOpaque (true);
scrollPane.getViewPort ().setOpaque (true);
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());
I'm writing a program where there is a JTable to be created (Which I'm able to). But I want to add a scroll bar to it. Below is my code.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class TagReplaceUI extends JFrame {
private JPanel contentPane;
private JTextField srcTextField;
private Executor executor = Executors.newCachedThreadPool();
static DefaultTableModel model = new DefaultTableModel();
static JTable table = new JTable(model);
/**
* Launch the application.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
final TagReplaceUI frame = new TagReplaceUI();
frame.add(new JScrollPane(table));
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
// FileDownloadTest downloadTest = new
// FileDownloadTest(srcTextField.getText(), textArea);
public TagReplaceUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 552, 358);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
srcTextField = new JTextField();
srcTextField.setBounds(10, 26, 399, 20);
contentPane.add(srcTextField);
srcTextField.setColumns(10);
JButton srcBtn = new JButton("Source Excel");
srcBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fChoose = new JFileChooser();
fChoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fChoose.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
srcTextField.setText(fChoose.getSelectedFile().getAbsolutePath());
} else {
System.out.println("No Selection");
}
}
});
table.setBounds(10, 131, 516, 178);
contentPane.add(table);
model.addColumn("Col1");
model.addColumn("Col2");
srcBtn.setBounds(419, 25, 107, 23);
contentPane.add(srcBtn);
JButton dNcButton = new JButton("Process");
dNcButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
executor.execute(new Test(srcTextField.getText(), model));
}
});
dNcButton.setBounds(212, 70, 89, 23);
contentPane.add(dNcButton);
}
}
When I run the above program, the table frame is also not displayed. But when I remove frame.add(new JScrollPane(table));, it is displaying the table in the JTable area, but there is no scrollbar in it.
Please let me know how can I get a scrollbar in the table and display the data correctly.
Thanks
At first don't use null layout, please read here.
frame.add(new JScrollPane(table)); this scroll pane is not displaying because in null layout each component needs to have bounds. Try below code. I just changed static variables to instance variables. And added scrollpane in to the constructor.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class TagReplaceUI extends JFrame {
private JPanel contentPane;
private JTextField srcTextField;
private Executor executor = Executors.newCachedThreadPool();
private DefaultTableModel model = new DefaultTableModel();
private JTable table = new JTable(model);
/**
* Launch the application.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
final TagReplaceUI frame = new TagReplaceUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
// FileDownloadTest downloadTest = new
// FileDownloadTest(srcTextField.getText(), textArea);
public TagReplaceUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 552, 358);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
srcTextField = new JTextField();
srcTextField.setBounds(10, 26, 399, 20);
contentPane.add(srcTextField);
srcTextField.setColumns(10);
JButton srcBtn = new JButton("Source Excel");
srcBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fChoose = new JFileChooser();
fChoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fChoose.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
srcTextField.setText(fChoose.getSelectedFile().getAbsolutePath());
} else {
System.out.println("No Selection");
}
}
});
JScrollPane scroll = new JScrollPane(table);
scroll.setBounds(10, 131, 516, 178);
contentPane.add(scroll);
model.addColumn("Col1");
model.addColumn("Col2");
srcBtn.setBounds(419, 25, 107, 23);
contentPane.add(srcBtn);
JButton dNcButton = new JButton("Process");
dNcButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
executor.execute(new Test(srcTextField.getText(), model));
}
});
dNcButton.setBounds(212, 70, 89, 23);
contentPane.add(dNcButton);
}
}
I was trying to implement an easy interface to make as much queries as I need within my DB
However I couldn't figure out how to do it. The interface has a button and each time I click it I wish to have the query executed on my DB and a result back to my JTextArea
Below the working code
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import org.neo4j.cypher.javacompat.ExecutionEngine;
import org.neo4j.cypher.javacompat.ExecutionResult;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.helpers.collection.IteratorUtil;
import static org.neo4j.kernel.impl.util.FileUtils.deleteRecursively;
public class Frame extends JFrame {
public static final String DB_PATH = "/Volumes/iTanioHD/Users/tanio/Desktop/ciao";
GraphDatabaseService BORO_DB;
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame frame = new Frame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Frame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 794, 653);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
final JTextArea queryTextArea = new JTextArea();
queryTextArea.setBounds(25, 40, 702, 279);
queryTextArea.setBorder(new EmptyBorder(5, 5, 5, 5));
queryTextArea.setText("start n=node(*) where n.name! = 'my node' return n, n.name");
contentPane.add(queryTextArea);
JLabel cypherQueryLabel = new JLabel("Cypher Query");
cypherQueryLabel.setBounds(25, 12, 105, 23);
contentPane.add(cypherQueryLabel);
final JTextArea resultTextArea = new JTextArea();
resultTextArea.setBounds(25, 351, 702, 171);
resultTextArea.setEditable(false);
resultTextArea.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.add(resultTextArea);
JLabel resultLabel = new JLabel("Result:");
resultLabel.setBounds(25, 323, 55, 23);
contentPane.add(resultLabel);
JButton btnNewButton_2 = new JButton("Execute Query");
btnNewButton_2.setBounds(274, 540, 176, 41);
btnNewButton_2.setVisible(true);
contentPane.add(btnNewButton_2);
final GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
Neo4jEngine neo4jDB = new Neo4jEngine();
neo4jDB.createBOROGraphOntology(db);
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String resultString;
ExecutionEngine engine = new ExecutionEngine( db );
ExecutionResult result = engine.execute(queryTextArea.getText());
resultString =result.dumpToString();
resultTextArea.setText(resultString);
}
});
}
}
Try this:
import org.neo4j.cypher.javacompat.ExecutionEngine;
import org.neo4j.cypher.javacompat.ExecutionResult;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.kernel.impl.util.FileUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
public class Frame extends JFrame {
public static final String DB_PATH = "/Volumes/iTanioHD/Users/tanio/Desktop/ciao";
private static GraphDatabaseService db;
private JPanel contentPane;
public static void main(String[] args) {
db = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
registerShutdownHook(db);
Transaction tx = db.beginTx();
try {
db.getNodeById(0).setProperty("name", "Name 0");
db.createNode().setProperty("name", "Name 1");
db.createNode().setProperty("name", "Name 2");
tx.success();
} finally {
tx.finish();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame frame = new Frame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private static void registerShutdownHook(final GraphDatabaseService graphDb) {
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
graphDb.shutdown();
try {
FileUtils.deleteRecursively(new File(DB_PATH));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public Frame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 794, 653);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
final JTextArea queryTextArea = new JTextArea();
queryTextArea.setBounds(25, 40, 702, 279);
queryTextArea.setBorder(new EmptyBorder(5, 5, 5, 5));
queryTextArea.setText("start n=node(*) return n, n.name");
contentPane.add(queryTextArea);
JLabel cypherQueryLabel = new JLabel("Cypher Query");
cypherQueryLabel.setBounds(25, 12, 105, 23);
contentPane.add(cypherQueryLabel);
final JTextArea resultTextArea = new JTextArea();
resultTextArea.setBounds(25, 351, 702, 171);
resultTextArea.setEditable(false);
resultTextArea.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.add(resultTextArea);
JLabel resultLabel = new JLabel("Result:");
resultLabel.setBounds(25, 323, 55, 23);
contentPane.add(resultLabel);
JButton btnNewButton_2 = new JButton("Execute Query");
btnNewButton_2.setBounds(274, 540, 176, 41);
btnNewButton_2.setVisible(true);
contentPane.add(btnNewButton_2);
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ExecutionEngine engine = new ExecutionEngine(db);
ExecutionResult result = engine.execute(queryTextArea.getText());
resultTextArea.setText(result.dumpToString());
}
});
}
}