How to create scrollable JTable - java

I really don't know what I'm doing wrong. I've tried following other people's code but I can't seem to understand how to add a scrollbar to my JTable
Here's what I have so far:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.JTextArea;
import javax.swing.JTable;
import javax.swing.JTextPane;
import javax.swing.border.BevelBorder;
public class TBB_SQLBuilder {
private JFrame frame;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TBB_SQLBuilder window = new TBB_SQLBuilder();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TBB_SQLBuilder() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 950, 900);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea textArea = new JTextArea();
JButton button = new JButton("New button");
table = new JTable();
table.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(table, GroupLayout.DEFAULT_SIZE, 938, Short.MAX_VALUE)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(textArea, GroupLayout.PREFERRED_SIZE, 289, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(button)))
.addContainerGap())
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(textArea, GroupLayout.PREFERRED_SIZE, 77, GroupLayout.PREFERRED_SIZE)
.addComponent(button))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(table, GroupLayout.PREFERRED_SIZE, 176, GroupLayout.PREFERRED_SIZE)
.addContainerGap(613, Short.MAX_VALUE))
);
frame.getContentPane().setLayout(groupLayout);
frame.add(new JScrollPane(table));
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String getValue = textArea.getText();
String connectDB = "jdbc:ucanaccess:///Users/sebastianzeki/Documents/PhysJava/My.mdb;";
Connection conn;
try {
conn = DriverManager.getConnection(connectDB);
Statement st =conn.createStatement();
ResultSet rsHNum = st.executeQuery(getValue);
table.setModel(buildTableModel(rsHNum));
((DefaultTableModel)table.getModel()).fireTableDataChanged(); // show changes
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
public static DefaultTableModel buildTableModel(ResultSet rs1)
throws SQLException {
ResultSetMetaData metaData = rs1.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs1.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs1.getObject(columnIndex));
System.out.println(rs1.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}

Though you are using a JScrollPane to place your table, you are not really adding the scrollpane to your GroupLayout. Instead, you are adding it to the JFrame - which is your first mistake.
So you should first create scrollpane, and then add table in to it; then add the scrollpane to GroupLayout as below
JScrollPane scrollPane = new JScrollPane(table);
// Force the scrollbars to always be displayed
scrollPane.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 938, Short.MAX_VALUE)
So where ever you did addComponent(table you should addComponent(scrollPane instead. Now, let us look at two lines. Just after scrollpane creation.
scrollPane.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
These will give you the fancy appearance you are looking for. Scrollbars (disabled) even when there is nothing to scroll.

Just create JScrollPane and add you table to it with values...see example below.
public class MainView extends JFrame{
private JPanel mainPanel;
private JTable table;
private DefaultTableModel model_table;
private JScrollPane scroll_table;
public static void main(String[] args) {
MainView main = new MainView();
main.setVisible(true);
}
public MainView() {
mainPanel = new JPanel(null);
setSize(500, 500);
table = new JTable();
model_table = new DefaultTableModel();
model_table.addColumn("1");
model_table.addColumn("2");
model_table.addColumn("3");
model_table.addColumn("4");
table.setModel(model_table);
for(int i=0;i<10;i++){ // add value to table
Vector<String> r = new Vector<String>();
r.addElement("a");
r.addElement("b");
r.addElement("c");
r.addElement("d");
model_table.addRow(r);
}
scroll_table = new JScrollPane(table); // add table to scroll panel
scroll_table.setBounds(5, 10, 300, 150);
scroll_table.setVisible(true);
mainPanel.add(scroll_table);
this.add(mainPanel);
}
}

Related

set JTextField Size according to text in JTextArea

In my program i have to make JTextField Dynamically when JButton pressed. And i have to set JTextField size according to text inside in JTextArea.
The process is whenever i typed any message in JTextArea and pressed JButton it show that message inside JTextField. And JTextField size is according to the text that i want to display in JTextArea.
this is my code
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.GroupLayout.Alignment;
import com.alee.laf.WebLookAndFeel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
public class ThirdApplication {
private JFrame frame;
private JPanel panel_2;
private JTextArea SendText;
private int y=20;
private JTextField DisplayText;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WebLookAndFeel.install();
ThirdApplication window = new ThirdApplication();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ThirdApplication() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 614, 649);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(panel, GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE)
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(panel, GroupLayout.DEFAULT_SIZE, 621, Short.MAX_VALUE)
);
panel.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBounds(0, 534, 608, 87);
panel.add(panel_1);
panel_1.setLayout(null);
JButton btnNewButton = new JButton("Send");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel_2.revalidate();
panel_2.repaint();
DisplayText = new JTextField();
DisplayText.setFont(new Font("Georgia", Font.PLAIN, 15));
DisplayText.setEditable(false);
DisplayText.setBounds(10,y,0,0);
DisplayText.setText(SendText.getText());
panel_2.add(DisplayText,"width 179, height 40,wrap");
DisplayText.setColumns(10);
y=y+38;
}
});
btnNewButton.setFont(new Font("Georgia", Font.BOLD, 15));
btnNewButton.setBounds(509, 23, 89, 40);
panel_1.add(btnNewButton);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 11, 486, 65);
panel_1.add(scrollPane);
SendText = new JTextArea();
SendText.setFont(new Font("Georgia", Font.PLAIN, 15));
scrollPane.setViewportView(SendText);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(0, 0, 608, 534);
panel.add(scrollPane_1);
panel_2 = new JPanel();
scrollPane_1.setViewportView(panel_2);
panel_2.setLayout(new MigLayout("wrap"));
frame.getContentPane().setLayout(groupLayout);
}
}

