Making a second frame in Java swing - java

I have made a simple digital business card in Java swing using Eclipse, I am brand new to Java and programming in general so please bear with me. Basically what I want to do is add a button that says "Our Work" or "Portfolio" for example, which when clicked will open a new window where I can then add pictures or links or false reviews etc.
I know this is probably quite simple, but I struggle to understand a lot of tutorials when it is based on other peoples code.
package dbuscard;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.awt.Font;
import javax.swing.JSeparator;
public class card {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
card window = new card();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public card() {
initialize();
}
/**
* Initialise the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(new Color(153, 204, 255));
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblLogo = new JLabel("");
lblLogo.setBounds(127, 11, 219, 104);
frame.getContentPane().add(lblLogo);
lblLogo.setIcon(new ImageIcon("Images\\zlogoimg.png"));
JLabel lblNewLabel = new JLabel("t: 01254 777494");
lblNewLabel.setFont(new Font("Source Code Pro Light", Font.PLAIN, 11));
lblNewLabel.setBounds(20, 187, 126, 14);
frame.getContentPane().add(lblNewLabel);
JLabel lblEApexuxdesigngmailcom = new JLabel("e: apexuxdesign#gmail.com");
lblEApexuxdesigngmailcom.setFont(new Font("Source Code Pro Light", Font.PLAIN, 11));
lblEApexuxdesigngmailcom.setBounds(20, 204, 200, 14);
frame.getContentPane().add(lblEApexuxdesigngmailcom);
JLabel lblVisitWebsite = new JLabel("visit website");
lblVisitWebsite.setFont(new Font("Source Code Pro Light", Font.BOLD, 11));
lblVisitWebsite.setBounds(10, 237, 117, 14);
frame.getContentPane().add(lblVisitWebsite);
JLabel facebook = new JLabel("");
facebook.setBounds(282, 204, 64, 47);
frame.getContentPane().add(facebook);
facebook.setIcon(new ImageIcon("Images\\facebook.png"));
JLabel twitter = new JLabel("");
twitter.setBounds(320, 204, 72, 47);
frame.getContentPane().add(twitter);
twitter.setIcon(new ImageIcon("Images\\twitter.png"));
JLabel youtube = new JLabel("");
youtube.setBounds(356, 204, 68, 47);
frame.getContentPane().add(youtube);
youtube.setIcon(new ImageIcon("Images\\youtube.png"));
JLabel lblSeanHutchinson = new JLabel("Sean Hutchinson");
lblSeanHutchinson.setFont(new Font("Source Code Pro Light", Font.PLAIN, 11));
lblSeanHutchinson.setBounds(20, 128, 126, 14);
frame.getContentPane().add(lblSeanHutchinson);
JLabel lblUxDesigner = new JLabel("UX Designer");
lblUxDesigner.setFont(new Font("Source Code Pro Light", Font.PLAIN, 11));
lblUxDesigner.setBounds(20, 145, 107, 14);
frame.getContentPane().add(lblUxDesigner);
JLabel lblNewLabel_1 = new JLabel("CEO - Apex UX Design");
lblNewLabel_1.setFont(new Font("Source Code Pro Light", Font.PLAIN, 11));
lblNewLabel_1.setBounds(20, 162, 158, 14);
frame.getContentPane().add(lblNewLabel_1);
}
}

Simple. Add an action listener which uses the method setVisible(true); on a seperate JFrame. Example code:
package com.nonsense;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class del {
private JFrame frame, frame2;
/**
* Launch the application.
*/
public static void main(String[] args) {
del window = new del();
window.frame.setVisible(true);
}
/**
* Create the application.
*/
public del() {
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);
frame2 = new JFrame();
frame2.setBounds(100, 100, 450, 300);
frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame2.getContentPane().setLayout(null);
JButton btnOpenWindow = new JButton("Open Window");
btnOpenWindow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame2.setVisible(true);
}
});
btnOpenWindow.setBounds(167, 118, 120, 23);
frame.getContentPane().add(btnOpenWindow);
}
}
I use "DISPOSE_ON_CLOSE" so that the second window does not terminate the program when the X button is pressed.

Related

When creating an Object of my Gui in another class the frame loads but nothing appears inside

