Accessing Jpanel from another method in java swing - java

I am new to java. And Most of my questions here are going unanswered, I don't know what is wrong with my question. I hope this question gets some answer.
So, Now I am creating a frame, this frame contains tabbedPane and tabbedPane contains two JPanels. All this is done in one function createAndShowGUI()
And there is another function which is creating buttons with for loop, and I want to add this new buttons to my JPanel panel. Here is my code. I want to add buttons creating in createButton() method to panel created in createAndShowGUI() method
public class Try extends JFrame {
static Connection conn;
//JPanel panel;
static JButton buttons;
static int totalRows;
static int recordPerPage = 1000000;
static int totalPages = 0;
private static JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
createAndShowGUI();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
protected static void createAndShowGUI() throws SQLException {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setBounds(30, 50, 1300, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
frame.setContentPane(contentPane);
UIManager.put("TabbedPane.selected", Color.lightGray);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setBorder(new EmptyBorder(10, 10, 10, 10));
frame.add(tabbedPane);
JPanel panel = new JPanel();
tabbedPane.addTab("TABLE", null, panel, null);
tabbedPane.setFont( new Font( "Dialog", Font.BOLD|Font.ITALIC, 16 ) );
panel.setBackground(Color.white);
JPanel panel_1 = new JPanel();
tabbedPane.addTab("GRAPH", null, panel_1, null);
panel_1.setBackground(Color.white);
JTable table = new JTable();
panel.add(table);
table.setFillsViewportHeight(true);
createDBConnection();
}
private static void createDBConnection() throws SQLException {
try {
Class.forName("org.h2.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection("jdbc:h2:file:G:/hs_temp/h2_db/test", "sa", "sa");
} catch (SQLException e) {
e.printStackTrace();
}
createPaginationButtons(conn);
}
private static void createPaginationButtons(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT count(*) FROM cdr");
while (rs.next()) {
JOptionPane.showMessageDialog(null, rs.getInt(1));
totalRows = rs.getInt(1);
}
int v = totalRows % recordPerPage == 0 ? 0 : 1;
totalPages = totalRows / recordPerPage + v;
createButton(totalPages);
}
private static void createButton(int totalPages) {
JOptionPane.showMessageDialog(null, totalPages);
for(int i = 0; i < totalPages;) {
buttons = new JButton(""+(i+1) );
//JOptionPane.showMessageDialog(null, buttons);
panel.add(buttons);
i++;
}
}
}
Any idea, how to do this ?

Related

How can I retrieve values from a DB and load them into a JTable?

I'm trying to load values from a database and list them into a jtable. I have the statement executing properly, however when I load the application nothing appears in the table space, nor do I receive any error messages. Is there a statement missing? I haven't worked with jtable before. I've edited the original post to contain all of my code to bring into context
//imports
public class viewMusic extends JFrame {
static Connection conn = null;
static viewMusic frame = new viewMusic();
private JPanel contentPane;
private JTable table;
private JTable table_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
viewMusic frame = new viewMusic();
//frame.setVisible(true);
try { //Login details for the DB.
String userName = "root";
String password = "";
String url = "jdbc:mysql://localhost/music";
conn = DriverManager.getConnection(url, userName, password);
//JOptionPane.showMessageDialog(null, "Connected");
} catch (Exception e) { //Error is DB connection is unsuccessful .
JOptionPane.showMessageDialog(null, "Cannot connect to database server");
// System.err.println(e.getMessage());
System.err.println(e.getStackTrace());
}
} catch (Exception e) {
e.printStackTrace();
}
Statement stmt;
try {
stmt = conn.createStatement();
DefaultTableModel model = new DefaultTableModel(new String[]{"Artist_Name", "Album_Title", "Record_Label", "Genre", "Year", "Format"}, 0);
JTable table = new JTable(model);
String query="SELECT * from cds";
System.out.println(query);
ResultSet rs = stmt.executeQuery(query);
String a = "artist";
String b = "album title";
String c = "record label";
String d = "genre";
String e = "year";
String f = "format";
model.addRow(new Object[]{a, b, c, d, e, f});
table.setModel(model);
JScrollPane scrollpane = new JScrollPane(table);
frame.getContentPane().add(scrollpane);
frame.setSize(600, 500);
frame.setVisible(true);
} catch (Exception e) { //Error is DB connection is unsuccessful .
JOptionPane.showMessageDialog(null, "Cannot connect");
// System.err.println(e.getMessage());
System.err.println(e.getStackTrace());
}
} //End of run()
});
} //End of main
/**
* Create the frame.
*/
public viewMusic() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
table_1 = new JTable();
table_1.setBounds(25, 64, 551, 250);
contentPane.add(table_1);
JLabel lblStatus = new JLabel("Connection Status");
lblStatus.setBounds(399, 18, 149, 13);
contentPane.add(lblStatus);
lblStatus.setText("Connecting to DB..");
}
}
You need to add the JTable to the JFrame
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
public class ViewMusic extends JFrame {
private static final long serialVersionUID = 1L;
// static Connection conn = null;
static ViewMusic frame = new ViewMusic();
private JPanel contentPane;
private static JTable table;
private static DefaultTableModel model;
// private JTable table_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
model = new DefaultTableModel(new Object[] { "Artist_Name",
"Album_Title", "Record_Label", "Genre", "Year", "Format" },
0);
String a = "artist";
String b = "album title";
String c = "record label";
String d = "genre";
String e = "year";
String f = "format";
model.addRow(new Object[] { a, b, c, d, e, f });
table.setModel(model);
frame.repaint();
}
});
} // End of main
/**
* Create the frame.
*/
public ViewMusic() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
table = new JTable();
JScrollPane scrollpane = new JScrollPane(table);
scrollpane.setBounds(25, 64, 551, 250);
contentPane.add(scrollpane);
JLabel lblStatus = new JLabel("Connection Status");
lblStatus.setBounds(399, 18, 149, 13);
contentPane.add(lblStatus);
lblStatus.setText("Connecting to DB..");
setVisible(true);
}
}

