not showing message diologe with JOptione pane - java

i have written a code to create a sms form and i want to add the ability to show error message when the text area is empty. i put JOptionpane in my code but diologe dose not appear when i run the program! here is my code
private void initialize() {
frame = new JFrame("?????? ? ????? ?????");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JOptionPane optionPane = new JOptionPane();
JPanel middlePanel = new JPanel();
txtPath = new JTextField();
txtPath.setBounds(150, 10, 200, 21);
frame.getContentPane().add(txtPath);
txtPath.setColumns(10);
txtPath2 = new JTextField();
txtPath2.setBounds(150, 65, 200, 21);
frame.getContentPane().add(txtPath2);
txtPath2.setColumns(20);
JButton btnBrowse = new JButton("?????");
btnBrowse.setBounds(5, 10, 87, 23);
frame.getContentPane().add(btnBrowse);
final JButton ok = new JButton("?????");
ok.setBounds(250, 230, 87, 23);
frame.getContentPane().add(ok);
JButton cancel = new JButton("???");
cancel.setBounds(110, 230, 87, 23);
frame.getContentPane().add(cancel);
final JTextArea textarea = new JTextArea();
textarea.setBounds(50, 100, 300, 100);
frame.getContentPane().add(textarea);
textarea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JProgressBar progressBar = new JProgressBar(0, 100);
progressBar.setSize(10, 1);
progressBar.setForeground(Color.blue);
frame.getContentPane().add(progressBar);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
// For Directory
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
// For File
//fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
int rVal = fileChooser.showOpenDialog(null);
if (rVal == JFileChooser.APPROVE_OPTION) {
txtPath.setText(fileChooser.getSelectedFile().toString());
fileChooser.setFileFilter(new FileNameExtensionFilter("Text Files", "txt", "rtf"));
}
}
});
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textarea.getLineCount()>=1)
{
test t=new test();
ReadTextFile readTextFile=new ReadTextFile();
t.testMethode(txtPath2.getText(), textarea.getText(),readTextFile.readFile(txtPath.getText()) );
}
else
JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
}
});
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
}
}

GUI's are event driven environments. Something happens, you respond to it.
You if-else statement will never be false because the time it is executed, the textarea will be blank (have no text).
You need to respond to some event (ie send for example) at which time you would make your check to valid the form.
Take a look at Creating a GUI with Swing for more details
Updated with example
public class Example {
public static void main(String[] args) {
new Example();
}
public Example() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private final JTextArea msg;
public TestPane() {
msg = new JTextArea(10, 20);
JButton send = new JButton("Send");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(new JScrollPane(msg), gbc);
add(send, gbc);
send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (msg.getText().trim().length() > 0) {
// Send msg
} else {
JOptionPane.showMessageDialog(TestPane.this, "Please write something (nice)", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
}
}
}
Updated based on changes to the answer by the OP
if(textarea.getLineCount()>=1) will always return true. Try using msg.getText().trim().length() > 0 instead to determine the JTextArea contains text or not...
Updated
mKobel has made an excellent point. You really should avoid using null layouts. You don't control what font size or screen DPI/resolution your application might need to work on. Layout managers take out the guess work.
You should try checking out A visual guide to layout managers and Using layout managers for more details

Related

Scroll Bar does not adjust to JPanel dimensions, Java JScrollPane

I am trying to get a scroll bar for a Panel that will get a big number of lines, however I am stuck whit this.
As you can see in my window (click here to open the picture), Scroll bars does not adjust to the panel's dimensions
Below you can see the code i am working with:
public class Config extends JFrame {
private static JPanel contentPane;
private static JScrollPane paneSiteScroll;
private static JPanel paneSite;
private JTextField txtURL;
private JButton btnAdd;
private JLabel lblName;
private JTextField txtName;
private JPanel paneBar;
/**
* Launch the application.
*/
public static void config() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Config frame = new Config();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws Throwable
*/
public Config() throws Throwable {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 550);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
//Start top Add Bar
paneBar = new JPanel();
paneBar.setBounds(0, 0, 700, 35);
contentPane.add(paneBar);
paneBar.setLayout(null);
JButton btnBack = new JButton("Back");
btnBack.setBounds(1, 3, 65, 28);
paneBar.add(btnBack);
btnBack.setVerticalAlignment(SwingConstants.TOP);
JLabel lblUrl = new JLabel("URL:");
lblUrl.setBounds(80, 9, 35, 20);
paneBar.add(lblUrl);
txtURL = new JTextField();
txtURL.setBounds(115, 5, 310, 26);
paneBar.add(txtURL);
txtURL.setColumns(10);
lblName = new JLabel("Name:");
lblName.setBounds(435, 9, 47, 20);
paneBar.add(lblName);
txtName = new JTextField();
txtName.setBounds(480, 5, 155, 26);
paneBar.add(txtName);
txtName.setColumns(10);
btnAdd = new JButton("Add");
btnAdd.setBounds(635, 3, 61, 29);
paneBar.add(btnAdd);
//End top Add Bar
//Start Scroll and Panel configuration
paneSiteScroll = new JScrollPane();
paneSite = new JPanel();
paneSite.setLayout(null);
paneSite.setBounds(10, 40, 400, 600);
/*Testing different dimensions configuration*/
paneSiteScroll.setSize(new Dimension(300, 300));
paneSiteScroll.setBounds(10, 40, 300, 200);
paneSiteScroll.setPreferredSize(new Dimension(400, 300));
/*Testing different dimensions configuration*/
paneSiteScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
paneSiteScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
paneSiteScroll.getViewport().add(paneSite);
contentPane.add(paneSiteScroll);
paneSiteScroll.setVisible(true);
paneSite.setVisible(true);
//End Scroll and Panel configuration
try {
Categories.categories(paneSite); //GET CATEGORIES
} catch (Throwable e) {
e.printStackTrace();
}
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!txtURL.getText().isEmpty() || !txtName.getText().isEmpty()) {
InsertDB insert = new InsertDB();
try {
insert.insertDB("INSERT INTO sites (siUrl, siName) VALUES ('" + txtURL.getText() +"'"
+ ", '" + txtName.getText() + "')",
conn);
} catch (Exception e1) {
e1.printStackTrace();
}
}
else {
JOptionPane.showMessageDialog(null, "URL or Name cannot be empty!");
}
}
});
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Back action button
dispose();
}
});
}
}
This is my first question, I do not know what else to add, also i visited many question from stak overflow with similar problems but i couldn't figure it out.
Thanks in advance.
Finally fixed it, I restored the layout to null and added paneSite.setPreferredSize(new Dimension(600, 600)); after paneSite.setbounds. This make it work.