I've made the initialize method public, didn't help and I've set visible to true both here and the external class as seen below, any help would be appreciated. I created the gui using the window builder tool from eclipse
GeneralWindow frame = new GeneralWindow();
frame.setVisible(true);
package gui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import java.awt.Font;
public class GeneralWindow extends JFrame{
private JFrame frame;
private JTextField textField;
/**
* Launch the application.
*/
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.
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GeneralWindow window = new GeneralWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GeneralWindow() {
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("Order");
btnNewButton.setBounds(309, 12, 115, 23);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("Search");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_1.setBounds(309, 46, 115, 23);
frame.getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Stock");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnNewButton_2.setBounds(309, 80, 115, 23);
frame.getContentPane().add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("Emplyoees");
btnNewButton_3.setBounds(309, 114, 115, 23);
frame.getContentPane().add(btnNewButton_3);
JButton btnNewButton_4 = new JButton("Price Amend");
btnNewButton_4.setBounds(309, 148, 115, 23);
frame.getContentPane().add(btnNewButton_4);
JButton btnNewButton_5 = new JButton("Total");
btnNewButton_5.setBounds(309, 182, 115, 23);
frame.getContentPane().add(btnNewButton_5);
textField = new JTextField();
textField.setBounds(10, 228, 178, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblProductcodeBar = new JLabel("Productcode Bar");
lblProductcodeBar.setFont(new Font("Tahoma", Font.BOLD, 11));
lblProductcodeBar.setBounds(10, 209, 125, 14);
frame.getContentPane().add(lblProductcodeBar);
JButton btnEnter = new JButton("Enter");
btnEnter.setBounds(198, 227, 89, 23);
frame.getContentPane().add(btnEnter);
JTextArea textArea = new JTextArea();
textArea.setBounds(10, 11, 277, 196);
frame.getContentPane().add(textArea);
}
}
You're making the frame frame, of type GeneralWindow, visible. But you never add any component to that frame. Instead, your initialize method creates yet another frame, and adds many components to that frame. Don't create another frame, and add the components to this, instead.
In Your initialize() just change the frame to this keyword
e.g
//Remove this line
frame = new JFrame();
//change frame to this keyword
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
That its u r done...
Whilst the two answers provide here give a correct solution, they both reinforce the view that you should extend JFrame. This is not good advice in general, as you should favour composition over inheritance. Indeed the way you were writing the code to include a JFrame as a private member was the correct instinct.
I've included a stripped down version of your code that doesn't extend JFrame Instead it creates an instance of the JFrame when you call the createAndDisplayFrame() method.
public class GeneralWindow {
private JFrame frame;
private JButton orderButton;
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
GeneralWindow window = new GeneralWindow();
window.crateAndDisplayFrame();
}
});
}
public void crateAndDisplayFrame() {
initialize();
frame.setVisible(true);
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
orderButton = new JButton("Order");
orderButton.setBounds(309, 12, 115, 23);
frame.getContentPane().add(orderButton);
}
}

How to open new window after JProgressBar is completed