Set String on main frame from second frame

Hi guys im trying to set a string value on my main frame with a value generated in an other frame, but i dont quite know how to do it this is my code so far.
This is my mainframe opens the query frame where i input the data
public class InfoCd extends JFrame {
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
InfoCd frame = new InfoCd();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection conn=null;
private JTextField verConsulta;
/**
* Create the frame.
*/
public InfoCd() {
conn=sqliteConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 753, 477);
contentPane = new JPanel();
contentPane.setBackground(SystemColor.activeCaption);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnHacerConsulta = new JButton("Hacer Consulta");
btnHacerConsulta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Query q = new Query();
q.setVisible(true);
String userQuery = Query.getqueryField();//here is the problem im sending the value before filling it in the second frame
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(userQuery);
table.setModel(DbUtils.resultSetToTableModel(rs));
//insert delete update
} catch (Exception e2) {
e2.printStackTrace();
}
}
});
btnHacerConsulta.setBounds(20, 388, 169, 39);
contentPane.add(btnHacerConsulta);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 0, 737, 367);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
verConsulta = new JTextField();
verConsulta.setBounds(260, 388, 359, 29);
contentPane.add(verConsulta);
verConsulta.setColumns(10);
}
}
here is the query field
public class Query extends JFrame {
private JPanel contentPane;
private static JTextField queryField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Query frame = new Query();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Query() {
setBackground(SystemColor.activeCaption);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 641, 146);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnAceptar = new JButton("Aceptar");
btnAceptar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getqueryField();
dispose();
}
});
btnAceptar.setBounds(226, 52, 155, 34);
contentPane.add(btnAceptar);
JLabel lblConsulta = new JLabel("Consulta:");
lblConsulta.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 13));
lblConsulta.setBounds(69, 11, 101, 39);
contentPane.add(lblConsulta);
queryField = new JTextField();
queryField.setBounds(135, 21, 480, 20);
contentPane.add(queryField);
queryField.setColumns(10);
}
public static String getqueryField() {
return queryField.getText();
}
}

Keep getting Resultset closed sql Exception

