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());
}
});
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
While working on a GUI project i am stuck with an error called null pointer error.
I am unable to resolve this problem.
The line which shows the error is closed by double asterisk on both sides(**).(line 80)
I have connected this with a SQL database and error erupts while assigning Jtable its value and structure.
package connectsqlite;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTable;
import java.sql.*;
import javax.swing.*;
import net.proteanit.sql.DbUtils;
public class afterLogin extends JFrame {
public JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
afterLogin frame = new afterLogin();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
Connection connect = null;
public afterLogin() {
connect = sqliteConnection.conn();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 695, 422);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnBack = new JButton("Log out");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Connecting window = new Connecting();
window.frame.setVisible(true);
}
});
btnBack.setBounds(10, 62, 114, 23);
contentPane.add(btnBack);
JButton btnNewButton = new JButton("Load Details");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
String query = "SELECT * FROM Appointments";
PreparedStatement pst = connect.prepareStatement(query);
ResultSet rs = pst.executeQuery();
**table.setModel(DbUtils.resultSetToTableModel(rs));**
}
catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(10, 28, 114, 23);
contentPane.add(btnNewButton);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(162, 57, 435, 305);
contentPane.add(scrollPane);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane.setViewportView(scrollPane_1);
}
}
You haven't instantiated your table, it's only declared. Therefore, when you call setModel on it it's going to cause a NullPointerException.
Please be gentle, this is my first time working with Swing and GUI's.
My problem/question:
I have written some code using Java Swing GUI. The validation portion of my code will only recognize if the textField is incorrectly filled out and ignores if the comboBoxes are left empty. Can anyone tell me what I am doing wrong here? My goal is to make sure that all fields are filled out when the user hits submit. Here is my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.layout.FormSpecs;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class FeliciasStore_GUI extends JFrame {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FeliciasStore_GUI frame = new FeliciasStore_GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public FeliciasStore_GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 558, 364);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Size:");
lblNewLabel.setBounds(67, 39, 23, 14);
contentPane.add(lblNewLabel);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setBounds(96, 36, 161, 20);
contentPane.add(comboBox);
comboBox.addItem("Small");
comboBox.addItem("Medium");
comboBox.addItem("Large");
comboBox.addItem("XLarge");
comboBox.setSelectedItem(null);
JLabel lblColor = new JLabel("Color:");
lblColor.setBounds(61, 90, 29, 14);
contentPane.add(lblColor);
JComboBox<String> comboBox_1 = new JComboBox<String>();
comboBox_1.setBounds(96, 87, 161, 20);
contentPane.add(comboBox_1);
comboBox_1.addItem("Blue");
comboBox_1.addItem("Red");
comboBox_1.addItem("Silver");
comboBox_1.addItem("Gold");
comboBox_1.addItem("Aqua");
comboBox_1.addItem("Green");
comboBox_1.addItem("Pink");
comboBox_1.addItem("Purple");
comboBox_1.addItem("White");
comboBox_1.addItem("Black");
comboBox_1.addItem("Orange");
comboBox_1.addItem("Maroon");
comboBox_1.setSelectedItem(null);
JLabel label = new JLabel("");
label.setBounds(518, 122, 19, 0);
contentPane.add(label);
JLabel lblStyle = new JLabel("Style:");
lblStyle.setBounds(62, 141, 28, 14);
contentPane.add(lblStyle);
JComboBox<String> comboBox_2 = new JComboBox<String>();
comboBox_2.setBounds(96, 138, 161, 20);
contentPane.add(comboBox_2);
comboBox_2.addItem("Queen");
comboBox_2.addItem("King");
comboBox_2.addItem("Pawn");
comboBox_2.addItem("Knight");
comboBox_2.addItem("Joker");
comboBox_2.addItem("Babydoll");
comboBox_2.addItem("Superstar");
comboBox_2.setSelectedItem(null);
JLabel lblInscription = new JLabel("Inscription:");
lblInscription.setBounds(36, 192, 54, 14);
contentPane.add(lblInscription);
textField = new JTextField();
textField.setBounds(96, 189, 161, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton btnSubmit_1 = new JButton("SUBMIT");
btnSubmit_1.setBounds(96, 240, 161, 23);
btnSubmit_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textField.getText().length()>15 || comboBox == null || comboBox_1 == null || comboBox_2 == null) {
JOptionPane.showMessageDialog(null, "Insufficient input.", "Input Error", JOptionPane.ERROR_MESSAGE);
return;
}
String enscription = textField.getText();
}
});
contentPane.add(btnSubmit_1);
}
}
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);
}
}
I've got a problem with this, I've got text from comboBox saved into text variable but now I can't make it to be saved to the file like 'num1' and 'num2' after I click a buttom. I know I am missing something simple - or everything is wrong anyways please help! Thank!
package windowbuilded.views;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.awt.event.ActionEvent;
import javax.swing.JList;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
public class WiewWindow {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WiewWindow window = new WiewWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public WiewWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int num1, num2, ans2, combo;
num1=Integer.parseInt(textField.getText());
num2=Integer.parseInt(textField_1.getText());
ans2 = num1 + num2;
textField_2.setText(Integer.toString(ans2));
try{
File dir = new File("C:\\test");
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
FileWriter writer = new FileWriter(child, true);
PrintWriter out = new PrintWriter(writer);
out.println(num1);
out.println(num2);
out.close();
}
}
} catch (IOException e) {
// do something
}
}
});
btnNewButton.setBounds(124, 206, 89, 23);
frame.getContentPane().add(btnNewButton);
textField = new JTextField();
textField.setBounds(10, 34, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(124, 34, 86, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(124, 101, 86, 20);
frame.getContentPane().add(textField_2);
textField_2.setColumns(10);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"Yes", "No", "Blah!"}));
String text = (String)comboBox.getSelectedItem();
System.out.println(text);
comboBox.setBounds(265, 101, 121, 20);
frame.getContentPane().add(comboBox);
}
}
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);
}
}