I created FlashScreen.java as loading screen consist of JProgressBar.
I want that after progressbar percentage is completed current window should be closed and new window should be open.
I made it but after closing first window in next window there is no component in window. Empty window is opening.
Here is code:
FlashScreen.java
package crimeManagement;
import javax.swing.*;
import java.awt.Rectangle;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class FlashScreen extends JFrame{
JProgressBar jb;
JLabel lblStat;
int i=0,num=0;
FlashScreen(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setBounds(new Rectangle(400, 200, 0, 0));
jb=new JProgressBar(0,2000);
jb.setBounds(100,219,579,22);
jb.setValue(0);
jb.setStringPainted(true);
getContentPane().add(jb);
setSize(804,405);
getContentPane().setLayout(null);
lblStat = new JLabel("");
lblStat.setForeground(Color.CYAN);
lblStat.setHorizontalAlignment(SwingConstants.CENTER);
lblStat.setHorizontalTextPosition(SwingConstants.CENTER);
lblStat.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 18));
lblStat.setBounds(229, 252, 329, 14);
getContentPane().add(lblStat);
JLabel lblBackGround = new JLabel("");
lblBackGround.setHorizontalTextPosition(SwingConstants.CENTER);
lblBackGround.setHorizontalAlignment(SwingConstants.CENTER);
lblBackGround.setIcon(new ImageIcon(FlashScreen.class.getResource("/Images/FlashImage.jpg")));
lblBackGround.setBounds(0, 0, 798, 376);
getContentPane().add(lblBackGround);
}
public void iterate(){
while(i<=2000){
jb.setValue(i);
i=i+20;
try{
Thread.sleep(50);
if(i==20)
{
lblStat.setText("Loading...");
}
if(i==500)
{
lblStat.setText("Please Wait...");
}
if(i==1000)
{
Thread.sleep(100);
lblStat.setText("Loading Police Station Management System...");
}
if(i==1200)
{
lblStat.setText("Please Wait...");
}
if(i==1600)
{
lblStat.setText("Almost Done...");
}
if(i==1980)
{
lblStat.setText("Done");
}
if(i==2000)
{
this.dispose();
LoginPage lp=new LoginPage();
lp.setVisible(true);
}
}
catch(Exception e){}
}
}
public static void main(String[] args) {
FlashScreen fs=new FlashScreen();
fs.setVisible(true);
fs.iterate();
}
}
**LoginPage.java**
package crimeManagement;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.border.*;
public class LoginPage extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frame;
private JTextField txtUserName;
private JPasswordField txtPass;
public static void main(String[] args) {
LoginPage window = new LoginPage();
window.frame.setVisible(true);
}
public LoginPage() {
frame = new JFrame();
frame.setResizable(false);
frame.getContentPane().setBackground(SystemColor.inactiveCaption);
frame.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 16));
frame.setBounds(100, 100, 554, 410);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblLoginType = new JLabel("Login Type");
lblLoginType.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblLoginType.setBounds(97, 53, 99, 20);
frame.getContentPane().add(lblLoginType);
JLabel lblUsename = new JLabel("User Name");
lblUsename.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblUsename.setBounds(97, 177, 99, 26);
frame.getContentPane().add(lblUsename);
JLabel lblPaaword = new JLabel("Password");
lblPaaword.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblPaaword.setBounds(97, 223, 99, 26);
frame.getContentPane().add(lblPaaword);
JPanel panel = new JPanel();
FlowLayout flowLayout = (FlowLayout) panel.getLayout();
panel.setBackground(SystemColor.inactiveCaptionBorder);
panel.setBounds(210, 47, 143, 93);
frame.getContentPane().add(panel);
TitledBorder tb=new TitledBorder( "Login");
tb.setTitleJustification(TitledBorder.CENTER);
tb.setTitlePosition(TitledBorder.CENTER);
panel.setBorder(BorderFactory.createTitledBorder(tb));
JRadioButton rdbAdmin = new JRadioButton("Admin");
rdbAdmin.setBackground(SystemColor.inactiveCaption);
rdbAdmin.setFont(new Font("Tahoma", Font.PLAIN, 13));
rdbAdmin.setSelected(true);
panel.add(rdbAdmin);
JRadioButton rdbOthers = new JRadioButton("Others");
rdbOthers.setBackground(SystemColor.inactiveCaption);
rdbOthers.setFont(new Font("Tahoma", Font.PLAIN, 13));
panel.add(rdbOthers);
txtUserName = new JTextField();
txtUserName.setBackground(UIManager.getColor("TextField.background"));
txtUserName.setBounds(210, 177, 158, 26);
frame.getContentPane().add(txtUserName);
txtUserName.setColumns(30);
JButton btnLogin = new JButton("Login");
btnLogin.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnLogin.setBounds(210, 286, 71, 23);
frame.getContentPane().add(btnLogin);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnExit.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnExit.setBounds(297, 286, 71, 23);
frame.getContentPane().add(btnExit);
txtPass = new JPasswordField();
txtPass.setBounds(210, 226, 158, 26);
frame.getContentPane().add(txtPass);
}
}
You're displaying the wrong JFrame. Yes the LoginPage extends JFrame, and yes you display it, but you add no components to it, and instead add all components to a private JFrame field of the class named, frame.
A quick solution is to change your LoginPage class so that it doesn't extend JFrame and then give this class a public getFrame() method:
public JFrame getFrame() {
return frame;
}
and when wanting to show it, call
this.dispose();
LoginPage lp = new LoginPage();
// lp.setVisible(true);
lp.getFrame().setVisible(true);
but having said this, there are still some serious threading issues with your code that you'll eventually want to fix, including trying to avoid calling Thread.sleep() in code that risks being called on the Swing event thread.
Also please check out The Use of Multiple JFrames: Good or Bad Practice? to see why it is often a bad practice to display a bunch of JFrames in your app, and ways around this.
Other issues include use of null layouts. Yes they may seem like an easy way to create complex GUI's quickly -- until you try to show the GUI on another platform and find that they don't look so nice, or have to enhance, debug or change it, and find it very tricky and easy to mess up. Much better to use layout managers.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class FlashScreenTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame mainFrame = new JFrame("Main App");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new MainAppPanel());
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
FlashScreenPanel dialogPanel = new FlashScreenPanel();
JDialog dialog = new JDialog(mainFrame, "Flash Screen", ModalityType.APPLICATION_MODAL);
dialog.add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialogPanel.startProgress();
dialog.setVisible(true);
mainFrame.setVisible(true);
});
}
}
class FlashScreenPanel extends JPanel {
public static final String LOADING = "Loading...";
public static final String PLEASE_WAIT = "Please Wait...";
public static final String LOADING_POLICE_STATION = "Loading Police Station...";
public static final String ALMOST_DONE = "Almost Done...";
public static final String DONE = "Done";
private static final int TIMER_DELAY = 50;
private JProgressBar jb = new JProgressBar(0, 2000);
private JLabel statusLabel = new JLabel("", SwingConstants.CENTER);
public FlashScreenPanel() {
setPreferredSize(new Dimension(800, 400));
statusLabel.setForeground(Color.CYAN);
statusLabel.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 18));
jb.setStringPainted(true);
JPanel bottomPanel = new JPanel(new BorderLayout(20, 20));
bottomPanel.add(jb, BorderLayout.PAGE_START);
bottomPanel.add(statusLabel, BorderLayout.CENTER);
int eb = 40;
setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
setLayout(new GridLayout(0, 1));
add(new JLabel()); // dummy component to move prog bar lower
add(bottomPanel);
}
public void startProgress() {
statusLabel.setText(LOADING);
new Timer(TIMER_DELAY, new ActionListener() {
private int i = 0;
#Override
public void actionPerformed(ActionEvent e) {
i += 20;
jb.setValue(i);
if (i == 500) {
statusLabel.setText(PLEASE_WAIT);
} else
if (i == 1000) {
statusLabel.setText(LOADING_POLICE_STATION);
} else
if (i == 1200) {
statusLabel.setText(PLEASE_WAIT);
} else
if (i == 1600) {
statusLabel.setText(ALMOST_DONE);
} else
if (i == 1980) {
statusLabel.setText(DONE);
} else
if (i == 2000) {
((Timer) e.getSource()).stop();
Window win = SwingUtilities.getWindowAncestor(FlashScreenPanel.this);
win.dispose();
}
}
}).start();
}
}
class MainAppPanel extends JPanel {
public MainAppPanel() {
setPreferredSize(new Dimension(600, 400));
}
}

