Why isn't the Frame showing? - java

After implementing the Observer/Observable pattern, I can't really see why the Frame isn't showing when the code is executed.
I've looked over it a million times but can't figure it out.
I just want to know where I've gone wrong and how I can fix, so that the frame is showing.
Apologies for the code dump. Would be very grateful for the assistance.
public class MainGameFrame extends JFrame implements KeyListener,Observer {
private final JLabel lblPythonChallenge = DefaultComponentFactory
.getInstance().createTitle("Code Wars");
protected JTextArea textAreaEditable;
protected JTextArea textAreaQuestion;
protected JTextArea textAreaResult;
protected JTextArea textAreaScore;
protected PrintWriter output; // to write textArea stuff to file
private JTextArea textAreaPreview;
private JLabel lblPreview;
private ServerToClient model;
private Socket sock;
/**
* Create the application.
*/
public MainGameFrame() {
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
try {
sock = new Socket("127.0.0.1", 6789);
model = new ServerToClient(sock);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
initialize();
setVisible(true);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
model.addObserver(this);
getContentPane().setBackground(new Color(153, 204, 102));
setForeground(Color.GREEN);
setBackground(Color.GREEN);
setTitle("Code Wars");
setBounds(100, 100, 762, 511);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
// TextArea 1
textAreaEditable = new JTextArea();
textAreaEditable.setBounds(10, 117, 353, 130);
getContentPane().add(textAreaEditable);
textAreaEditable.setTabSize(2); // fix tab size
// auto-indentation
textAreaEditable.registerKeyboardAction(new IndentNextLine(),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
JComponent.WHEN_FOCUSED);
// add KeyListener
textAreaEditable.addKeyListener(this);
// TextArea 2
textAreaQuestion = new JTextArea();
textAreaQuestion.setBackground(new Color(255, 255, 255));
textAreaQuestion.setBounds(10, 34, 353, 46);
getContentPane().add(textAreaQuestion);
// TextArea 3
textAreaResult = new JTextArea();
textAreaResult.setBounds(10, 357, 713, 104);
getContentPane().add(textAreaResult);
textAreaResult.setEditable(false);
// JTextPane textPane_1 = new JTextPane();
// textPane_1.setBounds(463, 158, 273, 269);
// frmPythonChallenge.getContentPane().add(textPane_1);
// component 4
JButton btnRunCode = new JButton("Run Code");
btnRunCode.setBounds(10, 258, 330, 31);
getContentPane().add(btnRunCode);
btnRunCode.addActionListener(new RunButtonListener());
// TextArea 4
textAreaScore = new JTextArea();
textAreaScore.setBounds(373, 34, 350, 46);
getContentPane().add(textAreaScore);
lblPythonChallenge.setBounds(23, -31, 143, 31);
getContentPane().add(lblPythonChallenge);
JLabel lblEnterCodeIn = DefaultComponentFactory.getInstance()
.createLabel("Enter code in the box below:");
lblEnterCodeIn.setForeground(new Color(0, 100, 0));
lblEnterCodeIn.setFont(new Font("Tahoma", Font.BOLD, 12));
lblEnterCodeIn.setBounds(10, 91, 209, 15);
getContentPane().add(lblEnterCodeIn);
JLabel lblQuestion = DefaultComponentFactory.getInstance().createLabel(
"Question:");
lblQuestion.setForeground(new Color(0, 100, 0));
lblQuestion.setFont(new Font("Tahoma", Font.BOLD, 12));
lblQuestion.setBounds(10, 9, 92, 14);
getContentPane().add(lblQuestion);
JLabel lblScores = DefaultComponentFactory.getInstance().createLabel(
"Scores:");
lblScores.setForeground(new Color(0, 100, 0));
lblScores.setFont(new Font("Tahoma", Font.BOLD, 12));
lblScores.setBounds(373, 9, 92, 14);
getContentPane().add(lblScores);
JLabel lblThisIsThe = DefaultComponentFactory.getInstance()
.createLabel("This is the result from your code!");
lblThisIsThe.setForeground(new Color(0, 100, 0));
lblThisIsThe.setFont(new Font("Tahoma", Font.BOLD, 12));
lblThisIsThe.setBounds(10, 328, 238, 15);
getContentPane().add(lblThisIsThe);
// TextArea 5
textAreaPreview = new JTextArea();
textAreaPreview.setBounds(373, 117, 350, 130);
textAreaPreview.setTabSize(2);
textAreaPreview.setEditable(false);
getContentPane().add(textAreaPreview);
lblPreview = DefaultComponentFactory.getInstance().createLabel(
"Preview");
lblPreview.setForeground(new Color(0, 128, 0));
lblPreview.setFont(new Font("Tahoma", Font.BOLD, 12));
lblPreview.setLabelFor(lblPreview);
lblPreview.setBounds(373, 84, 200, 31);
getContentPane().add(lblPreview);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainGameFrame window = new MainGameFrame();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}

Change your main() method to this:
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainGameFrame window = new MainGameFrame();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

At the end of the initialize() method, add some code that will make MainGameFrame() visible:
this.setVisible(true);
I also suggest you use a Layout Manager to organize the components. Oracle has some great tutorials on how to use different layouts. How to Use Various Layout Managers

Related

paging in java swing with jtable and database

I am new to java and I am working on Jtable with database.i fill up my jtable by data from database ,now I need to use paging and I don't know how to implement this in my code,i used DbUtils to fill up the jtable,every think is ok but the problem is that i don't know how to use pagination, thank you in advance for any sharing of information and help
public class FenetrePers extends JFrame {
private JTextField rechNomField;
private JTextField rechPrenField;
private JTextField rechemailField;
private JTextField rechtelephField;
private JButton btnNewButton_2;
AjoutPers ajpers;
Connection cnx =null;
PreparedStatement prepared=null;
ResultSet resultat=null;
private JScrollPane scrollPane;
private JTable table;
private JButton editButton;
private JButton deleteButton;
public FenetrePers() {
cnx=ConnectionSql.ConnexionDB();
this.setExtendedState(this.MAXIMIZED_BOTH);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel(" Gestion du personnel");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 14));
lblNewLabel.setForeground(Color.BLACK);
lblNewLabel.setBounds(10, 23, 181, 21);
getContentPane().add(lblNewLabel);
rechNomField = new JTextField();
rechNomField.setBounds(27, 84, 175, 32);
getContentPane().add(rechNomField);
rechNomField.setColumns(10);
rechPrenField = new JTextField();
rechPrenField.setBounds(298, 84, 163, 32);
getContentPane().add(rechPrenField);
rechPrenField.setColumns(10);
rechemailField = new JTextField();
rechemailField.setBounds(587, 84, 163, 32);
getContentPane().add(rechemailField);
rechemailField.setColumns(10);
rechtelephField = new JTextField();
rechtelephField.setBounds(844, 84, 157, 32);
getContentPane().add(rechtelephField);
rechtelephField.setColumns(10);
JButton FindButton = new JButton("find");
FindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
UpdateTableSearch();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
FindButton.setBounds(1034, 89, 66, 27);
getContentPane().add(FindButton);
JButton btnNewButton_1 = new JButton("reset");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String nomS=rechNomField.getText().toString();
String prenomS=rechPrenField.getText().toString();
String emailS=rechemailField.getText().toString();
String telephS=rechtelephField.getText().toString();
if(!nomS.equals("")|| !prenomS.equals("")|| !emailS.equals("")||!telephS.equals("")) {
rechNomField.setText("");
rechPrenField.setText("");
rechemailField.setText("");
rechtelephField.setText("");
UpdateTable();
}}
});
btnNewButton_1.setBounds(1110, 89, 66, 27);
getContentPane().add(btnNewButton_1);
btnNewButton_2 = new JButton("Ajouter personnel");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ajpers = new AjoutPers(FenetrePers.this);
UpdateTable();
}
});
btnNewButton_2.setBounds(1034, 24, 142, 32);
getContentPane().add(btnNewButton_2);
scrollPane = new JScrollPane();
scrollPane.setBounds(27, 150, 985, 308);
getContentPane().add(scrollPane);
table = new JTable();
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
}
});
scrollPane.setViewportView(table);

