Program shows an empty window [duplicate] - java

This question already has answers here:
JLabel doesn't show up
(4 answers)
Closed 9 years ago.
I have started a program in JAVA and SOMETIMES, when I run it or debug it, it shows an empty white window. I have no idea why, but I redebug it and it shows the window correctly. Btw, it has nothing to do with the mysql connect void at the end.
Here is the code:
package com.hinx.client;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.sql.*;
public class Main {
public static void main(String [] args)
{
createWindow();
}
static void createWindow()
{
//Create panel
JPanel content = new JPanel();
content.setLayout(null);
//Build the frame
JFrame frame = new JFrame("Hinx - A marketplace for apps - Client ALPHA_0.0.1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700, 233);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.add(content);
frame.setVisible(true);
//Create username label
JLabel username = new JLabel("Username:");
username.setFont(new Font("Arial", Font.BOLD, 15));
username.setForeground(Color.white);
username.setBounds(34, 8, 100, 50);
//Create password label
JLabel password = new JLabel("Password:");
password.setFont(new Font("Arial", Font.BOLD, 15));
password.setForeground(Color.white);
password.setBounds(36, 85, 100, 50);
//Create username field
JTextField usernamet = new JTextField(20);
usernamet.setBounds(12, 50, 125, 30);
usernamet.setBorder(javax.swing.BorderFactory.createEmptyBorder());
//Create password field
JTextField passwordt = new JTextField(20);
passwordt.setBounds(12, 125, 125, 30);
passwordt.setBorder(javax.swing.BorderFactory.createEmptyBorder());
//Add the login button
JButton login = new JButton("Login");
login.setBounds(0, 175, 150, 30);
login.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
}
});
//Create login panel
JPanel loginpanel = new JPanel();
loginpanel.setLayout(null);
loginpanel.setBounds(0, 0, 150, 400);
loginpanel.setBackground(Color.gray);
//Add the items to the loginpanel
loginpanel.add(username);
loginpanel.add(password);
loginpanel.add(usernamet);
loginpanel.add(passwordt);
loginpanel.add(login);
//Add the items to the content panel
content.add(loginpanel);
}
protected void connect()
{
String driver = "com.mysql.jdbc.Driver";
String dbadress = "";
String dbname = "";
String username = "";
String password = "";
try
{
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(dbadress+dbname, username,password);
Statement st = conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
}

frame.setVisible(true);
make it the last statement, after you add all the components to the JFrame.
Also, it is generally a best practice to do any swing-related code in the GUI-thread (EDT):
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createWindow();
}
});
}

Swing GUIs should be started on the Event Dispatch Thread. See Initial Threads for more details.

Invoke frame.setVisible(true); at the end of your method ( after adding all the components to panel)

Related

Label and Textfield won't appear