The method setVisible(boolean) is undefined for the type orbital_app

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.

Why isn't my JScrollPane working?

I'm trying to make my JPanel scrollable but it's not working. I made a JPanel, added components to it, then added my JPanel to a JScrollPane. This is what you're supposed to do, right? What am I doing wrong?
import java.awt.Dimension;
import java.awt.Font;
import java.awt.SystemColor;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneLayout;
import javax.swing.SwingConstants;
public class RegisterPane extends JPanel {
private JTextField txtJohnDoe;
private JTextField txtExampledomaincom;
private JPasswordField passwordField;
private JPasswordField passwordField_1;
/**
* Create the panel.
*/
public RegisterPane() {
setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(6, 36, 300, 450);
panel.setLayout(null);
JLabel lblFirstName = new JLabel("First Name");
lblFirstName.setBounds(28, 6, 92, 16);
panel.add(lblFirstName);
txtJohnDoe = new JTextField();
txtJohnDoe.setText("John Doe");
txtJohnDoe.setBounds(124, 0, 251, 28);
panel.add(txtJohnDoe);
txtJohnDoe.setColumns(10);
txtExampledomaincom = new JTextField();
txtExampledomaincom.setText("Example#domain.com");
txtExampledomaincom.setColumns(10);
txtExampledomaincom.setBounds(124, 40, 251, 28);
panel.add(txtExampledomaincom);
JLabel lblEmail = new JLabel("Email");
lblEmail.setBounds(28, 46, 92, 16);
panel.add(lblEmail);
JLabel lblGender = new JLabel("Gender");
lblGender.setBounds(28, 89, 55, 16);
panel.add(lblGender);
JRadioButton rdbtnMale = new JRadioButton("Male");
rdbtnMale.setBounds(124, 85, 92, 23);
panel.add(rdbtnMale);
JRadioButton rdbtnFemale = new JRadioButton("Female");
rdbtnFemale.setBounds(283, 85, 92, 23);
panel.add(rdbtnFemale);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(28, 157, 55, 16);
panel.add(lblPassword);
JLabel passDirections = new JLabel();
passDirections.setHorizontalAlignment(SwingConstants.CENTER);
passDirections.setFont(new Font("Lucida Grande", Font.PLAIN, 10));
passDirections.setBackground(SystemColor.window);
passDirections.setText("Password's Must be at Least 6 characters long and contain 1 non letter character");
passDirections.setBounds(29, 117, 346, 28);
panel.add(passDirections);
passwordField = new JPasswordField();
passwordField.setBounds(124, 151, 251, 28);
panel.add(passwordField);
passwordField_1 = new JPasswordField();
passwordField_1.setBounds(124, 195, 251, 28);
panel.add(passwordField_1);
JLabel lblRetypePassword = new JLabel("Password Again");
lblRetypePassword.setBounds(28, 201, 92, 16);
panel.add(lblRetypePassword);
JCheckBox chckbxSubscribeToNews = new JCheckBox("Subscribe to News Letter");
chckbxSubscribeToNews.setSelected(true);
chckbxSubscribeToNews.setHorizontalAlignment(SwingConstants.CENTER);
chckbxSubscribeToNews.setBounds(29, 244, 346, 23);
panel.add(chckbxSubscribeToNews);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(28, 280, 55, 16);
panel.add(lblNewLabel);
JScrollPane scroll = new JScrollPane(panel);
scroll.setSize(new Dimension(450,300));
panel.setAutoscrolls(true);
add(scroll);
}
}
Here's my JFrame class
import java.awt.BorderLayout;
public class MainFrame extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(0, 0));
setResizable(false);
setContentPane(new RegisterPane());
//RegisterPane isn't scrolling ^
}
}
Thanks in Advance for your help!
I'm seeing setLayout(null) alot in your code.
The JViewport uses the component's/view's preferred size as a bases for determining if the view expands beyond the visible bounds of the JScrollPane, because you've seen fit to ignore this feature, the components have begun to break down.
Swing is designed to work layout managers and it makes it much easier to develop complex user interfaces that can work across a multitude of platforms and environments