how can i transparent my JTextField and JLabel

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);

Reading and storing excel sheet values using POI (XSSF) - JAVA

Hello I am fairly new to Java programming and was wanting to get some input on my code. I know it is really messy and I have not had a chance to clean it up just yet.
I was able to get the JFilechooser to work and as far as I can tell I am setting my filepath correctly for XSSFWorkbook. But upon trying to open the sheet and read its contents my program is throwing exceptions.
All I need my program to do is read an excel file and take the 2 columns + X rows and store it into a 2d int array.
My Code (the part I am having trouble with is in the run() portion.)
PS (sorry again the code is messy and this probably isn't the best way to do what I want to do, JAVA newbie here)
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import javax.swing.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.util.Arrays;
import java.util.Iterator;
public class ExtensionsTool extends JFrame implements ActionListener, Runnable {
final JFileChooser fc = new JFileChooser();
Thread go;
private JMenuBar menuBar1;
private JMenu FileMenu;
private JMenuItem OpenMenu;
private JMenuItem ExitMenu;
private JMenu HelpMenu;
private JMenuItem AboutMenu;
private JScrollPane scrollPane1;
private JTextArea Extensions;
private JButton OpenButton;
private JButton ClearButton;
private JButton ExtCopy;
private JButton SQLCopy;
private JScrollPane scrollPane2;
private JTextArea Queries;
private JLabel label1;
private JLabel label2;
private JButton RunButton;
private int rows;
private int columns;
private int[][] array;
String filepath;
File f;
public ExtensionsTool() {
RunButton = new JButton();
menuBar1 = new JMenuBar();
FileMenu = new JMenu();
OpenMenu = new JMenuItem();
ExitMenu = new JMenuItem();
HelpMenu = new JMenu();
AboutMenu = new JMenuItem();
scrollPane1 = new JScrollPane();
Extensions = new JTextArea();
OpenButton = new JButton();
ClearButton = new JButton();
ExtCopy = new JButton();
SQLCopy = new JButton();
scrollPane2 = new JScrollPane();
Queries = new JTextArea();
label1 = new JLabel();
label2 = new JLabel();
setTitle("Extension Tool");
Container contentPane = getContentPane();
setResizable(false);
RunButton.addActionListener(this);
OpenButton.addActionListener(this);
ClearButton.addActionListener(this);
ExtCopy.addActionListener(this);
SQLCopy.addActionListener(this);
OpenMenu.addActionListener(this);
ExitMenu.addActionListener(this);
AboutMenu.addActionListener(this);
//======== menuBar1 ========
{
//======== FileMenu ========
{
FileMenu.setText("File");
//---- OpenMenu ----
OpenMenu.setText("Open");
FileMenu.add(OpenMenu);
//---- ExitMenu ----
ExitMenu.setText("Exit");
FileMenu.add(ExitMenu);
}
menuBar1.add(FileMenu);
//======== HelpMenu ========
{
HelpMenu.setText("Help");
//---- AboutMenu ----
AboutMenu.setText("About");
HelpMenu.add(AboutMenu);
}
menuBar1.add(HelpMenu);
}
setJMenuBar(menuBar1);
//======== scrollPane1 ========
{
scrollPane1.setViewportView(Extensions);
}
//---- OpenButton ----
OpenButton.setText("Open File");
//---- ClearButton ----
ClearButton.setText("Clear");
//---- ExtCopy ----
ExtCopy.setText("Copy Extensions");
//---- SQLCopy ----
SQLCopy.setText("Copy SQL Query");
//======== scrollPane2 ========
{
scrollPane2.setViewportView(Queries);
}
//---- label1 ----
label1.setText("Extensions:");
//---- label2 ----
label2.setText("SQL Queries");
//---- RunButton ----
RunButton.setText("Run");
GroupLayout contentPaneLayout = new GroupLayout(contentPane);
contentPane.setLayout(contentPaneLayout);
contentPaneLayout.setHorizontalGroup(
contentPaneLayout.createParallelGroup()
.addGroup(GroupLayout.Alignment.TRAILING, contentPaneLayout.createSequentialGroup()
.addContainerGap(156, Short.MAX_VALUE)
.addGroup(contentPaneLayout.createParallelGroup()
.addComponent(label2)
.addComponent(scrollPane2, GroupLayout.PREFERRED_SIZE, 599, GroupLayout.PREFERRED_SIZE))
.addGap(28, 28, 28))
.addGroup(contentPaneLayout.createSequentialGroup()
.addContainerGap()
.addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
.addComponent(SQLCopy, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(ExtCopy, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(ClearButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(OpenButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(RunButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(33, 33, 33)
.addGroup(contentPaneLayout.createParallelGroup()
.addComponent(label1)
.addComponent(scrollPane1, GroupLayout.PREFERRED_SIZE, 599, GroupLayout.PREFERRED_SIZE))
.addContainerGap(28, Short.MAX_VALUE))
);
contentPaneLayout.setVerticalGroup(
contentPaneLayout.createParallelGroup()
.addGroup(contentPaneLayout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(label1)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(contentPaneLayout.createParallelGroup()
.addGroup(contentPaneLayout.createSequentialGroup()
.addComponent(OpenButton)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ClearButton)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ExtCopy)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(SQLCopy)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(RunButton))
.addComponent(scrollPane1, GroupLayout.PREFERRED_SIZE, 214, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(label2)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(scrollPane2, GroupLayout.PREFERRED_SIZE, 214, GroupLayout.PREFERRED_SIZE)
.addContainerGap(12, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(getOwner());
setVisible(true);
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
if(source == RunButton){
if(go == null){
go = new Thread(this);
go.start();
}
} else if (source == ExitMenu){
System.exit(0);
} else if (source == OpenMenu){
JFileChooser fc=new JFileChooser();
int i=fc.showOpenDialog(this);
if(i==JFileChooser.APPROVE_OPTION){
File f=fc.getSelectedFile();
filepath=f.getPath();
try{
}catch (Exception ex) {ex.printStackTrace(); }
}
}else if (source == OpenButton){
JFileChooser fc=new JFileChooser();
int i=fc.showOpenDialog(this);
if(i==JFileChooser.APPROVE_OPTION){
File f=fc.getSelectedFile();
filepath=f.getPath();
try{
}catch (Exception ex) {ex.printStackTrace(); }
}
}
}
public static void main(String[] arguments){
ExtensionsTool frame = new ExtensionsTool();
}
public void run() {
Queries.setText(filepath);
try {
FileInputStream input_document = new FileInputStream(new File(filepath));
XSSFWorkbook my_xlsx_workbook = new XSSFWorkbook(input_document);
XSSFSheet sheet = my_xlsx_workbook.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 2; // No of columns
array = new int[cols][rows];
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++)
{
array[j][i] = (int) cell.getNumericCellValue();
}
}
my_xlsx_workbook.close();
} catch(Exception ioe) {
ioe.printStackTrace();
}
Extensions.setText(Arrays.toString(array));
}
}
The error I am getting when I hit Run and the thread is started is as follows
Exception in thread "Thread-3" java.lang.NoClassDefFoundError:
org/apache/commons/collections4/ListValuedMap
at ExtensionsTool.run(ExtensionsTool.java:261)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException:
org.apache.commons.collections4.ListValuedMap
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 2 more
It looks like the commons-collections4-x.x.jar file (available here) is missing from your build path.
Add it and it should work!

Java Resizable JLabel icon just keeps getting bigger

(EDIT 2) Hey guys i dont have a lot of time so i'll post this quick, i got the problem to happen in a smaller program:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JScrollPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextField;
import javax.swing.JList;
import javax.swing.JToolBar;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import java.awt.Color;
import javax.swing.border.LineBorder;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
public class Main extends JFrame {
private JPanel contentPane;
private JTextField txtWhatTheHell;
private static ArrayList<ImageIcon> thumbslist = new ArrayList<ImageIcon>();
public static DefaultListModel model = new DefaultListModel();
private static void initialize_pix() throws IOException
{
File filefolder = new File("pix");
File[] pictures = filefolder.listFiles();
for(File a: pictures)
{
Image tempimage = ImageIO.read(a);
ImageIcon perimage = new ImageIcon(tempimage);
thumbslist.add(perimage);
}
model.addElement(filefolder.toString());
}
public static ImageIcon resize(ImageIcon source, JLabel label)
{
int height = label.getHeight();
int width = label.getWidth();
Image original = source.getImage();
BufferedImage resized = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = resized.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics.drawImage(original, 0, 0, width, height, null);
graphics.dispose();
ImageIcon result = new ImageIcon(resized);
return result;
}
public static void main(String[] args) {
try {
initialize_pix();
} catch (IOException e1) {
e1.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 731, 563);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JScrollPane scrollPane = new JScrollPane();
txtWhatTheHell = new JTextField();
txtWhatTheHell.setText("Text");
txtWhatTheHell.setEditable(false);
txtWhatTheHell.setColumns(10);
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
JLabel label = new JLabel("");
label.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent a) {
label.setIcon(resize(thumbslist.get(0), label));
}
});
label.setBorder(new LineBorder(new Color(0, 0, 0)));
label.setBackground(Color.GRAY);
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addContainerGap()
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(toolBar, GroupLayout.DEFAULT_SIZE, 685, Short.MAX_VALUE)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 491, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(label, GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)
.addComponent(txtWhatTheHell, GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE))))
.addContainerGap())
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(toolBar, GroupLayout.PREFERRED_SIZE, 85, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(txtWhatTheHell, GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(label, GroupLayout.PREFERRED_SIZE, 239, GroupLayout.PREFERRED_SIZE))
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE))
.addContainerGap())
);
JList list = new JList(model);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent a) {
if(list.isSelectionEmpty() == true)
{
return;
}
else
{
label.setIcon(thumbslist.get(0));
}
}
});
scrollPane.setViewportView(list);
contentPane.setLayout(gl_contentPane);
}
}
The file at the beginning is a file of pictures
I'm really not sure what's wrong with it
(EDIT 3) I did a a delay after each instance the resize listener is invoked, and the very first time, it is resized correctly, then it seems after that it starts to grow out of control
i think that #HovercraftFullOfEels thought this, but i just do not know exactly what to do in order to make it resize only once every time the frame is resized
You've got recursion of a sorts going on inside your component listener. Since you increase the size of the JLabel's icon within its own ComponentListener, the listener is notified of the change in size, which increase's the icon's size, which notifies the listener of the change in size....
A possible solution: consider turning off the listener within itself so that this recursion doesn't happen, and then turning it back on again. One way to do this is to simply remove and then re-add the listener within itself.
e.g.,
Label thumbchanger = new JLabel();
thumbchanger.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent a) {
// remove the *this* component listener before resizing
thumbchanger.removeComponentListener(this);
Mod current_mod = Globals.modList.get(list.getSelectedIndex());
ImageIcon new_icon = Globals.resize(current_mod.get_current(), thumbchanger);
thumbchanger.setIcon(new_icon);
// re-add the component listener after done resizing
thumbchanger.addComponentListener(this);
}
});
Another way is to use a boolean field local to the listener that you set within it.
thumbchanger.addComponentListener(new ComponentAdapter() {
private boolean resizing = false;
#Override
public void componentResized(ComponentEvent a) {
if (resizing) {
return;
}
resizing = true;
Mod current_mod = Globals.modList.get(list.getSelectedIndex());
ImageIcon new_icon = Globals.resize(current_mod.get_current(), thumbchanger);
thumbchanger.setIcon(new_icon);
resizing = false;
}
});

