Get a JTextFeild to go back to a transparent state - java

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.

Related

Is it possible to make a toggleable button that changes text when clicked

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

How can I add a functional Java key listener to a panel under the card layout?

I was designing a program which has multiple layers(panels), and I want these panels to be keyboard sensitive so that I can press ESC to exit to the main menu (First panel) at any time.
Here is the switch panel code that I've written:
public void switchPane(JPanel jp) {
frmDavidsAppstore.getContentPane().removeAll();
frmDavidsAppstore.getContentPane().add(jp);
frmDavidsAppstore.getContentPane().repaint();
frmDavidsAppstore.getContentPane().revalidate();
jp.requestFocusInWindow();
}
I know that in order for the panel to be keyboard sensitive, it needs to be focusable.
Here's the code I have written for the initialisation of one of the panels:
panel2 = new JPanel();
panel2.setFocusable(true);
frmDavidsAppstore.getContentPane().add(panel2, "name_83147693736131");
panel2.setLayout(null);
panel2.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("panel2: " + KeyEvent.getKeyText(e.getKeyCode()));
if(e.getKeyCode()==KeyEvent.VK_ESCAPE) {
switchPane(panel1);
}
}
});
JButton btnReturnToMain = new JButton("Return to main page");
btnReturnToMain.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel1);
}
});
btnReturnToMain.setBounds(279, 431, 236, 50);
panel2.add(btnReturnToMain);
I have deleted most of the unrelated functions and codes.
What I wish to accomplish is that when the switch page button is clicked, the switchPane method is executed, and the new panel automatically gets the focus with the requestFocusInWindow(); command, so that user can type ESC to return to the main menu.
When I tried to run the program, it turns out that for the first time I entered a sub-panel, it can not get the focus and does not respond to the keyboard. However, if I return to the main panel using the return button and re-enter the same sub-panel, this time it automatically gets the focus and is responding to the keyboard.
I have no idea why the program shows such behaviour. The following is the full program. Please notice that in the full program I also added a click to get focus function which works. However, I wish the newly opened panel can automatically get the focus and responding to the keys without the user actually clicking the panel.
import java.awt.*;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.awt.Font;
import javax.swing.JList;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class mainFrame {
private JFrame frmDavidsAppstore;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainFrame window = new mainFrame();
window.frmDavidsAppstore.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mainFrame() {
initialize();
}
public void switchPane(JPanel jp) {
frmDavidsAppstore.getContentPane().removeAll();
frmDavidsAppstore.getContentPane().add(jp);
frmDavidsAppstore.getContentPane().repaint();
frmDavidsAppstore.getContentPane().revalidate();
jp.requestFocusInWindow();
System.out.println(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmDavidsAppstore = new JFrame();
frmDavidsAppstore.setResizable(false);
frmDavidsAppstore.setTitle("David's appstore");
frmDavidsAppstore.setBounds(100, 100, 800, 600);
frmDavidsAppstore.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmDavidsAppstore.getContentPane().setLayout(new CardLayout(0, 0));
panel1 = new JPanel();
panel1.setFocusable(true);
frmDavidsAppstore.getContentPane().add(panel1, "name_83127645466169");
panel1.setLayout(null);
panel1.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("panel1: " + KeyEvent.getKeyText(e.getKeyCode()));
}
});
JButton button2 = new JButton("Open page 2");
button2.setFont(new Font("Tahoma", Font.PLAIN, 18));
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel2);
}
});
button2.setBounds(279, 344, 236, 50);
panel1.add(button2);
JButton button3 = new JButton("Open page 3");
button3.setFont(new Font("Tahoma", Font.PLAIN, 18));
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel3);
}
});
button3.setBounds(279, 432, 236, 50);
panel1.add(button3);
JLabel background = new JLabel("");
background.setIcon(new ImageIcon(mainFrame.class.getResource("/images/background_main.jpg")));
background.setBounds(0, 0, 794, 565);
panel1.add(background);
panel2 = new JPanel();
panel2.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
panel2.requestFocusInWindow();
System.out.println(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
}
});
panel2.setFocusable(true);
frmDavidsAppstore.getContentPane().add(panel2, "name_83147693736131");
panel2.setLayout(null);
panel2.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("panel2: " + KeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
switchPane(panel1);
}
}
});
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(130, 104, 533, 270);
panel2.add(scrollPane_1);
JTextArea txtrIAmPage = new JTextArea();
txtrIAmPage.setEditable(false);
scrollPane_1.setViewportView(txtrIAmPage);
txtrIAmPage.setText("I am page2");
JButton btnReturnToMain = new JButton("Return to main page");
btnReturnToMain.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel1);
}
});
btnReturnToMain.setBounds(279, 431, 236, 50);
panel2.add(btnReturnToMain);
panel3 = new JPanel();
panel3.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
panel3.requestFocusInWindow();
System.out.println(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
}
});
panel3.setFocusable(true);
frmDavidsAppstore.getContentPane().add(panel3, "name_83334788966651");
panel3.setLayout(null);
panel3.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("panel3: " + KeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
switchPane(panel1);
}
}
});
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(130, 104, 533, 270);
panel3.add(scrollPane);
JTextArea txtrIAmPage_1 = new JTextArea();
scrollPane.setViewportView(txtrIAmPage_1);
txtrIAmPage_1.setText("I am page3");
JButton button = new JButton("Return to main page");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel1);
}
});
button.setBounds(279, 431, 236, 50);
panel3.add(button);
}
}
I have been working on it for a day now and couldn't figure out why. Thank you guys so much for any help or advices.
Apreciated!
Problem solved!!! You need to add .setVisible(true); before .requestFocusInWindow(); in order for it to work!