How do I remove a component from a JPanel? and then redisplay the frame?

Some context for this code,
what I am trying to do is create a validation warning if the input containts "" as a value,
so if an error is displayed it displays the message.
If it is valid it does not display a message,
so how do I remove the message when the textField is valid?
The message is a JPanel that contains a JLabel with the text in it,
I add this this JPanel to the frame when it is not valid,
and I am trying to remove it when it is valid.
So what am I doing wrong here?
I am at a basic level with Swing.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Test {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
/**
* 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, 401, 232);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 330, 94);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Firstname :");
lblNewLabel.setBounds(10, 11, 104, 14);
panel.add(lblNewLabel);
textField = new JTextField();
textField.setBounds(76, 8, 244, 20);
panel.add(textField);
textField.setColumns(10);
JLabel lblLastname = new JLabel("Lastname :");
lblLastname.setBounds(10, 42, 78, 14);
panel.add(lblLastname);
textField_1 = new JTextField();
textField_1.setBounds(76, 39, 244, 20);
panel.add(textField_1);
textField_1.setColumns(10);
JButton btnValidate = new JButton("Validate");
btnValidate.addMouseListener(new MouseAdapter() {
#SuppressWarnings("deprecation")
#Override
public void mousePressed(MouseEvent arg0) {
JPanel panel_1 = new JPanel();
JPanel panel_2 = new JPanel();
if(textField.getText().equals("")) {
panel_1.setBackground(new Color(30, 144, 255));
panel_1.setBounds(100, 116, 330, 26);
JLabel lblMessage = new JLabel("0 :");
lblMessage.setForeground(new Color(255, 255, 255));
lblMessage.setFont(new Font("Tahoma", Font.BOLD, 13));
panel_1.add(lblMessage);
frame.getContentPane().add(panel_1);
frame.revalidate();
frame.repaint(10);
frame.revalidate();
}
else if(textField_1.getText().equals("")) {
panel_2.setBackground(new Color(50, 200, 255));
panel_2.setBounds(10, 134, 330, 26);
JLabel lblMessage = new JLabel("1 :");
lblMessage.setBounds(50, 50, 50, 50);
lblMessage.setAlignmentX(50);
lblMessage.setForeground(new Color(255, 255, 255));
lblMessage.setFont(new Font("Tahoma", Font.BOLD, 13));
panel_2.add(lblMessage);
frame.getContentPane().add(panel_2);
frame.remove(panel_1);
frame.revalidate();
frame.repaint(10);
frame.revalidate();
}
}
});
btnValidate.setBounds(231, 71, 89, 23);
panel.add(btnValidate);
}
}
The easiest way is to simply adjust the visibility (JComponent#setVisible( false ) ).
If you really want to remove the component completely, you have to remove and revalidate, as documented in the Container#remove method
This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to reflect the changes.
which results in code like
panel.remove( componentToRemove );
panel.revalidate();
panel.repaint();
As a side note: please replace the null layout and those setBounds call by a proper LayoutManager. You might want to take a look excellent 'Nested layout example' available on SO to see what is possible with layout managers. The Swing tag info on SO contains some extra useful links when starting to work with layout managers
yourpanel.setVisible(false); should hide your panel, where "yourPanel" is your JPanel instance

Categories

Resources