Select two conditions for different panels to then decide two values to select the users game

I need to select two values from two of my frames (Key and Level) to decide what level of test the user will be completing that will then update the label on the start panel to say if the user has selected anything and what they have selected.
I have used window builder in eclipse to help my do this but when i click the button where i have set the value it doesn't change on the label and the label saying if the user can start of not doesn't change
here is my code..(I know its probably really messy im new to all this):
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import java.awt.Font;
public class Test {
private JFrame frame;
int key = 0;
int level=0;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
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);
JPanel Home = new JPanel();
Home.setBounds(6, 6, 438, 266);
frame.getContentPane().add(Home);
JPanel SelectKey = new JPanel();
SelectKey.setBounds(6, 6, 438, 266);
frame.getContentPane().add(SelectKey);
JPanel SelectLevel = new JPanel();
SelectLevel.setBounds(6, 6, 438, 266);
frame.getContentPane().add(SelectLevel);
SelectLevel.setLayout(null);
JPanel Start = new JPanel();
Start.setBounds(6, 6, 438, 266);
frame.getContentPane().add(Start);
Start.setLayout(null);
JButton btnHome = new JButton("Home");
btnHome.setBounds(169, 141, 100, 29);
btnHome.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Home.setVisible(true);
SelectKey.setVisible(false);
SelectLevel.setVisible(false);
Start.setVisible(false);
}
});
Home.setLayout(null);
Home.add(btnHome);
JButton btnSelectKey = new JButton("Select Key");
btnSelectKey.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Home.setVisible(false);
SelectKey.setVisible(true);
SelectLevel.setVisible(false);
Start.setVisible(false);
}
});
btnSelectKey.setBounds(159, 67, 117, 29);
Home.add(btnSelectKey);
JButton btnSelectLevel = new JButton("Select Level");
btnSelectLevel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SelectKey.setVisible(false);
SelectLevel.setVisible(true);
Home.setVisible(false);
Start.setVisible(false);
}
});
btnSelectLevel.setBounds(159, 37, 117, 29);
Home.add(btnSelectLevel);
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SelectKey.setVisible(false);
SelectLevel.setVisible(false);
Home.setVisible(false);
Start.setVisible(true);
}
});
btnStart.setBounds(159, 92, 117, 29);
Home.add(btnStart);
JLabel lblHome = new JLabel("Home");
lblHome.setFont(new Font("Comic Sans MS", Font.PLAIN, 16));
lblHome.setBounds(197, 18, 61, 16);
Home.add(lblHome);
JButton btnNewButton = new JButton("Home");
btnNewButton.setBounds(169, 185, 100, 29);
btnNewButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
Home.setVisible(true);
SelectKey.setVisible(false);
SelectLevel.setVisible(false);
Start.setVisible(false);
}
});
SelectKey.setLayout(null);
SelectKey.add(btnNewButton);
JButton btnKeyA = new JButton("Key A");
btnKeyA.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
key = 1;
System.out.print(key);
}
});
btnKeyA.setBounds(157, 44, 117, 29);
SelectKey.add(btnKeyA);
JButton btnKeyB = new JButton("Key B");
btnKeyB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
key = 2;
System.out.print(key);
}
});
btnKeyB.setBounds(157, 90, 117, 29);
SelectKey.add(btnKeyB);
JButton btnKeyC = new JButton("Key C");
btnKeyC.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
key = 3;
System.out.print(key);
}
});
btnKeyC.setBounds(157, 129, 117, 29);
SelectKey.add(btnKeyC);
JLabel lblSelectKey = new JLabel("Select Key");
lblSelectKey.setFont(new Font("Comic Sans MS", Font.PLAIN, 16));
lblSelectKey.setBounds(168, 19, 117, 23);
SelectKey.add(lblSelectKey);
JButton btnBeginnner = new JButton("Beginnner");
btnBeginnner.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
level = 1;
System.out.print(level);
}
});
btnBeginnner.setBounds(158, 67, 117, 29);
SelectLevel.add(btnBeginnner);
JButton btnIntermediate = new JButton("Intermediate");
btnIntermediate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
level=2;
System.out.print(level);
}
});
btnIntermediate.setBounds(158, 113, 117, 29);
SelectLevel.add(btnIntermediate);
JButton btnAdvanced = new JButton("Advanced");
btnAdvanced.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
level = 3;
System.out.print(level);
}
});
btnAdvanced.setBounds(158, 166, 117, 29);
SelectLevel.add(btnAdvanced);
JButton btnHome_1 = new JButton("Home");
btnHome_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Home.setVisible(true);
SelectKey.setVisible(false);
SelectLevel.setVisible(false);
Start.setVisible(false);
}
});
btnHome_1.setBounds(158, 207, 117, 29);
SelectLevel.add(btnHome_1);
JLabel lblSelectLevel = new JLabel("Select Level");
lblSelectLevel.setFont(new Font("Comic Sans MS", Font.PLAIN, 16));
lblSelectLevel.setBounds(162, 19, 158, 36);
SelectLevel.add(lblSelectLevel);
JLabel lblStart = new JLabel("Start");
lblStart.setFont(new Font("Comic Sans MS", Font.PLAIN, 16));
lblStart.setBounds(186, 25, 61, 16);
Start.add(lblStart);
JButton btnHome_2 = new JButton("Home");
btnHome_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Home.setVisible(true);
SelectKey.setVisible(false);
SelectLevel.setVisible(false);
Start.setVisible(false);
}
});
btnHome_2.setBounds(155, 216, 117, 29);
Start.add(btnHome_2);
JLabel lblSelectkeylabel = new JLabel("SelectKeyLabel");
lblSelectkeylabel.setFont(new Font("Comic Sans MS", Font.PLAIN, 16));
lblSelectkeylabel.setBounds(175, 64, 97, 41);
lblSelectkeylabel.setText(Integer.toString(key));
Start.add(lblSelectkeylabel);
JLabel lblSelectlevellabel = new JLabel("Selectlevellabel");
lblSelectlevellabel.setFont(new Font("Comic Sans MS", Font.PLAIN, 16));
lblSelectlevellabel.setBounds(169, 107, 146, 41);
lblSelectlevellabel.setText(Integer.toString(level));
Start.add(lblSelectlevellabel);
JLabel lblChoicedone = new JLabel("Choicedone");
lblChoicedone.setFont(new Font("Comic Sans MS", Font.PLAIN, 16));
lblChoicedone.setBounds(175, 147, 61, 16);
if (key==0 || level ==0) {
lblChoicedone.setText("Please go back and choose a key and a level");
}
else {
lblChoicedone.setText("Please Start");
}
Start.add(lblChoicedone);
JButton btnStart_1 = new JButton("Start");
btnStart_1.setBounds(155, 185, 117, 29);
Start.add(btnStart_1);
}
}