java JFrame setContentPanel and then JPanel disappear

I have a code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
class ReadPanel extends JPanel{
private static final long serialVersionUID = 1L;
private JTextArea textArea;
public ReadPanel(){
super();
setBackground(new Color(255, 182, 193));
JScrollPane scrollPane = new JScrollPane();
GroupLayout gl_panel_main = new GroupLayout(this);
gl_panel_main.setHorizontalGroup(
gl_panel_main.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_main.createSequentialGroup()
.addContainerGap()
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 402, Short.MAX_VALUE)
.addContainerGap())
);
gl_panel_main.setVerticalGroup(
gl_panel_main.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_main.createSequentialGroup()
.addContainerGap()
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
.addContainerGap())
);
textArea = new JTextArea();
scrollPane.setViewportView(textArea);
setLayout(gl_panel_main);
}
public void setNews(String news){
textArea.setText(news);
}
public String getNews(){
return textArea.getText();
}
//another complex method here...
}
public class SetContentPanelFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private ReadPanel panel_main;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SetContentPanelFrame frame = new SetContentPanelFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void goFullReadMode(){
/*ReadPanel copy = new ReadPanel();
copy.setNews(panel_main.getNews());
copy.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
exitFullReadMode();
}
});
//Set another property here...
this.setContentPane(copy);*/
this.setContentPane(panel_main);
this.repaint();
this.revalidate();
}
public void exitFullReadMode(){
this.setContentPane(contentPane);
//contentPane.add(panel_main);
this.repaint();
this.revalidate();
}
/**
* Create the frame.
*/
public SetContentPanelFrame() {
setTitle("Set Content Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 741, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JPanel panel_menu = new JPanel();
panel_menu.setBackground(new Color(240, 248, 255));
JPanel panel_ads = new JPanel();
panel_ads.setBackground(new Color(255, 239, 213));
panel_main = new ReadPanel();
panel_main.setNews("This is a news\r\n1\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
+ "This is a news\r\n2\r\n\r\n\r\n\r\n"
+ "This is a news\r\n3\r\n\r\n\r\n"
+ "This is a news\r\n4");
panel_main.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
exitFullReadMode();
}
});
JButton btnViewFull = new JButton("View full");
btnViewFull.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
goFullReadMode();
}
});
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(panel_menu, GroupLayout.PREFERRED_SIZE, 140, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(btnViewFull)
.addContainerGap())
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(panel_main, GroupLayout.DEFAULT_SIZE, 422, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(panel_ads, GroupLayout.PREFERRED_SIZE, 141, GroupLayout.PREFERRED_SIZE))))
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(btnViewFull)
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(panel_main, GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE)
.addComponent(panel_ads, GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE)
.addComponent(panel_menu, GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE)))
);
panel_ads.setLayout(new BorderLayout(0, 0));
JLabel lblAds = new JLabel("Ads...");
lblAds.setHorizontalAlignment(SwingConstants.CENTER);
panel_ads.add(lblAds, BorderLayout.CENTER);
panel_menu.setLayout(new BorderLayout(0, 0));
JLabel lblMenu = new JLabel("Menu");
lblMenu.setHorizontalAlignment(SwingConstants.CENTER);
panel_menu.add(lblMenu, BorderLayout.CENTER);
contentPane.setLayout(gl_contentPane);
}
}
I want to switch between two JPanel (contentPane and panel_main) using setContentPane method.
There are 2 important method: goFullReadMode() and exitFullReadMode().
When I run this program, the goFullReadMode() do correctly, but when switch back to default panel (click the pink area outside the text), the middle panel (panel_main) is disappear. Why it doesn't display again?
I think that it has been moved to somewhere, so in exitFullReadMode method, I try:
contentPane.add(panel_main);
But it doesn't display in correct position because the container has a GroupLayout, and regoup all component is not a good idea.
An afternate solution is make a copy of panel_main and setContentPane to this copy, but we need to copy all content(data, sub-component, ...) to this copy object (like the comment in goFullReadMode method). So it is not easy way to do.
Is there any solution that does not need make a copy of the panel and still keep it when we switch back to default view?
Thanks.
Since you are using only one reference to the panel_main by the time you call this.setContentPane(panel_main2); it will then remove it self from the contentPane panel and add itself to the Frame as its main Panel thus you can not see it in your contentPane panel upon exiting the fullscreen.
solution:
since you cant resize it back to its state, you can create 2 instance of ReadPanel one for the contentPane and one for the fullscreen
panel_main = new ReadPanel();
panel_main2 = new ReadPanel();
panel_main.setNews("This is a news\r\n1\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
+ "This is a news\r\n2\r\n\r\n\r\n\r\n"
+ "This is a news\r\n3\r\n\r\n\r\n"
+ "This is a news\r\n4");
panel_main2.setNews("This is a news\r\n1\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
+ "This is a news\r\n2\r\n\r\n\r\n\r\n"
+ "This is a news\r\n3\r\n\r\n\r\n"
+ "This is a news\r\n4");
panel_main2.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
exitFullReadMode();
}
For going fullScreen
public void goFullReadMode(){
this.setContentPane(panel_main2);
this.repaint();
this.revalidate();
}
Now when you update the text of the panel_main you must update the panel_main2 as well.

Categories