I'm making a gui program everything going right but add background image in frame so i take jpanel private variable.Also i add image in src which is
but how to use this jpanel variable to add background image in frame.
Code:
public class App extends JFrame{
private JPanel panel;
private JTextField field1;
private JTextField print;
private JLabel label;
private JLabel label2;
private JButton button;
public App(){
super();
getContentPane().setLayout(null);
label = new JLabel("Value");
label.setForeground(Color.RED);
label.setFont(new Font("SansSerif", Font.PLAIN, 18));
label.setBounds(178, 46, 51, 26);
getContentPane().add(label);
label2 = new JLabel("Print");
label2.setForeground(Color.RED);
label2.setFont(new Font("SansSerif", Font.PLAIN, 18));
label2.setBounds(178, 143, 42, 26);
getContentPane().add(label2);
field1 = new JTextField();
field1.setBounds(178, 72, 76, 26);
getContentPane().add(field1);
print = new JTextField();
print.setBounds(178, 181, 77, 26);
getContentPane().add(print);
button = new JButton("Click");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String w= field1.getText();
print.setText(w);
}
});
button.setBounds(178, 219, 77, 26);
getContentPane().add(button);
}
}
Main Method:
public class Main {
public static void main(String[] args) {
App object = new App();
object.setSize(450, 400);
object.setDefaultCloseOperation(object.EXIT_ON_CLOSE);
object.setLocationRelativeTo(null);
object.setVisible(true);
}
}
You have set Layout to null which is making a problem. Whenever we make layout null we have to set bounds for it.
Folow this method:
first of all copy your background image and paste in src of code
than set layout to borderlayout like this:
setLayout(new BorderLayout());
now add this code:
setContentPane(new JLabel new ImageIcon(getClass().getResource("image.jpg"))));
Note: add your image name here "image.jpg"
Related
So I want to store a string value in a variable, the value is given through a JTextField and after a confirm button is clicked, I want it to store what's written in the text field in a string variable.
This is the relevant part of the code:
public class Window {
private JButton confirm;
private JTextField textfield;
private JLabel label;
public void drawWindow() {
JFrame window = new JFrame("CountryQuiz");
ClickChecker click = new ClickChecker();
JPanel panel = new JPanel();
panel.setBounds(40, 80, 200, 200);
panel.setBackground(Color.green);
JTextField t1 = new JTextField("Enter country...");
t1.setBounds(50, 100, 200, 30);
window.add(t1);
JButton confirm = new JButton("Confirm");
confirm.setBounds(50, 50, 95, 30);
confirm.addActionListener(click);
window.add(confirm);
window.setSize(400, 400);
window.setLayout(null);
window.setVisible(true);
window.add(panel);
}
private class ClickChecker implements ActionListener {
public void actionPerformed(ActionEvent e) {
String answer = textfield.getText();
System.out.println(answer);
}
}
}
Results in the following error:
Cannot invoke "javax.swing.JTextField.getText()" because "this.this$0.textfield" is null
Your textfield variable is only declared but never used.
Replace the below
JTextField t1 = new JTextField("Enter country...");
t1.setBounds(50, 100, 200, 30);
window.add(t1);
With
textfield = new JTextField("Enter country...");
textfield.setBounds(50, 100, 200, 30);
window.add(textfield);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
having problems with the code mentioned below. the eclipse error code is as follows ::
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at gui.PassengerGui$2.actionPerformed(PassengerGui.java:139)
Any recommendations would be very much appreciated? I have have been pulling my hair out for almost one hour trying to figure out what the problem is..
private JPanel contentPane;
private JFileChooser fileChooser;
private PassengerController controller;
private PassengerTabelPanel tabelPanel;
private JTextField nameField;
private JTextField cityField;
private JTable passengerTable;
private JRadioButton standardRadio;
private JRadioButton businessRadio;
private ButtonGroup classGroup;
private PassengerFormListener formListener;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PassengerGui frame = new PassengerGui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public PassengerGui() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 584, 368);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenuItem importDataItem = new JMenuItem("Import Data");
menuBar.add(importDataItem);
JMenuItem exportDataItem = new JMenuItem("Export Data");
menuBar.add(exportDataItem);
fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new PassengerFileFilter());
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
classGroup = new ButtonGroup();
//set up class radio
classGroup.add(standardRadio);
classGroup.add(businessRadio);
JLabel nameLabel = new JLabel("Name: ");
nameLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
nameLabel.setBounds(12, 11, 69, 31);
contentPane.add(nameLabel);
JLabel cityLabel = new JLabel("City: ");
cityLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
cityLabel.setBounds(12, 47, 69, 31);
contentPane.add(cityLabel);
JLabel lblNewLabel_2 = new JLabel("Class: ");
lblNewLabel_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblNewLabel_2.setBounds(12, 89, 69, 31);
contentPane.add(lblNewLabel_2);
nameField = new JTextField();
nameField.setBounds(60, 18, 129, 20);
contentPane.add(nameField);
nameField.setColumns(10);
cityField = new JTextField();
cityField.setColumns(10);
cityField.setBounds(60, 53, 129, 20);
contentPane.add(cityField);
JRadioButton businessRadio = new JRadioButton("Business");
businessRadio.setBounds(58, 95, 109, 23);
contentPane.add(businessRadio);
JRadioButton standardRadio = new JRadioButton("Standard");
standardRadio.setBounds(60, 127, 109, 23);
contentPane.add(standardRadio);
JButton btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String city = cityField.getText();
String passengerClass = classGroup.getSelection().getActionCommand();
PassengerFormEvent ev = new PassengerFormEvent(this, name, passengerClass, city);
You aren't instantiating ButtonGroup variable classGroup. You are using dot (.) operator on a null reference.
Do this:
ButtonGroup classGroup = new ButtonGroup();
and Somewhere in your code after this instantiation, do this:
String passengerClass = classGroup.getSelection().getActionCommand();
You are not instantiating classGroup. You need code such as:-
classGroup = new ButtonGroup();
before you can call methods on classGroup.
EDIT: In answer to the second problem, it's because the buttons you've added to the buttonGroup are also null. You need to create them before you add them.
Im developing an little "clicker" but, if i press the button, and i should get 1+ Score, it dont work! Is there any way to reload or anything else?
Heres my code: (ClickEvent)
public class event implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("PRESS");
game.timesClicked.add(1);
points.setText(game.seePoints);
}
}
And there is my JFrame:
public class game extends JFrame
{
public static JButton buttonStart;
JButton buttonCredits;
JButton buttonBack;
JButton buttonLeave;
public static JFrame panel = new game();
public static ArrayList<Integer> timesClicked = new ArrayList<Integer>();
public static JLabel label1;
public static JLabel points;
public static String seePoints = "Deine Knöpfe: " + timesClicked.size();
public game()
{
setLayout(null);
label1 = new JLabel("ButtonClicker");
points = new JLabel(seePoints);
points.setFont(new Font("Tahoma", Font.BOLD, 15));
points.setBounds(0, 0, 200, 200);
label1.setFont(new Font("Tahoma", Font.BOLD, 50));
label1.setBounds(315, 50, 500, 200);
event e1 = new event();
JButton b = new JButton("KNOPF");
b.setBackground(new Color(96, 140, 247));
b.setForeground(Color.WHITE);
b.setFocusPainted(false);
b.setFont(new Font("Tahoma", Font.BOLD, 15));
b.setBounds( 402, 380, 180, 50 );
b.addActionListener(e1);
add(b);
add(label1);
add(points);
}
}
(Sorry For My Bad English)
public static String seePoints = "Deine Knöpfe: " + timesClicked.size();
This is only being called once at the start of your program. When you add to timesClicked, it does not recalculate seePoints.
You will need to set this variable to the correct value every time you click.
This is the code. My main frame is orbital_app and I would like it to when I click on JButton (button), data is being saved, the current window closes and another window orbital_app opens.
public class signup_try {
private JFrame frame;
private JTextField txtname;
private JTextField textusername;
private JTextField txtpass;
private JTextField textmail;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
signup_try window = new signup_try();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public signup_try() {
initialize();
}
Connection connection=null;
/**
* Initialize the contents of the frame.
*/
private void initialize() {
connection=dbase.dBase();
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel label = new JLabel("Orbital");
label.setForeground(SystemColor.activeCaption);
label.setFont(new Font("Arial Black", Font.BOLD, 17));
label.setBounds(170, 11, 71, 25);
frame.getContentPane().add(label);
JLabel label_1 = new JLabel("Name:");
label_1.setForeground(SystemColor.activeCaption);
label_1.setFont(new Font("Arial Black", Font.PLAIN, 12));
label_1.setBounds(21, 66, 46, 14);
frame.getContentPane().add(label_1);
txtname = new JTextField();
txtname.setColumns(10);
txtname.setBounds(102, 63, 200, 22);
frame.getContentPane().add(txtname);
textusername = new JTextField();
textusername.setColumns(10);
textusername.setBounds(102, 108, 200, 22);
frame.getContentPane().add(textusername);
txtpass = new JTextField();
txtpass.setColumns(10);
txtpass.setBounds(102, 150, 200, 22);
frame.getContentPane().add(txtpass);
textmail = new JTextField();
textmail.setColumns(10);
textmail.setBounds(102, 192, 200, 22);
frame.getContentPane().add(textmail);
JLabel label_2 = new JLabel("Username:");
label_2.setForeground(SystemColor.activeCaption);
label_2.setFont(new Font("Arial Black", Font.PLAIN, 12));
label_2.setBounds(21, 111, 71, 14);
frame.getContentPane().add(label_2);
JLabel label_3 = new JLabel("Password:");
label_3.setForeground(SystemColor.activeCaption);
label_3.setFont(new Font("Arial Black", Font.PLAIN, 12));
label_3.setBounds(21, 154, 71, 14);
frame.getContentPane().add(label_3);
JLabel label_4 = new JLabel("Email:");
label_4.setForeground(SystemColor.activeCaption);
label_4.setFont(new Font("Arial Black", Font.PLAIN, 12));
label_4.setBounds(21, 196, 46, 14);
frame.getContentPane().add(label_4);
JButton button = new JButton("Sign Up");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query="insert into Users(Name, Username, Password, Email) values(?,?,?,?)";
PreparedStatement prepstat=connection.prepareStatement(query);
prepstat.setString(1, txtname.getText());
prepstat.setString(2, textusername.getText());
prepstat.setString(3, txtpass.getText());
prepstat.setString(4, textmail.getText());
prepstat.execute();
JOptionPane.showMessageDialog(null, "Data saved");
prepstat.close();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
I get the error saying that The method setVisible(boolean) is undefined for the type orbital_app. what should I do to fix this? Here I want to close this present frame(signup_try) and go to other frame (orbital_app).. setVisible is underlined red and says "The method setVisible(boolean) is undefined for the type orbital_app".
frame.dispose();
orbital_app orb=new orbital_app();
orb.setVisible(true);
}
});
button.setBounds(170, 239, 91, 23);
frame.getContentPane().add(button);
}
}
Orbital_app code(in this code setVisible works properly without any error):
package project;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.SystemColor;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import javax.swing.UIManager;
public class orbital_app{
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
orbital_app window = new orbital_app();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public orbital_app() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(UIManager.getColor("Button.background"));
frame.setResizable(false);
frame.setBounds(100, 100, 450, 260);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel toplbl = new JLabel("Orbital");
toplbl.setForeground(SystemColor.activeCaption);
toplbl.setFont(new Font("Arial Black", Font.BOLD, 17));
toplbl.setVerticalAlignment(SwingConstants.TOP);
toplbl.setBounds(182, 11, 71, 25);
frame.getContentPane().add(toplbl);
JLabel infolbl = new JLabel("Multipurpose app == orbital 1.0\r\n");
infolbl.setFont(new Font("Arial", Font.PLAIN, 11));
infolbl.setForeground(SystemColor.activeCaption);
infolbl.setBounds(138, 47, 165, 25);
frame.getContentPane().add(infolbl);
JButton signup_btn = new JButton("Sign Up");
signup_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.dispose();
signup_form sup_for=new signup_form();
3.setVisible works here
sup_for.setVisible(true);
}
});
signup_btn.setFont(new Font("Arial", Font.PLAIN, 11));
signup_btn.setForeground(SystemColor.activeCaption);
signup_btn.setBounds(61, 133, 91, 23);
frame.getContentPane().add(signup_btn);
JButton signin_btn = new JButton("Sign In");
signin_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.dispose();
signin_form log_for=new signin_form();
4.and here too
log_for.setVisible(true);
}
});
signin_btn.setFont(new Font("Arial", Font.PLAIN, 11));
signin_btn.setForeground(SystemColor.activeCaption);
signin_btn.setBounds(285, 133, 91, 23);
frame.getContentPane().add(signin_btn);
JLabel notelbl = new JLabel("note: click Sign Up for new account or Sign In for existing account.");
notelbl.setHorizontalAlignment(SwingConstants.CENTER);
notelbl.setBounds(10, 199, 406, 25);
frame.getContentPane().add(notelbl);
}
}
I faced the same problem, it is solved by exteding the JFrame class.
Your class should extends JFrame, because setVisible() method belongs to JFrameclass.
There seems to be a few issues with your code.
Most importantly: You have multiple entry points in your program.
You should only have one public static void main(String[] args) ... function in your application, that is where the 'program starts'.
The error message you get (The method setVisible(boolean) is undefined for the type orbital_app) comes from the fact that the class orbital_app don´t have a setVisible function, one of its members does, but that doesn't matter.
Your orbital_app have a private member that is a JFrame, which makes it possible for you to call the JFrames methods from inside the orbital_app by accessing the frame, but you cant reach it from outside.
It seems you have mixed up inheritance and ownership.
If you wish your orbital_app class to be a JFrame, you need to inherit from the JFrame. Else you could just implement the methods you wish to make public for your other classes.
Or you could just create a getter for the private JFrame object so that you can access it from outside.
So I'm starting a new project and I was wondering how can I setup multiple classes for my different JPanels. It looks very messy in one class. Let me show you the example. I would like the JPanel for a menu screen in it's own class.
import java.awt.EventQueue;
public class TakeAwayLogin {
private JFrame frmTakeAwaySystem;
private JTextField textFieldId;
private JPasswordField passwordField;
/**
* Launch the application.
* #return
*/
public void login() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TakeAwayLogin window = new TakeAwayLogin();
window.frmTakeAwaySystem.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TakeAwayLogin() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmTakeAwaySystem = new JFrame();
frmTakeAwaySystem.setTitle("Take Away System Alpha");
frmTakeAwaySystem.setBounds(100, 100, 450, 300);
frmTakeAwaySystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTakeAwaySystem.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel panelLogin = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelLogin, "name_254735117500687");
panelLogin.setLayout(null);
panelLogin.setVisible(true);
final JLabel lblIncorrect = new JLabel("Incorrect login, try again");
lblIncorrect.setHorizontalAlignment(SwingConstants.CENTER);
lblIncorrect.setFont(new Font("Tahoma", Font.PLAIN, 9));
lblIncorrect.setForeground(Color.RED);
lblIncorrect.setBounds(148, 74, 139, 14);
panelLogin.add(lblIncorrect);
lblIncorrect.setVisible(false);
final JPanel panelPassword = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelPassword, "name_254738265432897");
panelPassword.setLayout(null);
passwordField = new JPasswordField();
passwordField.setBounds(112, 157, 205, 41);
panelLogin.add(passwordField);
passwordField.setHorizontalAlignment(JPasswordField.CENTER);
JButton btnNewButton = new JButton("Lock Application");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panelPassword.setVisible(false);
panelLogin.setVisible(true);
passwordField.setText("");
textFieldId.disable();
}
});
btnNewButton.setBounds(135, 155, 172, 50);
panelPassword.add(btnNewButton);
panelPassword.setVisible(false);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String login = textFieldId.getText();
char[] pass = passwordField.getPassword();
String p = new String(pass);
String password = "pass";
if (login.equalsIgnoreCase("milan") && p.equals(password)) {
panelPassword.setVisible(true);
panelLogin.setVisible(false);
}else {
lblIncorrect.setVisible(true);
}
}
});
btnLogin.setBounds(160, 209, 97, 41);
panelLogin.add(btnLogin);
textFieldId = new JTextField();
textFieldId.setBounds(112, 88, 205, 43);
panelLogin.add(textFieldId);
textFieldId.setColumns(10);
textFieldId.setHorizontalAlignment(JTextField.CENTER);
JLabel lblId = new JLabel("Enter the business login:");
lblId.setHorizontalAlignment(SwingConstants.CENTER);
lblId.setBounds(112, 63, 205, 14);
panelLogin.add(lblId);
JLabel lblEnterYourPassword = new JLabel("Enter your password");
lblEnterYourPassword.setHorizontalAlignment(SwingConstants.CENTER);
lblEnterYourPassword.setBounds(148, 142, 139, 14);
panelLogin.add(lblEnterYourPassword);
JPanel panelPizza = new JPanel();
frmTakeAwaySystem.getContentPane().add(panelPizza, "name_254741096954780");
}
}
So help would be great.
Thanks very much.
I don't know why creating a second class would be necessary. If you just want the code to look less messy, then add comment separators between Panels or something to that effect. I think that splitting up the Panels into their own classes would be just cause you to have to write more calls to be able to create the same functionality. But if you must, then make a class within your initiate class and work from there.
Simplifying, you want something like:
public class MyMainJFrame extends JFrame{
private JPanel panel1 = new MyFooPanel();
private JPanel panel2 = new MyBarPanel();
public MyMainPanel(){
initialize();
}
void initialize(){
//init the JFrame
this.setTitle("Take Away System Alpha");
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new CardLayout(0, 0));
//and add the panels
this.add(panel1);
this.add(panel2);
}
}
// a file for each one
public class MyFooPanel extends JPanel{
private JButton button;
//... add components and logic
}
public class MyBarPanel extends JPanel{
private JTextField field;
//... add components and logic
}
If you want to use specific methods for each custom panel, then change the type of variable for the same name of the custom class.