Unable to call another function from Actionlistener

I am trying to come up with a simple tool that takes DB Parameters as input from the user in JTextFields and when the user clicks on connect to DB, it uses the input to connect to DB. The UI part is written in a function in the main class from where it is supposed to call the DBConnector class method and pass the input text parameters via the ActionListener. I cannot seem to make the ActionListener part work at all. Here's the main class code below:
public class ExcelReportGenerator implements DocumentListener{
//MAIN METHOD
public static void main(String[] args) {
try {
createAndShowUI();
} catch (Exception e) {
e.printStackTrace();
}
}
public ExcelReportGenerator(JButton button1, JButton button2)
{
button1=this.button1;
button2=this.button2;
}
private JButton button1 ;
private JButton button2;
private List<JTextField> textFields = new ArrayList<JTextField>();
//public void DBCaller()
public void addTextField(JTextField textField)
{
textFields.add( textField );
textField.getDocument().addDocumentListener( this );
}
public boolean isDataEntered()
{
for (JTextField textField : textFields)
{
if (textField.getText().trim().length() == 0)
return false;
}
return true;
}
#Override
public void insertUpdate(DocumentEvent e)
{
checkData();
}
#Override
public void removeUpdate(DocumentEvent e)
{
checkData();
}
#Override
public void changedUpdate(DocumentEvent e) {}
private void checkData()
{
button1.setEnabled( isDataEntered() );
button2.setEnabled( isDataEntered() );
}
private static void createAndShowUI() throws RowsExceededException, ClassNotFoundException, WriteException, SQLException, IOException
{
//CREATING BUTTONS
JButton submit = new JButton( "Connect To DB" );
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DBConnector.DBConnection(textField_1.getText(),textField_2.getText(),
textField_3.getText(),textField_4.getText(),textField_5.getText());
//NEED TO ACCESS THE DBCONNECTOR CLASS METHOD HERE
}
});
submit.setEnabled(false);
submit.setBackground(UIManager.getColor("Button.disabledShadow"));
submit.setForeground(new Color(0, 0, 128));
submit.setBounds(282, 77, 192, 36);
JButton btnExportToExcel = new JButton("Export To Excel");
btnExportToExcel.setEnabled(false);
btnExportToExcel.setForeground(new Color(0, 0, 128));
btnExportToExcel.setBackground(UIManager.getColor("Button.background"));
submit.setBackground(UIManager.getColor("Button.disabledShadow"));
btnExportToExcel.setBounds(282, 178, 192, 36);
//DECLARING TEXTFIELDS
JTextField textField_1 = new JTextField();
textField_1.setBackground(new Color(255, 255, 224));
JTextField textField_2 = new JTextField();
textField_2.setBackground(new Color(255, 255, 224));
JTextField textField_3 = new JTextField();
textField_3.setBackground(new Color(255, 255, 224));
JTextField textField_4 = new JTextField();
textField_4.setBackground(new Color(255, 255, 224));
JTextField textField_5 = new JTextField();
textField_5.setBackground(new Color(255, 255, 224));
JTextField textField_6 = new JTextField();
textField_6.setBackground(new Color(255, 255, 224));
JTextField textField_7 = new JTextField();
textField_7.setBackground(new Color(255, 255, 224));
//ADDING TEXTFIELDS TO ARRAY THROUGH CONSTRUCTOR
ExcelReportGenerator de = new ExcelReportGenerator( submit , btnExportToExcel);
de.addTextField( textField_1 );
de.addTextField( textField_2 );
de.addTextField( textField_3 );
de.addTextField( textField_4 );
de.addTextField( textField_5 );
de.addTextField( textField_6 );
de.addTextField( textField_7 );
//CREATING THE FRAME
JFrame frame = new JFrame("Report Maker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(500,335));
frame.getContentPane().setLayout(null);
frame.getContentPane().add(submit);
frame.getContentPane().add(btnExportToExcel);
//ALL TEXTFIELDS
textField_1.setBounds(112, 62, 117, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
textField_2.setBounds(112, 93, 117, 20);
frame.getContentPane().add(textField_2);
textField_2.setColumns(10);
textField_3.setBounds(112, 124, 117, 20);
frame.getContentPane().add(textField_3);
textField_3.setColumns(10);
textField_4.setBounds(112, 155, 117, 20);
frame.getContentPane().add(textField_4);
textField_4.setColumns(10);
textField_5.setBounds(112, 186, 117, 20);
frame.getContentPane().add(textField_5);
textField_5.setColumns(10);
textField_6.setBounds(112, 219, 117, 20);
frame.getContentPane().add(textField_6);
textField_6.setColumns(10);
textField_7.setBounds(112, 250, 117, 20);
frame.getContentPane().add(textField_7);
textField_7.setColumns(10);
//DBConnector.DBConnection(username,password,hostname,port,sid,tablename,filename);
//ALL LABELS
JLabel lblDatabaseToExcel = new JLabel("Database To Excel Tool");
lblDatabaseToExcel.setForeground(new Color(0, 0, 128));
lblDatabaseToExcel.setFont(new Font("Georgia", Font.BOLD, 20));
lblDatabaseToExcel.setBounds(123, -11, 351, 50);
frame.getContentPane().add(lblDatabaseToExcel);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblUsername.setForeground(new Color(0, 0, 128));
lblUsername.setBounds(20, 44, 200, 50);
frame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblPassword.setForeground(new Color(0, 0, 128));
lblPassword.setBounds(20, 78, 200, 50);
frame.getContentPane().add(lblPassword);
JLabel lblHostname = new JLabel("Hostname:");
lblHostname.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblHostname.setForeground(new Color(0, 0, 128));
lblHostname.setBounds(20, 109, 200, 50);
frame.getContentPane().add(lblHostname);
JLabel lblPort = new JLabel("Port:");
lblPort.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblPort.setForeground(new Color(0, 0, 128));
lblPort.setBounds(20, 140, 200, 50);
frame.getContentPane().add(lblPort);
JLabel lblSid = new JLabel("SID:");
lblSid.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblSid.setForeground(new Color(0, 0, 128));
lblSid.setBounds(20, 171, 200, 50);
frame.getContentPane().add(lblSid);
JLabel lblEnterDbDetails = new JLabel("DB Details:");
lblEnterDbDetails.setForeground(new Color(0, 0, 128));
lblEnterDbDetails.setFont(new Font("Vrinda", Font.BOLD, 15));
lblEnterDbDetails.setBounds(20, 11, 200, 50);
frame.getContentPane().add(lblEnterDbDetails);
JLabel lblTableviewName = new JLabel("Table/View Name:");
lblTableviewName.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblTableviewName.setForeground(new Color(0, 0, 128));
lblTableviewName.setBackground(new Color(255, 228, 225));
lblTableviewName.setBounds(20, 203, 200, 50);
frame.getContentPane().add(lblTableviewName);
JLabel lblEnterNameOf = new JLabel("Enter Name Of File:");
lblEnterNameOf.setForeground(new Color(0, 0, 128));
lblEnterNameOf.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblEnterNameOf.setBounds(20, 235, 200, 50);
frame.getContentPane().add(lblEnterNameOf);
JLabel lblgeneratedFileLocated = new JLabel("(Generated File Located At C:\\)");
lblgeneratedFileLocated.setFont(new Font("Tahoma", Font.PLAIN, 11));
lblgeneratedFileLocated.setForeground(new Color(205, 92, 92));
lblgeneratedFileLocated.setBounds(305, 204, 200, 50);
frame.getContentPane().add(lblgeneratedFileLocated);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
}
Here's the DBConnector Class code below:
public class DBConnector implements ActionListener
{
public static void DBConnection(String user,String pword, String host, String portnum, String sidValue, String table, String generatedfile) throws SQLException, ClassNotFoundException, RowsExceededException, WriteException, IOException
{
String username=user;
String password=pword;
String hostname=host;
String port=portnum;
String sid=sidValue;
String tablename=table;
String filename=generatedfile;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is the fricking JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("Oracle JDBC Driver Found!");
Connection con;
try {
Properties props=new Properties();
props.put("user",username);
props.put("password",password);
props.setProperty("hostname",hostname);
props.setProperty("port",port);
props.setProperty("sid",sid);
String jdbcurl="jdbc:oracle:oci:#";
System.out.println();
con = DriverManager
.getConnection(jdbcurl,props);
}
catch (SQLException e)
{
JOptionPane.showMessageDialog(null, " DB Connection Failed,\n Make Sure All Details Entered Are Correct");
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (con != null)
{
JOptionPane.showMessageDialog(null, "Connected to Database\nClick on the Export To Excel Button");
System.out.println("You made it, take control your database now!");
ReportMaker.reportParameters(tablename,filename, con);
}
else
{
JOptionPane.showMessageDialog(null, " DB Connection Failed,\n Make Sure All Details Entered Are Correct");
}
}
}

Swing gui disappeared

I am working on a simple GUI with options to add,remove,write to disk etc.. While i was coding my program i came to a problem where the GUI start to disappear and opening only blank frame in the design tab/editor(also in run time), i tried to undo multiple times and it was coming back but this time i am to a point where i cannot do undo anymore. I posted all the code i have. What could be the solution to this problem ?
package nikola.lozanovski.bitola;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class VozenRed extends JFrame {
public VozenRed() {
}
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JButton Delete;
private JButton Transporter;
private JTextField IdBox;
private JTextField InitialBox;
private JTextField FinalBox;
private JTextField Hbox;
private JTextField PriceBox;
private JTextField AgencyBox;
private JTextField SaveBox;
private JTextField Mbox;
private JTextField DeleteBox;
private JTextField DestinationsBox;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
VozenRed frame = new VozenRed();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #return
*/
public void pishi(){ //tried deleting from here
Hashtable<Broj, Elementi> h1=new Hashtable<Broj, Elementi>();
try
{
Broj B=new Broj(IdBox.getText());
Elementi elem=new Elementi(InitialBox.getText(), FinalBox.getText(), Hbox.getText(), Mbox.getText(), PriceBox.getText(), AgencyBox.getText());
h1.put(B , elem);
}
catch(Exception e)//i tried NullPointerException still the same
{
System.out.println("asd");//not realy what i meant
}
} //deleting to here, still no frame
public void VozenRed1() {
setTitle("Transport me");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 502, 396);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton InitialDestination = new JButton("Initial Destination");
InitialDestination.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Input the initial destination, I.E. My Home", "Initial Destination", 2);
}
});
InitialDestination.setBounds(255, 63, 194, 23);
contentPane.add(InitialDestination);
JButton FinalDestination = new JButton("Final Destination");
FinalDestination.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Input final destination, I.E. Your Home", "Final Destination", 2);
}
});
FinalDestination.setBounds(255, 97, 194, 23);
contentPane.add(FinalDestination);
JButton TimeDeparture = new JButton("Departure Time");
TimeDeparture.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Input time, Hours in first box, Minutes in second box, I.E. 00:00", "Departure Time", 2);
}
});
TimeDeparture.setBounds(255, 128, 194, 23);
contentPane.add(TimeDeparture);
JButton TicketPrice = new JButton("Ticket Price");
TicketPrice.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,"Input price, digits only, I.E. 100","TicketPrice",2);
}
});
TicketPrice.setBounds(255, 159, 194, 23);
contentPane.add(TicketPrice);
Transporter = new JButton("Transport Agency");
Transporter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,"Input transporter name, I.E. MyTrans","Transporter",2);
}
});
Transporter.setBounds(255, 190, 194, 23);
contentPane.add(Transporter);
JButton SaveRoute = new JButton("Save Route");
SaveRoute.setBounds(255, 320, 194, 23);
contentPane.add(SaveRoute);
Delete = new JButton("Delete");
Delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
Delete.setBounds(255, 286, 194, 23);
contentPane.add(Delete);
JButton Destinations = new JButton("Destinations");
Destinations.setBounds(255, 252, 194, 23);
contentPane.add(Destinations);
JLabel InputLabel = new JLabel("Input Elements");
InputLabel.setBounds(44, 11, 211, 14);
contentPane.add(InputLabel);
JLabel CommandsLabel = new JLabel("Additional Commands");
CommandsLabel.setBounds(44, 222, 201, 14);
contentPane.add(CommandsLabel);
JButton IdentificationNumber = new JButton("Identification Number");
IdentificationNumber.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Enter Identification number , only numbers, I.E. 0123","IdentificationNumber", 2);
}
});
IdentificationNumber.setBounds(255, 29, 194, 23);
contentPane.add(IdentificationNumber);
JButton ClearAll = new JButton("Clear All");
ClearAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IdBox.setText(null);
InitialBox.setText(null);
FinalBox.setText(null);
Hbox.setText(null);
Mbox.setText(null);
PriceBox.setText(null);
AgencyBox.setText(null);
}
});
ClearAll.setFont(new Font("Tahoma", Font.BOLD, 11));
ClearAll.setBounds(255, 218, 194, 23);
contentPane.add(ClearAll);
JLabel lblHelpButtons = new JLabel("Help Buttons");
lblHelpButtons.setBounds(314, 11, 76, 14);
contentPane.add(lblHelpButtons);
JButton HelpDestinations = new JButton("");
HelpDestinations.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Outputs Destinations in a new box","Destinations", 2);
}
});
HelpDestinations.setBounds(459, 252, 17, 23);
contentPane.add(HelpDestinations);
JButton HelpDelete = new JButton("");
HelpDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Deletes selected Identification","Delete", 2);
}
});
HelpDelete.setBounds(459, 286, 17, 23);
contentPane.add(HelpDelete);
JButton HelpSave = new JButton("");
HelpSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Choose Directory to save","Save Document", 2);
}
});
HelpSave.setBounds(459, 320, 17, 23);
contentPane.add(HelpSave);
JButton HelpClearAll = new JButton("");
HelpClearAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Clears all the boxes above","Clear All", 2);
}
});
HelpClearAll.setBounds(459, 218, 17, 23);
contentPane.add(HelpClearAll);
JButton IdentificationHelpButton = new JButton("");
IdentificationHelpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
IdBox.setText(null);
}
});
IdentificationHelpButton.setBounds(10, 29, 17, 23);
contentPane.add(IdentificationHelpButton);
JButton InitialDestinationHelpButton = new JButton("");
InitialDestinationHelpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
InitialBox.setText(null);
}
});
InitialDestinationHelpButton.setBounds(10, 60, 17, 23);
contentPane.add(InitialDestinationHelpButton);
JButton FinalDestinationHelpButton = new JButton("");
FinalDestinationHelpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
FinalBox.setText(null);
}
});
FinalDestinationHelpButton.setBounds(10, 97, 17, 23);
contentPane.add(FinalDestinationHelpButton);
JButton DeparturetimeHelpButton = new JButton("");
DeparturetimeHelpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Hbox.setText(null);
Mbox.setText(null);
}
});
DeparturetimeHelpButton.setBounds(10, 129, 17, 23);
contentPane.add(DeparturetimeHelpButton);
JButton TicketPriceHelpButton = new JButton("");
TicketPriceHelpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
PriceBox.setText(null);
}
});
TicketPriceHelpButton.setBounds(10, 159, 17, 23);
contentPane.add(TicketPriceHelpButton);
JButton TransporterHelpButton = new JButton("");
TransporterHelpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AgencyBox.setText(null);
}
});
TransporterHelpButton.setBounds(10, 190, 17, 23);
contentPane.add(TransporterHelpButton);
JLabel label = new JLabel(" :");
label.setBounds(113, 132, 39, 14);
contentPane.add(label);
JButton SaveDocumentButton = new JButton("");
SaveDocumentButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SaveBox.setText(null);
}
});
SaveDocumentButton.setBounds(10, 320, 17, 23);
contentPane.add(SaveDocumentButton);
IdBox = new JTextField();
IdBox.setBounds(44, 30, 201, 20);
contentPane.add(IdBox);
IdBox.setColumns(10);
InitialBox = new JTextField();
InitialBox.setColumns(10);
InitialBox.setBounds(44, 64, 201, 20);
contentPane.add(InitialBox);
FinalBox = new JTextField();
FinalBox.setColumns(10);
FinalBox.setBounds(44, 98, 201, 20);
contentPane.add(FinalBox);
Hbox = new JTextField();
Hbox.setColumns(10);
Hbox.setBounds(44, 129, 86, 20);
contentPane.add(Hbox);
PriceBox = new JTextField();
PriceBox.setColumns(10);
PriceBox.setBounds(44, 160, 201, 20);
contentPane.add(PriceBox);
AgencyBox = new JTextField();
AgencyBox.setColumns(10);
AgencyBox.setBounds(44, 191, 201, 20);
contentPane.add(AgencyBox);
SaveBox = new JTextField();
SaveBox.setColumns(10);
SaveBox.setBounds(44, 321, 201, 20);
contentPane.add(SaveBox);
Mbox = new JTextField();
Mbox.setColumns(10);
Mbox.setBounds(145, 129, 100, 20);
contentPane.add(Mbox);
DeleteBox = new JTextField();
DeleteBox.setColumns(10);
DeleteBox.setBounds(44, 287, 201, 20);
contentPane.add(DeleteBox);
DestinationsBox = new JTextField();
DestinationsBox.setColumns(10);
DestinationsBox.setBounds(44, 253, 201, 20);
contentPane.add(DestinationsBox);
JButton DeleteHelpButton = new JButton("");
DeleteHelpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DeleteBox.setText(null);
}
});
DeleteHelpButton.setBounds(10, 286, 17, 23);
contentPane.add(DeleteHelpButton);
JButton DestinationHelpButton = new JButton("");
DestinationHelpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DestinationsBox.setText(null);
}
});
DestinationHelpButton.setBounds(10, 252, 17, 23);
contentPane.add(DestinationHelpButton);
}
}
Looks like your code never calls all that UI stuff in VozenRed1().
You create the VozenRed object, which calls the empty constructor, then you set it to be visible. Never calling VozenRed1().
I think you've missed initComponents() in the constructor of your jframe.

