I am trying to code a program with multiple screens, however, I do not want to use tabbed panes. I have looked at using multiple JPanels with the card layout and the methods are simply not working. What I need to be able to do is load the new JPanel when a button is clicked. Here is my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class IA extends JFrame {
private JPanel contentPane;
private JPanel home;
private JPanel clients;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
IA frame = new IA();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public IA() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new CardLayout(0, 0));
JPanel home = new JPanel();
contentPane.add(home, "name_714429679706141");
home.setLayout(null);
JButton btnClients = new JButton("Clients");
btnClients.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
home.setVisible(false);
clients.setVisible(true);
}
});
btnClients.setBounds(160, 108, 89, 23);
home.add(btnClients);
JPanel clients = new JPanel();
contentPane.add(clients, "name_714431450350356");
clients.setLayout(null);
JButton btnHome = new JButton("Home");
btnHome.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clients.setVisible(false);
home.setVisible(true);
}
});
btnHome.setBounds(169, 107, 89, 23);
clients.add(btnHome);
}
}
The problem is that you have duplicate variables home and clients .
The folllowing is your modified code to fix that, with comments on the changed lines (five lines total) :
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class IA extends JFrame {
private final JPanel contentPane;
// private final JPanel home; // REMOVED
// private JPanel clients; // REMOVED
/**
* Launch the application.
*/
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
IA frame = new IA();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public IA() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new CardLayout(0, 0));
final JPanel home = new JPanel();
contentPane.add(home, "name_714429679706141");
home.setLayout(null);
final JPanel clients = new JPanel(); // MOVED UP
contentPane.add(clients, "name_714431450350356"); // MOVED UP
clients.setLayout(null); // MOVED UP
JButton btnClients = new JButton("Clients");
btnClients.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
home.setVisible(false);
clients.setVisible(true);
}
});
btnClients.setBounds(160, 108, 89, 23);
home.add(btnClients);
JButton btnHome = new JButton("Home");
btnHome.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
clients.setVisible(false);
home.setVisible(true);
}
});
btnHome.setBounds(169, 107, 89, 23);
clients.add(btnHome);
}
}
I would take a look at this post, however I have a feeling you'll need to use a actionlistener to get this done...
Java Swing. Opening a new JPanel from a JButton and making the buttons pretty
I would of left this as a comment but apparently you need 50 rep for that...
This link might be more helpful.. How to open a new window by clicking a button
When the following code is invoked the clients variable equals to null.
JButton btnClients = new JButton("Clients");
btnClients.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
home.setVisible(false);
clients.setVisible(true);
}
});
Write this:
JPanel clients = new JPanel();
contentPane.add(clients, "name_714431450350356");
clients.setLayout(null);
JButton btnHome = new JButton("Home");
btnHome.setBounds(169, 107, 89, 23);
clients.add(btnHome);
before you add the Action Listener
Related
I have made a JFrame that shows a start button, and changes to stop when clicked. How to make it so that it changes its text to start when stop is clicked. Here is the source code:
public class FRMCountdown extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FRMCountdown frame = new FRMCountdown();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public FRMCountdown() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton Start_Stop_btn = new JButton("Start");
Start_Stop_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Start_Stop_btn.setText("Stop");
}
});
Start_Stop_btn.setBounds(10, 188, 89, 23);
contentPane.add(Start_Stop_btn);
}
}
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section.
Swing was designed to be used with layout managers. I used a FlowLayout to place one JButton. Null layouts and absolute positioning lead to problems.
Java field names start with a lower case letter, Java method names start with a lower case letter. Java class names start with an upper case letter.
Here's the modified code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ToggleJButton {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new ToggleJButton();
}
});
}
public ToggleJButton() {
JFrame frame = new JFrame("Toggle JButton");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 100, 5, 100));
JButton startStopButton = new JButton("Start");
startStopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JButton button = (JButton) event.getSource();
String text = button.getText();
if (text.contentEquals("Start")) {
text = "Stop";
} else {
text = "Start";
}
button.setText(text);
}
});
panel.add(startStopButton);
return panel;
}
}
I tried to add a button to the JFrame, but it won't appear for some reason. How do I make it appear?
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Container;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.*;
public class GraficoconArreglo extends javax.swing.JFrame {
JPanel pan = (JPanel) this.getContentPane();
JLabel []lab = new JLabel[6];
JTextField []text = new JTextField[6];
Border border = BorderFactory.createLineBorder(Color.pink,1);
JButton b = new JButton("Calculate");
public GraficoconArreglo() {
initComponents();
pan.setLayout(null);
pan.setBackground(Color.GRAY);
for(int i=0; i<lab.length ;i++){
lab[i] = new JLabel();
text[i] = new JTextField();
lab[i].setBounds(new Rectangle(15,(i+1)*40, 60, 25));
lab[i].setText("Data " + (i+1));
lab[i].setBorder(border);
text[i].setBounds(new Rectangle(100,(i+1)*40, 60, 25));
pan.add(lab[i],null);
pan.add(text[i],null);
setSize(200,330);
setTitle("Arrays in forums.");
add(b);
b.addActionListener((ActionListener) this);
}
}
You are creating only one button and adding it to 6 different places. Therefore, you only would see it on the last place you added.
You should add the button to the contentPane, not the JFrame. A working code for this, provided from SwingDesigner from Eclipse Marketplace would be:
public class Window extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window frame = new Window();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Window() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(170, 110, 89, 23);
contentPane.add(btnNewButton);
}
}
I am trying to get a JTextField to show over a JButton when I click the button. I have that working, but when I click out of the button it still stays visible. I'm using a MouseListener event so once I exit the button I want JTextField to become transparent again, but it stays visible.
My code:
import java.awt.EventQueue;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseEvent;
public class magicalJtextField extends JFrame implements MouseListener{
private JPanel contentPane;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
magicalJtextField frame = new magicalJtextField();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public magicalJtextField() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(78, 78, 89, 30);
contentPane.add(textField);
textField.setColumns(10);
JButton button = new JButton("");
//button transparent
// button.setOpaque(false);
// button.setContentAreaFilled(false);
// button.setBorderPainted(false);
button.setBounds(78, 78, 89, 23);
button.addMouseListener(this);
contentPane.add(button);
textField.setVisible(false);
}
public void mouseEntered(MouseEvent e)
{
//button.setText("Mouse Entered");
//button.setBackground(Color.CYAN);
// textField.setVisible(true);
}
public void mouseExited(MouseEvent e)
{
textField.setVisible(false);
}
public void mouseClicked(MouseEvent e)
{
textField.setVisible(true);
}
public void mousePressed(MouseEvent e)
{
textField.setVisible(true);
}
public void mouseReleased(MouseEvent e)
{
textField.setVisible(true);
}
}
I suggest a CardLayout for the Jbutton-JTextField magic trick (edit: I actually saw the recommendations in the comments only after I posted because it was so obvious and on an answer). Pressing the button will switch the card and then exiting the text field area with the mouse will switch it again.
public class Example extends JPanel {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new JFrame();
frame.add(new Example());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
});
}
public Example() {
CardLayout cards = new CardLayout(5, 5);
JPanel panel = new JPanel(cards);
JButton button = new JButton("");
JTextField textField = new JTextField(10);
button.addActionListener(e -> {
cards.next(panel);
textField.requestFocusInWindow();
});
textField.addMouseListener(new MouseAdapter() {
#Override
public void mouseExited(MouseEvent e) {
cards.next(panel);
}
});
panel.add(button);
panel.add(textField);
add(panel);
}
}
As you were told by Andrew Thompson, don't use null layouts and don't specify bounds. Use a proper layout manager to do this for you.
Use an ActionListener to react on the button click: If you receive a click, make the button invisible and the textField visible.
Then attach the MouseListener to the textField and not the button and only implement mouseExited (all others empty). When you receive this event make the textField invisible and the button visible again.
I'm trying to make a scrollable JTextArea. I'm not quite sure what's wrong with my code here... When I create this GUI, it doesn't create the chatBox
package GUI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import Client.Client;
#SuppressWarnings("serial")
public class GUI extends JFrame implements KeyListener {
public static JPanel contentPane;
public static JTextField usernameBox;
public static JTextField inputBox;
public static JTextField ipBox;
public static JLabel usernameLabel;
public static JButton connectButton;
public static JButton disconnectButton;
public static JLabel usersLabel;
public static JTextArea usersBox;
public static JTextArea chatBox;
public static JButton sendButton;
public static JLabel ipLabel;
public static JMenuBar menuBar;
public static JMenu file;
public static JMenuItem about;
public static JMenuItem connect;
public static JMenuItem disconnect;
public static JMenuItem setDefaultUsername;
public static JMenuItem setDefaultIP;
public static String setUser;
public static String setIP;
public static String title;
public static JScrollPane scroll = new JScrollPane(chatBox);
#SuppressWarnings("unused")
private static About aboutFrame;
public GUI() {
System.out.println("Creating new client...");
addItems();
System.out.println("DONE");
}
public void addItems() {
// Frame
title = "title";
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 760, 355);
setTitle(title);
setSize(770, 385);
setResizable(false);
// Panel
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
// Username Box
usernameBox = new JTextField();
usernameBox.setBounds(88, 6, 117, 28);
usernameBox.setColumns(10);
contentPane.add(usernameBox);
// Username Label
usernameLabel = new JLabel("Username");
usernameLabel.setBounds(17, 12, 72, 16);
contentPane.add(usernameLabel);
// Connect Button
connectButton = new JButton("Connect");
connectButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Connect");
Client.Connect();
}
});
connectButton.setBounds(365, 7, 117, 29);
contentPane.add(connectButton);
// Disconnect Button
disconnectButton = new JButton("Disconnect");
disconnectButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Disconnect");
Client.Disconnect();
}
});
disconnectButton.setBounds(493, 7, 117, 29);
contentPane.add(disconnectButton);
// Users Label
usersLabel = new JLabel("Users");
usersLabel.setBounds(664, 12, 61, 16);
contentPane.add(usersLabel);
// Users Box
usersBox = new JTextArea();
usersBox.setEditable(false);
usersBox.setBounds(622, 40, 122, 282);
contentPane.add(usersBox);
// Chat Box
chatBox = new JTextArea();
chatBox.setEditable(false);
chatBox.setBounds(17, 40, 593, 226);
scroll = new JScrollPane(chatBox, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
contentPane.add(scroll);
// Input Box
inputBox = new JTextField();
inputBox.setBounds(17, 274, 506, 48);
contentPane.add(inputBox);
inputBox.setColumns(10);
inputBox.addKeyListener(this);
inputBox.setEditable(false);
// Send Button
sendButton = new JButton("Send");
sendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Send");
Client.Send();
}
});
sendButton.setBounds(526, 274, 84, 48);
contentPane.add(sendButton);
// ipLabel
ipLabel = new JLabel("IP");
ipLabel.setBounds(215, 12, 17, 16);
contentPane.add(ipLabel);
// ipBox
ipBox = new JTextField();
ipBox.setBounds(236, 6, 117, 28);
contentPane.add(ipBox);
ipBox.setColumns(10);
// Set Pane
setContentPane(contentPane);
// send disconnect on close of window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Client.Disconnect();
}
});
menuBar = new JMenuBar();
setJMenuBar(menuBar);
file = new JMenu("File");
menuBar.add(file);
about = new JMenuItem("About");
file.add(about);
connect = new JMenuItem("Connect");
file.add(connect);
disconnect = new JMenuItem("Disconnect");
file.add(disconnect);
setDefaultUsername = new JMenuItem("Set default username.");
file.add(setDefaultUsername);
setDefaultIP = new JMenuItem("Set default IP address.");
file.add(setDefaultIP);
about.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
aboutFrame = new About();
}
});
setDefaultUsername.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
promptDefaultUser();
}
});
setDefaultIP.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
promptDefaultIP();
}
});
connect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Client.Connect();
}
});
disconnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Client.Disconnect();
}
});
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER)
Client.Send();
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
Don't use a null layout!!!
Your scrollpane doesn't have a proper size so its not painted. Even if it does get painted. Swing was designed to be used with layout managers for too many reasons to list here.
Read the JTextArea API and follow the link to the Swing tutorial where you will find working examples of the proper way to use a text area in a scrollpane.
You need to place the JTextArea and the JScrollPane at the right places, then everything should work.
The JTextArea resides inside the JScrollPane and it is not required to call setBounds(...) on it. This is because the origin of the JTextArea inside the scrollpane should be (0,0).
The JScrollPane needs to be placed at the location where you placed the JTextArea at.
chatBox = new JTextArea();
chatBox.setEditable(false);
scroll = new JScrollPane(chatBox, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setBounds(17,40,593,226);
contentPane.add(scroll);
chatBox = new JTextArea();
chatBox.setEditable(false);
chatBox.setBounds(17, 40, 593, 226);
scroll = new JScrollPane(chatBox, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
contentPane.add(scroll);
// Input Box
issues:
where are you setting the Bound of JSCrollPane to become visible in the panel with null layout?
You are using null layout! you should use LayoutManager which will lay out your GUI component for you. start learning them.
JScrollPane uses the component's preferred size under it's view to scroll it. Well don't rush to set the preferred size of chatBox right now. The LayoutManager should do it for you.
start learning from : A Visual Guide to Layout Managers
I'm getting a NullPointerException error at line 77 lblNewLabel.setVisible(false);
which is called from line 65 runTest(); in the following code. (This is a dummy project I wrote to simulate a problem I'm having in a larger project). What I'm trying to do is change the attribute of several fields, buttons, etc based on user action at various places in the project. I would like to group all the changes in a separate method that can be called from various other methods. I'm still a Java novice, having come from some Visual Basic and Pascal experience. Seems like what I'm trying to do should be straight forward, but for now, I'm at a loss. Thanks in advance for your suggestions.
package woodruff;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.SwingConstants;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
public class MyTest extends JFrame {
private JPanel contentPane;
private JTextField txtHasFocus;
private JLabel lblNewLabel;
/**
* Create the frame.
*/
public MyTest() {
initialize();
}
private void initialize() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 237, 161);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
final JLabel lblNewLabel = new JLabel("This is a label.");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setHorizontalTextPosition(SwingConstants.CENTER);
lblNewLabel.setBounds(10, 25, 202, 14);
contentPane.add(lblNewLabel);
JButton btnShow = new JButton("Show");
btnShow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
lblNewLabel.setVisible(true);
}
});
btnShow.setBounds(10, 50, 89, 23);
contentPane.add(btnShow);
JButton btnHide = new JButton("Hide");
btnHide.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lblNewLabel.setVisible(false);
}
});
btnHide.setBounds(123, 50, 89, 23);
contentPane.add(btnHide);
txtHasFocus = new JTextField();
txtHasFocus.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent arg0) {
// Following results in NullPointerException error
// at woodruff.MyTest.runTest(MyTest.java:77)
runTest();
}
});
txtHasFocus.setHorizontalAlignment(SwingConstants.CENTER);
txtHasFocus.setText("Has Focus?");
txtHasFocus.setBounds(67, 92, 86, 20);
contentPane.add(txtHasFocus);
txtHasFocus.setColumns(10);
}
private void runTest() {
lblNewLabel.setVisible(false);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyTest frame = new MyTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
In the initialize() method, you have created a local variable for JLabel, and hence are not initializing the instance field, as a reason it remains initialized to null, and hence NPE.
final JLabel lblNewLabel = new JLabel("This is a label.");
change the above line to: -
lblNewLabel = new JLabel("This is a label.");