How to open a new JPanel with a JButton?

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

Go back to prior JPanel

I have inherited code and for reasons to long to explain I am required to use a null layout. I have been attempting to take what they have an navigate between JPanels. I haven't been able to figure out how. This is what I have now which compiles broken down into a SSCCE below. What I am attempting to do is add the JPanels to an ArrayList which contains a reference to previous JPanels. That way I can call a "home" JPanel from the current JPanel the user is in. As of now it goes to the previous JPanel but the contents are empty. Any help would be great, THANKS!
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Mainscreen extends JFrame {
public JPanel Home;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Mainscreen frame = new Mainscreen();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Mainscreen() {
ArrayList <JPanel> jpLayout = new ArrayList();
final Dataentrylog DEL = new Dataentrylog(this, jpLayout);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setBounds(100, 100, 618, 373);
Home=new JPanel();
Home.setBackground(new Color(255, 250, 250));
Home.setBorder(new LineBorder(Color.DARK_GRAY, 1, true));
Home.setVisible(true);
setContentPane(Home);
Home.setLayout(null);
JButton delLog = new JButton("Next JPanel");
delLog.setFont(new Font("Tahoma", Font.PLAIN, 14));
delLog.setForeground(new Color(0, 0, 0));
delLog.setBackground(UIManager.getColor("Menu.selectionBackground"));
Home.add(delLog);
jpLayout.add(Home);
delLog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Home.setVisible(false);
setContentPane(DEL);
getContentPane().setLayout(null);
}
});
delLog.setBounds(44, 214, 213, 61);
}
}
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Dataentrylog extends JPanel {
public Dataentrylog(final JFrame parent, final ArrayList <JPanel> jpLayout) {
setBounds(100, 100, 618, 373);
setBackground(new Color(255, 250, 250));
setBorder(new LineBorder(Color.DARK_GRAY, 1, true));
setLayout(null);
final JButton btnSignIn = new JButton("Go Back");
btnSignIn.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnSignIn.setBackground(UIManager.getColor("EditorPane.selectionBackground"));
btnSignIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
parent.setContentPane(jpLayout.get(0));
setLayout(null);
}
});
btnSignIn.setBounds(226, 282, 153, 52);
add(btnSignIn);
}
}
I am required to use a null layout.
If you are asked by some mentor to perform navigation among panels using null layout, here is what you need to do:
First, leave the mentor.
Second, use CardLayout.
Check out the tutorial: How to use CardLayout
Working Example:
here is a written CardLayoutDemo which navigates among 10 panels including Home panel using button click action:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class CardLayoutDemo1 extends JFrame {
private JPanel jPanel1;
private JButton navHomeButt;
private JButton navNextButt;
private JButton navPreviousButt;
private JPanel panelContainer;
public CardLayoutDemo1() {
initComponents();
panelContainer.add(createSamplePanel("Home Panel "), ""+0);
for(int i=1; i < 10; i++)
{
panelContainer.add(createSamplePanel("Panel "+i), ""+i);
}
}
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
navPreviousButt = new JButton();
navNextButt = new JButton();
navHomeButt = new JButton();
panelContainer = new JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
navPreviousButt.setText("Previous");
navPreviousButt.setPreferredSize(new Dimension(90, 23));
jPanel1.add(navPreviousButt);
navNextButt.setText("next");
navNextButt.setPreferredSize(new Dimension(90, 23));
jPanel1.add(navNextButt);
navHomeButt.setText("Back to Home");
jPanel1.add(navHomeButt);
panelContainer.setPreferredSize(new Dimension(400, 300));
panelContainer.setLayout(new CardLayout());
// setting the card layout
getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_END);
getContentPane().add(panelContainer, BorderLayout.CENTER);
navNextButt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
CardLayout cardLayout = (CardLayout) panelContainer.getLayout();
cardLayout.next(panelContainer);
// using cardLayout next() to go to next panel
}
});
navHomeButt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
CardLayout cardLayout = (CardLayout) panelContainer.getLayout();
cardLayout.first(panelContainer);
// suing first to get to the home panel
}
});
navPreviousButt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
CardLayout cardLayout = (CardLayout) panelContainer.getLayout();
cardLayout.previous(panelContainer);
// using previous to get to previous(left)panel
}
});
pack();
}
public JPanel createSamplePanel(String panelTitle)
{
JPanel samplePanel = new JPanel();
samplePanel.add(new JLabel(panelTitle));
return samplePanel;
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CardLayoutDemo1().setVisible(true);
}
});
}
}

Having a bit of trouble with a JScrollPane

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

Categories