JAVA two way communication between classes

I want to be able to create an instance of my Client class in my GUI and then pass GUI.this as a parameter for the Client constructor but I'm not sure exactly how to do that. I know I'm missing something obvious! I want to be able to call methods on the other from either class. Obviously I have commented code out because I don't know how or what I am supposed to do to achieve this two way communication without merging the classes! I want to be able to do stuff like send a command through the Client from the GUI class when the "Up" button is clicked on the GUI etc. Thanks for the help in advance.
Client class:
public class Client{
//static playerGUI GUI;
public static void main(String[] args) {
//GUI = new playerGUI();
//GUI.getFrame().setVisible(true);
//Client cli = new Client("localhost",4444);
}
public Client(playerGUI GUI){
try{
final Socket sock = new Socket("localhost",4444);
final DataInputStream in = new DataInputStream(sock.getInputStream());
final PrintStream out = new PrintStream(sock.getOutputStream());
DataInputStream inputLine = new DataInputStream(new BufferedInputStream(System.in));
final Thread serverResponse = new Thread(){
public void run(){
System.out.println("DUNGEON OF DOOM HAS STARTED");
if(sock != null){
if(in != null){
try{
String response;
while((response = in.readLine()) != null){
//GUI.processgrid(response);
//send to GUI to process output!
System.out.println(response);
}
}catch(UnknownHostException uhe){
System.err.println("Unknown host1: " + uhe);
}catch(IOException ioe){
System.err.println("IOException1: " + ioe);
}catch(NullPointerException npe){
System.err.println("Null Pointer1: " + npe);
}
}
}
}
};
serverResponse.start();
if(sock != null){
if(out != null){
try{
while(true){
//inputbuttons!
String sending = inputLine.readLine();
out.println(sending);
if(sending.equals("QUIT")) break;
}
}catch(UnknownHostException uhe2){
System.err.println("Unknown host2: " + uhe2);
}catch(IOException ioe2){
System.err.println("IOException2: " + ioe2);
}catch(NullPointerException npe2){
System.err.println("Null Pointer2: " + npe2);
}
}
}
out.close();
in.close();
sock.close();
}catch(UnknownHostException uhe3){
System.err.println("Unknown host3: " + uhe3);
}catch(IOException ioe3){
System.err.println("IOException3: " + ioe3);
}catch(NullPointerException npe3){
System.err.println("Null Pointer3: " + npe3);
}
}
}
GUI Class:
public class playerGUI {
private JFrame Frame = new JFrame();
private JPanel displayPanel;
private JTextPane hostTextPane;
private JTextPane portTextPane;
private playerGUI GUI;
public static void main(String[] args) {
playerGUI GUI = new playerGUI();
GUI.Frame.setVisible(true);
Client newclient = new Client(this.playerGUI);
}
/**
* Create the application.
*/
public playerGUI() {
Frame.getContentPane().setBackground(new Color(255, 255, 255));
Frame.getContentPane().setLayout(null);
Frame.setBounds(100, 100, 500, 630);
Frame.setUndecorated(false); // REMOVES MENU BAR
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// ############################################################################################################################################################################
final JPanel humanGameWindow = new JPanel();
humanGameWindow.setLayout(null);
humanGameWindow.setBackground(Color.LIGHT_GRAY);
humanGameWindow.setBounds(0, 0, 500, 600);
humanGameWindow.setVisible(false);
JLabel gameTitle = new JLabel("DUNGEON OF DOOM!!");
gameTitle.setForeground(new Color(100, 149, 237));
gameTitle.setFont(new Font("Moire", Font.BOLD, 28));
gameTitle.setBounds(92, 5, 380, 50);
JButton up = new JButton("Up");
up.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
up.setBackground(new Color(100, 149, 237));
up.setBounds(274, 514, 100, 40);
JButton down = new JButton("Down");
down.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
down.setBackground(new Color(100, 149, 237));
down.setBounds(274, 555, 100, 40);
JButton left = new JButton("Left");
left.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
left.setBackground(new Color(100, 149, 237));
left.setBounds(173, 535, 100, 40);
JButton right = new JButton("Right");
right.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
right.setBackground(new Color(100, 149, 237));
right.setBounds(375, 535, 100, 40);
JButton pickup = new JButton("Pickup");
pickup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ######################
}
});
pickup.setBackground(new Color(100, 149, 237));
pickup.setBounds(40, 555, 100, 40);
JButton Exit = new JButton("Exit");
Exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Exit.setBackground(new Color(100, 149, 237));
Exit.setBounds(427, 17, 70, 40);
displayPanel = new JPanel();
displayPanel.setBounds(48, 89, 400, 400);
displayPanel.setLayout(new GridLayout(5, 5));
displayPanel.setPreferredSize(new Dimension((int) (400), (int) (400)));
for (int i = 1; i < 26; i++) {
displayPanel.add(new JLabel("Label " + i));
}
humanGameWindow.add(gameTitle);
humanGameWindow.add(up);
humanGameWindow.add(down);
humanGameWindow.add(left);
humanGameWindow.add(right);
humanGameWindow.add(pickup);
humanGameWindow.add(Exit);
humanGameWindow.add(displayPanel);
final JPanel mainMenu = new JPanel();
mainMenu.setLayout(null);
mainMenu.setBackground(Color.LIGHT_GRAY);
mainMenu.setBounds(0, 0, 500, 600);
mainMenu.setVisible(true);
JLabel mainMenuTitle = new JLabel("DUNGEON OF DOOM!!");
mainMenuTitle.setForeground(new Color(100, 149, 237));
mainMenuTitle.setFont(new Font("Moire", Font.BOLD, 28));
mainMenuTitle.setBounds(50, 13, 380, 50);
hostTextPane = new JTextPane();
hostTextPane.setToolTipText("Enter the host name");
hostTextPane.setBackground(new Color(192, 192, 192));
hostTextPane.setBounds(50, 100, 234, 30);
hostTextPane.setFont(new Font("Moire", Font.BOLD, 19));
portTextPane = new JTextPane();
portTextPane.setToolTipText("Enter the port");
portTextPane.setBackground(new Color(192, 192, 192));
portTextPane.setBounds(50, 175, 234, 30);
portTextPane.setFont(new Font("Moire", Font.BOLD, 19));
JButton playGameHuman = new JButton("Play Game Human");
playGameHuman.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainMenu.setVisible(false);
humanGameWindow.setVisible(true);
//not sure if i need to be creating the Client here?
/*
* if (!(hostTextPane.getText().equals("")) &&
* !(portTextPane.getText().equals(""))) { try { Client cli =
* new Client(hostTextPane.getText(), Integer
* .parseInt(portTextPane.getText())); } catch (Exception e1) {
* System.out.println("Error."); } } else {
* JOptionPane.showMessageDialog(null,
* "Do not leave hostname or port no. blank."); }
*/
}
});
playGameHuman.setBackground(new Color(100, 149, 237));
playGameHuman.setBounds(50, 345, 150, 55);
mainMenu.add(mainMenuTitle);
mainMenu.add(mainMenuQuit);
mainMenu.add(playGameHuman);
mainMenu.add(hostTextPane);
mainMenu.add(portTextPane);
getFrame().getContentPane().add(humanGameWindow);
getFrame().getContentPane().add(mainMenu);
getFrame().setVisible(true);
}
}
public static void main(String[] args) {
playerGUI GUI = new playerGUI();
GUI.Frame.setVisible(true);
Client newclient = new Client(GUI);
}
main is a static method, which means it is run in a static context (ie, not "as" any instantiated object). This means you can't access this in main because there is no this to access. You need to access playerGUI with just playerGUI or playerGUI.playerGUI in your Client.main method. Also, you need to set the field playerGUI.playerGUI to static.
Instead of this:
Client newclient = new Client(this.playerGUI);
you need this:
Client newclient = new Client(GUI);
Notice that as main is static there is no this defined.
Also consider changing the names of your class and variables to follow Java naming conventions:
playerGUI should be PlayerGUI
GUI should be gui or whatever you feel like but starting with lowercase
Also do you notice that you are not using that field called GUI? You are only using the variable GUI. So it may be adding up to the confusion.

Categories