So, we have a group project and we need to make a food ordering system with login and register and I'm tasked with the login layout. I used what I did on my other GUI's but I don't know why it doesn't work here. The userL and the textfield won't show. The imageIcon and it's label "LOGIN" does appear, however.
import java.awt.*;
import java.awt.event.*;
public class OOPproject implements ActionListener{
//declarations
JFrame frame;
JPanel panel;
JTextField userTF, passwordTF;
JLabel loginL, userL, passwordL, createL;
JButton loginB;
//layout
OOPproject(){
frame = new JFrame();
frame.setSize(400,400);
frame.setLayout(null);
frame.getContentPane().setBackground(Color.WHITE);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon image = new ImageIcon("11.png");
loginL = new JLabel("L O G I N");
loginL.setIcon(image);
loginL.setHorizontalTextPosition(JLabel.CENTER);
loginL.setVerticalTextPosition(JLabel.BOTTOM);
loginL.setForeground(new Color(0,191,255));
loginL.setFont(new Font("Arial",Font.BOLD,35));
loginL.setIconTextGap(5);
loginL.setVerticalAlignment(JLabel.CENTER);
loginL.setHorizontalAlignment(JLabel.CENTER);
loginL.setBounds(-8, -110, 400, 400);
frame.add(loginL);
userL = new JLabel("Username");
userL.setBounds(-16, -200, 12, 12);
userL.setVerticalAlignment(JLabel.CENTER);
userL.setHorizontalAlignment(JLabel.CENTER);
userL.setFont(new Font("Arial",Font.BOLD,12));
userL.setForeground(Color.LIGHT_GRAY);
frame.add(userL);
userTF = new JTextField();
userTF.setBackground(Color.white);
userTF.setHorizontalAlignment(JLabel.CENTER);
frame.add(userTF);
frame.setVisible(true);
}
public static void main(String[] args) {
OOPproject proj = new OOPproject();
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}

Java - Unable to open a new frame from ActionListener

I am currently designing a login screen, but I ran into a strange issue. I already designed my GUI with the help of swing, and it was time to make functional buttons. I wanted to test my login button and if it would take me to the frame I want, but it is unable to. I can set a JOptionPane.showMessageDialog for example, which works just fine, but I am unable to open another frame from the button. I tried with New JFrameName().setVisible(true), and also JFrameName test = new JFrameName(); test.setVisible(true);, but the methods show up in red. Here is my code.
package com.edu4java.swing.tutrial3;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginView {
public static void main(String[] args) {
JFrame frame = new JFrame("Bus Tour Booking System");
frame.setSize(300, 200);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel titleLabel = new JLabel("Bus Tour Booking System");
titleLabel.setBounds(70,15,150,25);
panel.add(titleLabel);
JLabel userLabel = new JLabel("Username: ");
userLabel.setBounds(30, 50, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(120, 50, 130, 25);
panel.add(userText);
JLabel passwordLabel = new JLabel("Password: ");
passwordLabel.setBounds(30, 80, 80, 25);
panel.add(passwordLabel);
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(120, 80, 130, 25);
panel.add(passwordText);
JButton loginButton = new JButton("login");
loginButton.setBounds(100, 125, 80, 25);
panel.add(loginButton);
ActionListener myButtonListener = new MyButtonListener();
loginButton.addActionListener(myButtonListener);
}
private static class MyButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
//can't access a new frame from here :(
}
}
}
I would be very grateful if someone could help me out, I read a lot on Stackoverflow and Reddit, but just can't find the solution. I am also new to Java, so that doesn't help a lot either :D. Thanks in advance!
P.S. As far as the actual functionality for the login screen, I am going to do that in a later stage.
This is your login class. I put the JFrame frame in the global scope, so you can manipulate it from the ButtonListener method. I also created a SomeFrame class, just to demonstrate the new JFrame that would be created when you click the button. When an action is performed(the button is clicked) a new object of SomeFrame is created. Since SomeFrame extends JFrame we can use the method setVisible() to a SomeFrame object. The SomeFrame frame appears and the LoginView is no longer visible.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginView {
public static JFrame frame = new JFrame("Bus Tour Booking System");
public static void main(String[] args) {
frame.setSize(300, 200);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel titleLabel = new JLabel("Bus Tour Booking System");
titleLabel.setBounds(70,15,150,25);
panel.add(titleLabel);
JLabel userLabel = new JLabel("Username: ");
userLabel.setBounds(30, 50, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(120, 50, 130, 25);
panel.add(userText);
JLabel passwordLabel = new JLabel("Password: ");
passwordLabel.setBounds(30, 80, 80, 25);
panel.add(passwordLabel);
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(120, 80, 130, 25);
panel.add(passwordText);
JButton loginButton = new JButton("login");
loginButton.setBounds(100, 125, 80, 25);
panel.add(loginButton);
ActionListener myButtonListener = new MyButtonListener();
loginButton.addActionListener(myButtonListener);
}
private static class MyButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
SomeFrame newFrame = new SomeFrame();
newFrame.setVisible(true);
frame.setVisible(false);
}
}
}
This is the SomeFrame class.
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SomeFrame extends JFrame {
public SomeFrame(){
super("something");
this.setSize(300, 200);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
this.add(panel);
this.setVisible(true);
}
}