this is the class where error happens
public class Drinks extends JFrame {
private JPanel contentPane;
private JButton button;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Drinks frame = new Drinks();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Drinks() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 401, 401);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JList list = new JList();
list.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent arg0) {
}
private Component StringtoInt(String string) {
// TODO Auto-generated method stub
return null;
}
});
list.setBorder(new CompoundBorder(new MatteBorder(3, 3, 3, 3, (Color) new Color(0, 0, 0)), null));
list.setFont(new Font("Tahoma", Font.PLAIN, 14));
JLabel lblDrink = new JLabel("Drink");
lblDrink.setFont(new Font("Tahoma", Font.PLAIN, 18));
JLabel lblIngredients = new JLabel("Ingredients");
lblIngredients.setFont(new Font("Tahoma", Font.PLAIN, 18));
button = new JButton("Back");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainMenu frame = new MainMenu();
frame.setVisible(true);
dispose();
}
});
JTextPane textPane = new JTextPane();
textPane.setBorder(new LineBorder(new Color(0, 0, 0), 3));
Here is where i believe the problem to be as you can see there are no
existing close statements
JButton btnLoad = new JButton("Load");
btnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
Connection connDrink = Connections.sqlConn();
int countDrinks = Connections.count();
System.out.println(countDrinks);
for (int j = 0; j < countDrinks; j++) {
String dk = "select DrinkID, Drink from Drinks where DrinkID = " + j + ";";
PreparedStatement pSt = connDrink.prepareStatement(dk);
ResultSet rS = pSt.executeQuery();
System.out.println(rS.getString(2));
int oi = Integer.parseInt(rS.getString(1).toString());
`//`list.add(rS.getString(2).toString(), null);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getClass().getName() + ": " + e.getMessage());
}
}
});
Always gives java.sql.SQLException: Result Set closed and I cant find where the result set is closed or if there is another error
I don't have enough points to comment, so I'll answer here.
you should try
if(rS.first())// move the cursor to the first row, true if there's a row, false otherwise
System.out.println(rS.getString(2));

Add button on top of JTable

How to add a Back button on top of JTable ? I tried but no luck.
public class viewMovie extends JPanel{
static JFrame frame = new JFrame("View Movie");
JTable table;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
try {
createAndShowGui();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
}
static void createAndShowGui() throws Exception {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new viewMovie());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public viewMovie() throws Exception
{
String sql="Select * from movie";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ResultSetMetaData rsmt= rs.getMetaData();
int c= rsmt.getColumnCount();
Vector column= new Vector(c);
for(int i=1;i<=c;i++)
{
column.add(rsmt.getColumnName(i));
}
Vector data = new Vector();
Vector row=new Vector();
while(rs.next())
{
row=new Vector(c);
for(int i=1;i<=c;i++)
{
row.add(rs.getString(i));
}
data.add(row);
}
JButton back= new JButton("Back");
JPanel topPanel = new JPanel(new GridLayout(1, 0, 3, 3));
topPanel.add(back);
JPanel panel= new JPanel();
table=new JTable(data,column);
JScrollPane jsp = new JScrollPane(table);
panel.setLayout(new BorderLayout());
panel.add(jsp,BorderLayout.CENTER);
frame.setContentPane(panel);
frame.setVisible(true);
}
}
This is the output I get.
You're forgetting one line of code, the line that adds the topPanel to the panel JPanel:
panel.add(topPanel, BorderLayout.PAGE_START);
Side note: for future questions, you will want to make your code compilable and runnable by us, meaning get rid of unnecessary dependencies, such as database. For your code above, the database stuff could be replaced by:
JPanel panel = new JPanel();
Integer[][] data = { { 1, 2, 3 }, { 4, 5, 6 } };
String[] column = { "A", "B", "C" };
table = new JTable(data, column);
But actually since it is just a simple layout question, even the JTable is not necessary.

Adding a JTable to JFrame

I want to add test2 to my DFrametest class, so that the table of test2 shows up in my window. I get an empty window and can't find the mistake.
public class test2 extends JPanel {
JTable tbl;
DefaultTableModel dt;
public test2(){
JLabel label = new JLabel("Course Lookup GUI");
this.add( label );
tbl = new JTable();
dt = new DefaultTableModel();
dt.addColumn("ID");
dt.addColumn("Name");
tbl.setModel(dt);
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/lagerverwaltungwin", "root", "");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT ArtNr, Beschreibung FROM artikel");
}catch(Exception e){
e.printStackTrace();
}
JScrollPane jp = new JScrollPane();
jp.getViewport().add(tbl);
add(jp);
}
}
This is my Frameclass which should have the table from test2:
public class DFrametest extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DFrametest frame = new DFrametest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public DFrametest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
test2 t = new test2();
this.add(t);
this.setVisible(true);
}
}
Never Use null Layout. Also donot use setBounds(100, 100, 450, 300);
use pack();
Change your DFrametest class like this
contentPane.setLayout(new BorderLayout());
contentPane.add(t, BorderLayout.CENTER);
Full Code of DFrametest class:
public class DFrametest extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DFrametest frame = new DFrametest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public DFrametest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
test2 t = new test2();
contentPane.setLayout(new BorderLayout());
contentPane.add(t, BorderLayout.CENTER);
pack();
}
}
Try to use setBounds() method since you haven't mentioned any layout (setLayout is null).
Add setBounds method before adding the jpanel to the jframe
setBounds(x-axis,y-axis,width,height);
EX:-
setBounds(10,20,200,400);
Note:

Categories

Resources