JButton not responsive - have to click twice

I created a GUI using java swing and in a specific situation, the JButton is unresponsive and I have to click it twice. On the click, it takes the info in the textArea and sends it to a TextParser class to be parsed. If I type more stuff in the area after, and click the evaluateButton, it doesn't respond and I have to click it again to work. Does anyone know if this is a known bug or how I can fix this?
The code for the class is as follows.
/**
* Add the components to the GUI.
* #param pane - the pane for the GUI
*/
public static void addComponentsToPane(Container pane) {
pane.setLayout(new BorderLayout());
JPanel instructionsPanel = new JPanel();
JLabel instructions = new JLabel("Enter the email text below");
instructionsPanel.setBackground(Color.LIGHT_GRAY);
instructionsPanel.add(instructions);
pane.add(instructionsPanel, BorderLayout.NORTH);
JPanel textAreaPanel = new JPanel();
textAreaPanel.setBackground(Color.LIGHT_GRAY);
final JTextArea textArea = new JTextArea();
textArea.setBackground(Color.WHITE);
textArea.setMinimumSize(new Dimension(400,350));
textArea.setMaximumSize(new Dimension(400,350));
textArea.setPreferredSize(new Dimension(400,350));
textArea.setLineWrap(true);
Border border = BorderFactory.createLineBorder(Color.BLACK);
textArea.setBorder(border);
textArea.setMinimumSize(new Dimension(500, 200));
textArea.setFont(new Font("Serif", Font.PLAIN, 16));
textAreaPanel.add(textArea);
pane.add(textAreaPanel, BorderLayout.CENTER);
JPanel scoringPanel = new JPanel();
JButton evaluateButton = new JButton("Evaluate Email");
final JLabel scoreLabel = new JLabel("");
JButton uploadFileBtn = new JButton("Upload File");
JButton importTermsBtn = new JButton("Import Terms");
scoringPanel.add(evaluateButton);
scoringPanel.add(uploadFileBtn);
scoringPanel.add(importTermsBtn);
scoringPanel.add(scoreLabel);
pane.add(scoringPanel, BorderLayout.SOUTH);
evaluateButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
String email = textArea.getText();
TextParser textParser = new TextParser(email);
double score = textParser.parse();
scoreLabel.setText(score+"");
} catch (Exception ex) {
System.out.println(ex);
}
}
});
uploadFileBtn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
scoreLabel.setText("Feature not yet available.");
}
});
importTermsBtn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
DatabaseInput d = new DatabaseInput();
d.main(null);
}
});
}
/**
* Create the GUI and show it.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("EmailGUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setLocationRelativeTo(null);
frame.setPreferredSize(new Dimension(500,500));
frame.setTitle("Email Text Input");
frame.setResizable(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(screenSize.width, screenSize.height);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
My main method just calls createAndShowGUI(). I am new to StackOverflow so if I need to give more or less information in my post please let me know!
As Reimeus and Jason C said in the comments, I should have been using ActionListener which works perfectly.

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);

Enable/Disable buttons on main frame from jInternalFrame in Eclipse

As I said in the title, I am writing a code for a small program in java. I used Internal Frames to implement it. The thing is I am trying to add a login option to the program. The login class is a jInternalFrame and I want it to Enable/Disable specific buttons in my main window. I tried google-ing a solution but didn't seem to find it. (Keep in mind that I'm really new to programing so I expect there might be other problems in my code I don't see at the moment).
Main Window code:
import javax.swing.JDesktopPane;
public class FereastraPrincipala extends JFrame {
private static final long serialVersionUID = 1L;
JDesktopPane jdpDesktop;
static int openFrameCount = 0;
public FereastraPrincipala() {
super("Fereastra Principala");
// Make the main window positioned as 50 pixels from each edge of the
// screen.
int inset = 50;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(inset, inset, screenSize.width - inset * 2,screenSize.height - inset * 2);
// Add a Window Exit Listener
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Create and Set up the GUI.
jdpDesktop = new JDesktopPane();
// A specialized layered pane to be used with JInternalFrames
setContentPane(jdpDesktop);
setJMenuBar(createMenuBar());
// Make dragging faster by setting drag mode to Outline
jdpDesktop.putClientProperty("JDesktopPane.dragMode", "outline");
}
private JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu mnFile = new JMenu("File");
mnFile.setMnemonic(KeyEvent.VK_F);
JMenuItem mntmLogin = new JMenuItem("Login");
mnFile.add(mntmLogin);
mntmLogin.setMnemonic(KeyEvent.VK_N);
menuBar.add(mnFile);
mntmLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
login();
}
});
JMenuItem mntmLogout = new JMenuItem("Logout");
mnFile.add(mntmLogout);
mntmLogout.setEnabled(true);
JMenuItem mntmCreazaUser = new JMenuItem("Creaza User");
mntmCreazaUser.setMnemonic(KeyEvent.VK_C);
mnFile.add(mntmCreazaUser);
mntmCreazaUser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
creazaUser();
}
});
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.setMnemonic(KeyEvent.VK_X);
mnFile.add(mntmExit);
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JMenu mnAdministrator = new JMenu("Administrator");
mnAdministrator.setMnemonic(KeyEvent.VK_N);
menuBar.add(mnAdministrator);
mnAdministrator.setEnabled(true);
JMenu mnPresedinte = new JMenu("Presedinte");
mnPresedinte.setMnemonic(KeyEvent.VK_P);
menuBar.add(mnPresedinte);
mnPresedinte.setEnabled(true);
JMenuItem mnHelp = new JMenuItem("Help");
mnHelp.setMnemonic(KeyEvent.VK_H);
menuBar.add(mnHelp);
mnHelp.setEnabled(true);
mnHelp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
help();
}
});
return menuBar;
}
protected void login() {
Login frame = new Login();
frame.setVisible(true);
// Every JInternalFrame must be added to content pane using JDesktopPane
jdpDesktop.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
protected void help() {
Help frame1 = new Help();
frame1.setVisible(true);
jdpDesktop.add(frame1);
try {
frame1.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
protected void creazaUser() {
CreazaUser frame = new CreazaUser();
frame.setVisible(true);
jdpDesktop.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
FereastraPrincipala frame = new FereastraPrincipala();
frame.setVisible(true);
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
}
Login class code:
import java.awt.EventQueue;
public class Login extends JInternalFrame {
private static Login instance = null;
private JTextField textField;
private JPasswordField passwordField;
public static Login getInstance(){
if(instance == null) {instance = new Login(); }
return instance;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login frame = new Login();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Login() {
super("Login", false, true, false, false);
setVisible(true);
setBounds(200, 200, 290, 173);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Username:");
lblNewLabel.setBounds(22, 29, 79, 14);
panel.add(lblNewLabel);
JLabel label = new JLabel("Parola:");
label.setBounds(22, 54, 79, 14);
panel.add(label);
textField = new JTextField();
textField.setColumns(10);
textField.setBounds(123, 26, 98, 20);
panel.add(textField);
passwordField = new JPasswordField();
passwordField.setBounds(123, 51, 98, 20);
panel.add(passwordField);
JButton button = new JButton("Autentificare");
button.setBounds(80, 97, 112, 23);
panel.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String user = textField.getText();
String pass = passwordField.getText();
if(user.equals("admin") && pass.equals("admin")) {
FereastraPrincipala(mntmLogout.setEnabled(true));
FereastraPrincipala(mnAdministrator.setEnabled(true));
JOptionPane.showMessageDialog(null,"Login esuat","Login esuat",JOptionPane.ERROR_MESSAGE);
} else if (user.equals("prez") && pass.equals("prez")) {
/* FereastraPrincipala(mntmLogout.setEnabled(true)):
FereastraPrincipala(mnPresedinte.setEnabled(true)); */
JOptionPane.showMessageDialog(null,"Login esuat","Login esuat",JOptionPane.ERROR_MESSAGE);
} else { JOptionPane.showMessageDialog(null,"Login esuat","Login esuat",JOptionPane.ERROR_MESSAGE);}
}
});
}
}

