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);
Related
Im bulding a GUI using eclipse plugin WindowsBuilder, im trying to pass a variable "comboBox kombo" from the initialize() method. I cant call the method to run my passed variable. The method supposed to get the data from my database to the comboBox.
Below i have attached my coding, any help will be appreciated ,Thank you!
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Label;
import java.awt.Font;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JTextField;
public class book extends JFrame {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
private JFrame mdetail;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
book window = new book();
window.mdetail.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public book() {
initialize();
comboBox(kombo);
}
private void comboBox(JComboBox kombo) {
try
{
con= DriverManager.getConnection("jdbc:mysql://localhost/oop_project", "root","");
String sql = "select movieName from movie ";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next())
{
String name = rs.getString("movieName");
kombo.addItem(name);
}
}catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex);
}
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
mdetail = new JFrame();
mdetail.setTitle("Book Ticket");
mdetail.setBounds(100, 100, 450, 336);
mdetail.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mdetail.getContentPane().setLayout(null);
Label label = new Label("Movie Details");
label.setForeground(Color.BLACK);
label.setFont(new Font("Dialog", Font.PLAIN, 21));
label.setBounds(135, 10, 184, 54);
mdetail.getContentPane().add(label);
JComboBox kombo = new JComboBox();
kombo.setBounds(155, 70, 226, 22);
mdetail.getContentPane().add(kombo);
Label label_1 = new Label("Select Movie");
label_1.setBounds(74, 70, 75, 22);
mdetail.getContentPane().add(label_1);
Label label_1_1 = new Label("Select Date");
label_1_1.setBounds(74, 103, 75, 22);
mdetail.getContentPane().add(label_1_1);
JComboBox comboBox_1 = new JComboBox();
comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"11-12-2022", "12-12-2022", "13-12-2022"}));
comboBox_1.setBounds(155, 103, 226, 22);
mdetail.getContentPane().add(comboBox_1);
Label label_1_1_1 = new Label("Select Time");
label_1_1_1.setBounds(74, 136, 75, 22);
mdetail.getContentPane().add(label_1_1_1);
JComboBox comboBox_1_1 = new JComboBox();
comboBox_1_1.setModel(new DefaultComboBoxModel(new String[] {"7.00am", "10.00am", "1.00pm", "5.00pm", "8.00pm"}));
comboBox_1_1.setBounds(155, 136, 226, 22);
mdetail.getContentPane().add(comboBox_1_1);
Label label_1_1_2 = new Label("Select Seat");
label_1_1_2.setBounds(74, 169, 75, 22);
mdetail.getContentPane().add(label_1_1_2);
JComboBox comboBox_1_2 = new JComboBox();
comboBox_1_2.setModel(new DefaultComboBoxModel(new String[] {"A(01)", "B(02)", "B(03)"}));
comboBox_1_2.setBounds(155, 169, 226, 22);
mdetail.getContentPane().add(comboBox_1_2);
JButton btnNewButton = new JButton("SUBMIT");
btnNewButton.setBounds(155, 241, 89, 23);
mdetail.getContentPane().add(btnNewButton);
JLabel lblNewLabel = new JLabel("View Seat Position");
lblNewLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
seatposition.main(null);
mdetail.setVisible(false);
}
});
lblNewLabel.setBounds(282, 245, 112, 14);
mdetail.getContentPane().add(lblNewLabel);
Label label_1_2 = new Label("Welcome \"user\"");
label_1_2.setBounds(10, 10, 89, 22);
mdetail.getContentPane().add(label_1_2);
Label label_1_1_2_1_1 = new Label("Number of ticket");
label_1_1_2_1_1.setBounds(53, 202, 101, 22);
mdetail.getContentPane().add(label_1_1_2_1_1);
JComboBox comboBox_1_2_1 = new JComboBox();
comboBox_1_2_1.setBounds(155, 202, 226, 22);
mdetail.getContentPane().add(comboBox_1_2_1);
JMenuBar menuBar = new JMenuBar();
mdetail.setJMenuBar(menuBar);
JMenu mnNewMenu = new JMenu("Option");
menuBar.add(mnNewMenu);
JMenuItem mntmNewMenuItem = new JMenuItem("Logout");
mnNewMenu.add(mntmNewMenuItem);
JMenuItem exitmenu = new JMenuItem("Exit");
exitmenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int exit = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit", "Exit", JOptionPane.YES_NO_OPTION);
if(exit==JOptionPane.YES_OPTION) {
System.exit(0);
}else {
mdetail.setVisible(true);
}
}
});
mnNewMenu.add(exitmenu);
}
}
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);
}
}
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'm trying to open this gui from an action listener in another class but for whatever reason it's not doing it, any and all help appreciated.
package gui;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.table.DefaultTableModel;
import database.DBConnection;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JTextArea;
import javax.swing.JTable;
public class OrderExample {
static JFrame frame;
public static void main(String[] args){
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
JFrame frame = new JFrame();
JTable table= new JTable();
table.setBounds(428, 445, 396, -328);
Object[] columns = {"Product Id", "Product Name", "Description", "Price"};
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columns);
table.setModel(model);
table.setBackground(Color.white);
table.setForeground(Color.black);
Font font = new Font("", 1, 22);
table.setRowHeight(30);
JTextField prodId = new JTextField();
JTextField prodName = new JTextField();
JTextField prodPrice = new JTextField();
JButton btnAdd = new JButton("Add");
JButton btnDelete = new JButton("Delete");
JButton btnExit = new JButton("Exit");
prodId.setBounds(20, 56, 230, 38);
prodName.setBounds(20, 129, 230, 38);
prodPrice.setBounds(21, 201, 229, 39);
btnAdd.setBounds(20, 451, 100, 38);
btnDelete.setBounds(150, 451, 100, 38);
btnExit.setBounds(20, 511, 100, 39);
JScrollPane pane = new JScrollPane(table);
pane.setBounds(281, 32, 440, 518);
frame.getContentPane().setLayout(null);
frame.getContentPane().add(pane);
frame.getContentPane().add(prodId);
frame.getContentPane().add(prodName);
frame.getContentPane().add(prodPrice);
frame.getContentPane().add(btnAdd);
frame.getContentPane().add(btnDelete);
frame.getContentPane().add(btnExit);
JLabel lblAddId = new JLabel("Product ID");
lblAddId.setBounds(20, 32, 79, 14);
frame.getContentPane().add(lblAddId);
JLabel lblProduct = new JLabel("Product Name");
lblProduct.setBounds(20, 105, 100, 14);
frame.getContentPane().add(lblProduct);
JLabel lblProductPrice = new JLabel("Product Price");
lblProductPrice.setBounds(20, 178, 90, 14);
frame.getContentPane().add(lblProductPrice);
JButton btnListProducts = new JButton("List Products");
btnListProducts.setBounds(150, 511, 100, 39);
frame.getContentPane().add(btnListProducts);
JTextArea description = new JTextArea();
description.setBounds(20, 276, 230, 164);
frame.getContentPane().add(description);
JLabel lblDescription = new JLabel("Description");
lblDescription.setBounds(20, 251, 116, 14);
frame.getContentPane().add(lblDescription);
Object[] row = new Object[4];
btnAdd.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
row[0] = prodId.getText();
row[1] = prodName.getText();
row[2] = description.getText();
row[3] = prodPrice.getText();
model.addRow(row);
try{
Connection connection = DBConnection.getConnection();
PreparedStatement ps = connection.prepareStatement("insert into stock(sname, description, quantity , price) values(?,?,20,?);");
ps.setString(1, prodName.getText());
ps.setString(2, description.getText());
ps.setDouble(3, Double.parseDouble( prodPrice.getText()));
ps.executeUpdate();
}
catch(SQLException sqle){
sqle.printStackTrace();
}
}
});
btnDelete.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
int i = table.getSelectedRow();
if(i >= 0){
model.removeRow(i);
}
else{
System.out.print("Delete ");
}
}
});
table.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e) {
int i = table.getSelectedRow();
prodId.setText(model.getValueAt(i, 0). toString());
prodName.setText(model.getValueAt(i, 1).toString());
prodPrice.setText(model.getValueAt(i, 3).toString());
description.setText(model.getValueAt(i, 2).toString());
}
});
btnListProducts.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
int i = table.getSelectedRow();
try{
Connection connection = DBConnection.getConnection();
Statement statement = connection.createStatement();
ResultSet rs;
if(prodId.getText().equalsIgnoreCase(""))
rs = statement.executeQuery("select * from stock;");
else
rs = statement.executeQuery("select * from stock where stockID = " + prodId.getText() + ";");
while(rs.next()){
row[0] = rs.getInt("stockID");
row[1] = rs.getString("sname");
row[2] = rs.getString("description");
row[3] = rs.getDouble("price");
model.addRow(row);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
btnExit.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
frame.dispose();
}
});
frame.setSize(771, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
This is the actionlistener code
btnStock.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
OrderExample window = new OrderExample();
}
});
I've tried to set window to visible but it just gives me an error.
The class OrderExamplehas all of its functionality in its (static) main method which is never been called by your Actionlistener implementation.
You could simply add the call to OrderExample.main to your Actionlistener implementation, but you should better first move the content of main to a non static method (e.g.: init) and call that.
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);
}
}