Getting user input from JtextArea

public static void main(String[] args) throws IOException {
//cevir("ornek3.txt");
JFrame frame=new JFrame("Print");
JPanel input=new JPanel();
JPanel output=new JPanel(); output.setBackground(Color.black);
final JTextArea ita = new JTextArea(30, 40);
JScrollPane ijp = new JScrollPane(ita);
JTextArea ota = new JTextArea(30, 40);
JScrollPane ojp = new JScrollPane(ota);
JButton buton=new JButton("Print");
frame.setLayout(new FlowLayout());
buton.setSize(50, 20);
input.setBounds(0,0,500, 500);
output.setBounds(500, 0, 500, 450);
frame.setBounds(100, 50, 1000, 500);
input.add(ijp, BorderLayout.CENTER);
output.add(ojp, BorderLayout.EAST);
input.add(buton, BorderLayout.SOUTH);
frame.add(input);
frame.add(output);
buton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(String line: ita.getText().split("\\n"));
System.out.println(line);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
This is my code and i want to get the text that i wrote while the program running and print it to the console. Is it possible with JtextArea. This code prints null when i clicked the button to the console even if i write something to the textarea.
You have use the JtextArea#append method.
public void actionPerformed(ActionEvent e) {
for(String line: ita.getText().split("\\n"))
ota.append(line);
}
Also variables used inside the methods inner class should be final, so make ota as final
final JTextArea ota = new JTextArea(30, 40);

How to use a text area?

I m creating a GUI in java and would like to use a JTextArea, however I am having a lot of trouble adding it to the frame. How would I go about creating a text Area and then using it to read text or display text?
Here is my GUI code so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class addMemoUI extends JFrame {
JFrame frame = new JFrame();
/**
* Create the application.
*/
public addMemoUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame.getContentPane().setBackground(new Color(255, 255, 255));
frame.getContentPane().setLayout(null);
JButton button = new JButton("Create");
button.setBackground(new Color(100, 149, 237));
button.setBounds(135, 350, 130, 50);
frame.getContentPane().add(button);
JLabel lblMemos = new JLabel("MEMOS");
lblMemos.setForeground(new Color(100, 149, 237));
lblMemos.setFont(new Font("Moire", Font.BOLD, 30));
lblMemos.setBounds(22, 21, 234, 37);
frame.getContentPane().add(lblMemos);
JButton button_1 = new JButton("Cancel");
button_1.setBackground(new Color(100, 149, 237));
button_1.setBounds(5, 350, 130, 50);
frame.getContentPane().add(button_1);
frame.setBounds(100, 100, 270, 400);
frame.setUndecorated(true); //REMOVES MENU BAR
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnExit = new JButton("");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MemoUI window = new MemoUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Thanks very much :)
Here is example for how to use JTextArea. You can set, get or append text. You can find the others by google.
public class Example {
private JTextArea jtextbox;
private void initialize() {
JFrame frm = new JFrame();
:
JScrollPane scroll = new JScrollPane();
jtextbox= new JTextArea();
scroll.setViewportView(jtextbox); // add scroll panel
jtextbox.setTabSize(4);
jtextbox.setLineWrap(true);
jtextbox.setBackground(SystemColor.window);
}
private void setText(String text) {
jtextbox.append(text); // or setText(text)
}
private String getText() {
return jtextbox.getText();
}
}

Area Calculator not working and not sure why

This is the source code for my calculator that i am building in eclipse windowbuilder, i am trying to make two textFields read input and output the area for a simple rectangle, i can type the numbers into the boxes however the numbers do not compute and i am at a loss as to what i could be doing wrong, please critique my code and let me know why it isn't working. Thank you
*Edit, i have removed and changed a few things and now the Answer box displays 0.0 and nothing else
import java.awt.EventQueue;
public class GUI {
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 {
GUI window = new GUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 694, 499);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
tabbedPane.addTab("New tab", null, panel, null);
panel.setLayout(null);
JLabel lblInputBase = new JLabel("Input Base");
lblInputBase.setBounds(0, 0, 57, 39);
panel.add(lblInputBase);
textField = new JTextField();
textField.setBounds(0, 28, 86, 20);
panel.add(textField);
textField.setColumns(10);
double value = Double.parseDouble(textField.getText());
JLabel lblInputHeight = new JLabel("Input Height");
lblInputHeight.setBounds(0, 212, 68, 20);
panel.add(lblInputHeight);
textField_1 = new JTextField();
textField_1.setBounds(0, 230, 86, 20);
panel.add(textField_1);
textField_1.setColumns(10);
double value_1 = Double.parseDouble(textField_1.getText());
double Area = value*value_1;
String finalArea = Double.toString(Area);
JLabel lblArea = new JLabel("Area:");
lblArea.setBounds(244, 119, 75, 68);
panel.add(lblArea);
textField_2 = new JTextField();
textField_2.setBounds(273, 143, 86, 20);
panel.add(textField_2);
textField_2.setColumns(10);
textField_2.setEditable(false);
textField_2.setText(finalArea);
}
}
Your code is really confusing, but here are some problems that I found:
double value = Double.parseDouble(textField.getText());
This is being run before the user has any chance to even look at the gui. textField.getText() will return an empty string here, and the parseDouble method will always throw a NumberFormatException when the program is run, as it does not consider an empty string to be a valid number format.
double Area = Double.parseDouble(value)*Double.parseDouble(value_1);
Here, the variable value is already a double and does not need to be parsed, and the variable value_1 doesn't exist.
Where you meant to assign an actionListener to textField_1, you assigned a second one to textField.
Overall, it seems that all your calculation logic is being run in your initialize() method, and this means that it is only being run once. You'll want your math to be run whenever one of the text fields is updated.
Your field names are horribly confusing. Your textField variable names should give some indication of their function, like areaTextField, baseTextField, heightTextField.
Here is a modification of your code that seems to function as you intended yours to function. Note the addition of a calculate() method that is called by the action listeners that will find the area and display it, or display NaN (Not a Number) if either of the input fields are not valid numbers. All of your GUI code is retained as is, excepting the renaming of the text field variables.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
public class GUI {
private JFrame frame;
private JTextField baseTextField;
private JTextField heightTextField;
private JTextField areaTextField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 694, 499);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
tabbedPane.addTab("New tab", null, panel, null);
panel.setLayout(null);
JLabel lblInputBase = new JLabel("Input Base");
lblInputBase.setBounds(0, 0, 57, 39);
panel.add(lblInputBase);
baseTextField = new JTextField();
baseTextField.setBounds(0, 28, 86, 20);
panel.add(baseTextField);
baseTextField.setColumns(20);
baseTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
calculate();
}
});
JLabel lblInputHeight = new JLabel("Input Height");
lblInputHeight.setBounds(0, 212, 68, 20);
panel.add(lblInputHeight);
heightTextField = new JTextField();
heightTextField.setBounds(0, 230, 86, 20);
panel.add(heightTextField);
heightTextField.setColumns(20);
heightTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
calculate();
}
});
JLabel lblArea = new JLabel("Area:");
lblArea.setBounds(244, 119, 75, 68);
panel.add(lblArea);
areaTextField = new JTextField();
areaTextField.setBounds(273, 143, 86, 20);
panel.add(areaTextField);
areaTextField.setColumns(20);
areaTextField.setEditable(false);
}
private void calculate() {
try {
double base = Double.parseDouble(baseTextField.getText());
double height = Double.parseDouble(heightTextField.getText());
double area = base * height;
areaTextField.setText(String.format("%.4f", area));
} catch (NumberFormatException e) {
areaTextField.setText("NaN");
}
}
}
Note that you need to hit the enter key in one of the two fields to update the area field. That is what it takes to trigger the ActionListener for a JTextField.

Categories