frame 2 inside frame 1

I have 2 classes; Students and RegisterStudents, and hence 2 different main_panel(Class 1) and panel_1 (Class 2). What I am trying to do is, when a button on the Students Interface is pressed, the whole panel_1 should appear within main_panel. I have set both to same size already. is that possible?
The code i got so far is:
JButton btnNewButton = new JButton("Register Student");
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
Students main_panel = new Students();
RegisterStudent panel_1 = new RegisterStudent();
main_panel.add(panel_1);
}
});
btnNewButton.setBounds(0, 162, 167, 37);
panel.add(btnNewButton);
This isnt doing anything though? its compiling, but panel_1 is not actually appearing inside the main_panel. Has anyone got any suggestions?
JButton btnNewButton = new JButton("Register Student");
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
Students main_panel = new Students();
RegisterStudent panel_1 = new RegisterStudent();
main_panel.add(panel_1);
panel.add(main_panel); // ADD THIS LINE
}
});
btnNewButton.setBounds(0, 162, 167, 37);
panel.add(btnNewButton);
You were initializing the new main_panel, and new panel_1, and adding panel_1 to main_panel but then you weren't doing anything with the new main_panel.
Also, I highly suggest naming your variables otherwise - these names are very non-intuitive.
For such things I would suggest you to use CardLayout
When you add something to the container, you must call revalidate() and repaint() methods to realize the changes made to it at RunTime. Like in your case you adding main_panel.add(panel_1);now after this you must perform
main_panel.revalidate();
main_panel.repaint();
frame.getRootPane().revalidate(); // for Upto JDK 1.6.
frame.revalidate(); // for JDK 1.7+
frame.repaint();
so that changes can be seen. A small code snippet to help you understand what I mean.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MultiplePanels extends JFrame
{
private JPanel registrationPanel, loginPanel, searchPanel;
private JButton registerButton, loginButton, searchButton;
private ActionListener action;
public MultiplePanels()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
registrationPanel = new JPanel();
registrationPanel.setBackground(Color.WHITE);
loginPanel = new JPanel();
loginPanel.setBackground(Color.YELLOW);
searchPanel = new JPanel();
searchPanel.setBackground(Color.BLUE);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0, 1));
buttonPanel.setBackground(Color.DARK_GRAY);
registerButton = new JButton("REGISTER");
loginButton = new JButton("LOGIN");
searchButton = new JButton("SEARCH");
buttonPanel.add(registerButton);
buttonPanel.add(loginButton);
buttonPanel.add(searchButton);
action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
if (button == registerButton)
{
if (!(loginPanel.isShowing()) && !(searchPanel.isShowing()))
{
add(registrationPanel, BorderLayout.CENTER);
}
else
{
if (loginPanel.isShowing())
{
remove(loginPanel);
add(registrationPanel, BorderLayout.CENTER);
}
else if (searchPanel.isShowing())
{
remove(searchPanel);
add(registrationPanel, BorderLayout.CENTER);
}
}
}
else if (button == loginButton)
{
if (!(registrationPanel.isShowing()) && !(searchPanel.isShowing()))
{
add(loginPanel, BorderLayout.CENTER);
}
else
{
if (registrationPanel.isShowing())
{
remove(registrationPanel);
add(loginPanel, BorderLayout.CENTER);
}
else if (searchPanel.isShowing())
{
remove(searchPanel);
add(loginPanel, BorderLayout.CENTER);
}
}
}
else if (button == searchButton)
{
if (!(loginPanel.isShowing()) && !(registrationPanel.isShowing()))
{
add(searchPanel, BorderLayout.CENTER);
}
else
{
if (loginPanel.isShowing())
{
remove(loginPanel);
add(searchPanel, BorderLayout.CENTER);
}
else if (registrationPanel.isShowing())
{
remove(registrationPanel);
add(searchPanel, BorderLayout.CENTER);
}
}
}
// This is what we are doing here to realize the changes
// made to the GUI.
revalidate();
repaint();
}
};
registerButton.addActionListener(action);
loginButton.addActionListener(action);
searchButton.addActionListener(action);
add(buttonPanel, BorderLayout.LINE_START);
setSize(300, 300);
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new MultiplePanels();
}
});
}
}

Categories