I am writing a simple card game GUI with a JTextArea to display what is happening and who placed which card and so on. After I finished the layout, I added a method to append the text to the JTextArea character by character, so it has a nice writing effect. I have a class for creating the window and GUI, and a class for the game and the output to the TextArea.
This works however only for initializing the game. After that the player has to choose a card by pressing a button and when he does, I call a method within the game object so that it goes on. The problem here is it waits until the actionEvent from the button press is performed and then updates the TextArea with all text that the game processed without updating it character by character. Just adding textArea.update(... after every character doesnt solve the problem because the area begins to flicker.
Here is my window class:
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
import javax.swing.JTable;
import javax.swing.border.MatteBorder;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.JPanel;
import java.awt.ComponentOrientation;
public class window {
private JFrame frmStinkt;
private JLabel label;
private JTextArea textArea;
private JTable table;
private static ArrayList<JButton> buttons = new ArrayList<JButton>();
private JTextField textField;
private static WindowGame newGame;
private static int test = 0;
/**
* Launch the application.
*/
public static void main(String[] args)
{
window window = new window(104, 4);
window.frmStinkt.setVisible(true);
newGame = new WindowGame(104, 4, window.textArea, window.table);
newGame.initGame();
setButtonNames(newGame.players.get(0).cards);
window.enableButtons();
}
/**
* Create the application.
*/
public window(int numberOfCards, int numberOfRows)
{
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Font defaultFont = new Font("Gill Sans MT",Font.BOLD,14);
frmStinkt = new JFrame();
frmStinkt.setTitle("6 STINKT!");
frmStinkt.getContentPane().setForeground(Color.GREEN);
frmStinkt.getContentPane().setFocusTraversalPolicyProvider(true);
frmStinkt.getContentPane().setBackground(Color.BLACK);
frmStinkt.setBounds(400, 200, 600, 450);
frmStinkt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmStinkt.getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBorder(null);
scrollPane.setBounds(83, 18, 420, 130);
frmStinkt.getContentPane().add(scrollPane);
textArea = new JTextArea();
textArea.setBorder(new LineBorder(new Color(0, 255, 0), 2, true));
textArea.setEditable(false);
scrollPane.setViewportView(textArea);
textArea.setWrapStyleWord(true);
textArea.setForeground(Color.GREEN);
textArea.setBackground(Color.BLACK);
textArea.setLineWrap(true);
textArea.setFont(new Font("Gill Sans MT", Font.BOLD, 13));
label = new JLabel("CARDS");
label.setEnabled(false);
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setForeground(Color.GREEN);
label.setBackground(Color.DARK_GRAY);
label.setFont(defaultFont);
label.setBounds(254, 264, 78, 23);
frmStinkt.getContentPane().add(label);
table = new JTable();
table.setShowVerticalLines(false);
table.setGridColor(new Color(0, 255, 0));
table.setForeground(Color.GREEN);
table.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 255, 0)));
table.setBackground(Color.BLACK);
table.setBounds(165, 160, 255, 64);
table.setFont(new Font("Gill Sans MT", Font.BOLD, 14));
frmStinkt.getContentPane().add(table);
textField = new JTextField();
textField.setEditable(false);
textField.setForeground(new Color(0, 255, 0));
textField.setBackground(Color.DARK_GRAY);
textField.setFont(new Font("Gill Sans MT", Font.BOLD, 14));
textField.setBounds(277, 235, 32, 25);
frmStinkt.getContentPane().add(textField, BorderLayout.CENTER);
textField.setHorizontalAlignment(JTextField.CENTER);
textField.setColumns(10);
JPanel panel = new JPanel();
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panel.setBackground(Color.BLACK);
panel.setBounds(10, 284, 564, 66);
frmStinkt.getContentPane().add(panel);
JButton button0 = new JButton("---");
panel.add(button0);
button0.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
button0.setVisible(false);
test = buttons.indexOf(button0);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(0)));
disableButtons();
newGame.HumanTurn(test);
buttons.remove(0);
}
});
button0.setForeground(new Color(0, 255, 0));
button0.setBackground(Color.decode("#000000"));
button0.setFont(defaultFont);
button0.setOpaque(true);
button0.setRequestFocusEnabled(false);
button0.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button0);
JButton button1 = new JButton("---");
panel.add(button1);
button1.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(1);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(1)));
disableButtons();
panel.remove(button0);
}
});
button1.setForeground(new Color(0, 255, 0));
button1.setBackground(Color.decode("#000000"));
button1.setFont(defaultFont);
button1.setOpaque(true);
button1.setRequestFocusEnabled(false);
button1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button1);
JButton button2 = new JButton("---");
panel.add(button2);
button2.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(2);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(2)));
disableButtons();
}
});
button2.setForeground(new Color(0, 255, 0));
button2.setBackground(Color.decode("#000000"));
button2.setFont(defaultFont);
button2.setOpaque(true);
button2.setRequestFocusEnabled(false);
button2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button2);
JButton button3 = new JButton("---");
panel.add(button3);
button3.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(3);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(3)));
disableButtons();
}
});
button3.setRequestFocusEnabled(false);
button3.setForeground(new Color(0, 255, 0));
button3.setBackground(Color.decode("#000000"));
button3.setFont(defaultFont);
button3.setOpaque(true);
button3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button3);
JButton button4 = new JButton("---");
panel.add(button4);
button4.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(4);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(4)));
disableButtons();
}
});
button4.setRequestFocusEnabled(false);
button4.setForeground(new Color(0, 255, 0));
button4.setBackground(Color.decode("#000000"));
button4.setFont(defaultFont);
button4.setOpaque(true);
button4.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button4);
JButton button5 = new JButton("---");
panel.add(button5);
button5.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(5);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(5)));
disableButtons();
}
});
button5.setRequestFocusEnabled(false);
button5.setForeground(new Color(0, 255, 0));
button5.setBackground(Color.decode("#000000"));
button5.setFont(defaultFont);
button5.setOpaque(true);
button5.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button5);
JButton button6 = new JButton("---");
panel.add(button6);
button6.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(6);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(6)));
disableButtons();
}
});
button6.setRequestFocusEnabled(false);
button6.setForeground(new Color(0, 255, 0));
button6.setBackground(Color.decode("#000000"));
button6.setFont(defaultFont);
button6.setOpaque(true);
button6.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button6);
JButton button7 = new JButton("---");
panel.add(button7);
button7.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(7);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(7)));
disableButtons();
}
});
button7.setRequestFocusEnabled(false);
button7.setForeground(new Color(0, 255, 0));
button7.setBackground(Color.decode("#000000"));
button7.setFont(defaultFont);
button7.setOpaque(true);
button7.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button7);
JButton button8 = new JButton("---");
panel.add(button8);
button8.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(8);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(8)));
disableButtons();
}
});
button8.setRequestFocusEnabled(false);
button8.setForeground(new Color(0, 255, 0));
button8.setBackground(Color.decode("#000000"));
button8.setFont(defaultFont);
button8.setOpaque(true);
button8.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button8);
JButton button9 = new JButton("---");
panel.add(button9);
button9.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(9);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(9)));
disableButtons();
}
});
button9.setRequestFocusEnabled(false);
button9.setForeground(new Color(0, 255, 0));
button9.setBackground(Color.decode("#000000"));
button9.setFont(defaultFont);
button9.setOpaque(true);
button9.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button9);
JButton random_1 = new JButton("RANDOM");
random_1.setBounds(238, 361, 105, 25);
frmStinkt.getContentPane().add(random_1);
random_1.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
random_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int random = (int)(Math.random() * newGame.players.get(0).cards.size());
newGame.HumanTurn(random);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(random)));
disableButtons();
}
});
random_1.setRequestFocusEnabled(false);
random_1.setForeground(new Color(0, 255, 0));
random_1.setBackground(Color.decode("#000000"));
random_1.setFont(defaultFont);
random_1.setOpaque(true);
random_1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(random_1);
disableButtons();
}
public void enableButtons()
{
for(int i=0; i<buttons.size(); i++)
buttons.get(i).setEnabled(true);
label.setEnabled(true);
}
public void disableButtons()
{
for(int i=0; i<buttons.size(); i++)
buttons.get(i).setEnabled(false);
label.setEnabled(false);
}
public static void setButtonNames(ArrayList<Integer> cards)
{
for(int i=0; i<buttons.size() - 1; i++)
buttons.get(i).setText(cards.get(i).toString());
}
}
I have read that I probably could work around this by using a swingWorker. I found a useful demo for a progressBar, but I can't figure out how to use it with my approach. I would appreciate any help. Thanks in advance!
This is how it looks like:
Here the method which is called by the button press and print:
public void HumanTurn(int cardIndex)
{
print("Du hast " + players.get(0).cards.get(cardIndex) + " gewählt.", textSpeedNormal);
next += 1;
BotTurn();
}
public void print(String text, int speed)
{
for(int i=0; i<text.length(); i++)
{
textArea.append(text.substring(i, (i+1)));
try {
Thread.sleep(speed);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
textArea.append("\n");
textArea.setCaretPosition(textArea.getDocument().getLength());
}
Thread.sleep(speed);
Don't use Thread.sleep(...).
This puts the Event Dispatch Thread (EDT) to sleep so the GUI can't respond to events or repaint itself. Read the Swing tutorial on Concurrency for more information.
Instead use a Swing Timer to schedule the animation. The Swing Timer replaces the looping code. Every time the timer fires you do some Action, in this case add a character to the text area.
One way might be to add the text to a StringBuilder. Then every time the Timer fires you remove the first character from the StringBuilder and append it to the text area. When the StringBuilder is empty you stop the Timer.
Related
I have made a parentPanel that has a CardLayout on it, and under this I've made 4 more JPanel containers.
On the left side I have 4 buttons that when I press "Forside" (button) I want to switch to the panel on the card layout (Forside) and so on...
I've tried different youtube tutorials and tried to look on here without any success.
Everything I have tried has ended up with a NullPointerException
public class Main extends JFrame {
private JPanel contentPane;
int xx, xy;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setUndecorated(true); // Hides the jframe top bar
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 735, 506);
contentPane = new JPanel();
contentPane.setBackground(new Color(102, 102, 102));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panelLeft = new JPanel();
panelLeft.setBackground(new Color(51, 51, 51));
panelLeft.setForeground(Color.DARK_GRAY);
panelLeft.setBounds(0, 54, 150, 459);
contentPane.add(panelLeft);
panelLeft.setLayout(null);
JButton btnForside = new JButton("Forside");
btnForside.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnForside.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnForside.setForeground(Color.WHITE);
btnForside.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnForside.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Home_32px_1.png")));
btnForside.setContentAreaFilled(false);
btnForside.setBorderPainted(false);
btnForside.setBorder(null);
btnForside.setBounds(16, 60, 112, 30);
panelLeft.add(btnForside);
JButton btnDagbog = new JButton("Dagbog");
btnDagbog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDagbog.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnDagbog.setContentAreaFilled(false);
btnDagbog.setBorderPainted(false);
btnDagbog.setBorder(null);
btnDagbog.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnDagbog.setForeground(Color.WHITE);
btnDagbog.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Book_32px.png")));
btnDagbog.setBounds(16, 116, 112, 30);
panelLeft.add(btnDagbog);
JButton btnAftaler = new JButton("Aftaler");
btnAftaler.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnAftaler.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnAftaler.setContentAreaFilled(false);
btnAftaler.setBorderPainted(false);
btnAftaler.setBorder(null);
btnAftaler.setForeground(Color.WHITE);
btnAftaler.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnAftaler.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Planner_32px.png")));
btnAftaler.setBounds(16, 173, 112, 30);
panelLeft.add(btnAftaler);
JButton btnKontakt = new JButton("Kontakt");
btnKontakt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnKontakt.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnKontakt.setContentAreaFilled(false);
btnKontakt.setBorder(null);
btnKontakt.setBorderPainted(false);
btnKontakt.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnKontakt.setForeground(Color.WHITE);
btnKontakt.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Phone_32px.png")));
btnKontakt.setBounds(16, 231, 112, 30);
panelLeft.add(btnKontakt);
JPanel panelTop = new JPanel();
panelTop.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent arg0) {
int x = arg0.getXOnScreen(); // makes uggerhøj picture dragable
int y = arg0.getYOnScreen(); // makes uggerhøj picture dragable
Main.this.setLocation(x - xx, y - xy); // makes uggerhøj picture dragable
}
});
panelTop.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
xx = e.getX(); // makes uggerhøj picture dragable
xy = e.getY(); // makes uggerhøj picture dragable
}
});
panelTop.setBackground(new Color(51, 51, 51));
panelTop.setBounds(0, 0, 737, 60);
contentPane.add(panelTop);
panelTop.setLayout(null);
JButton btnX = new JButton("X");
btnX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnX.setRolloverIcon(null);
btnX.setFont(new Font("Tahoma", Font.BOLD, 18));
btnX.setFocusTraversalKeysEnabled(false);
btnX.setFocusPainted(false);
btnX.setBorderPainted(false);
btnX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnX.setContentAreaFilled(false);
btnX.setForeground(SystemColor.activeCaption);
btnX.setBorder(null);
btnX.setBounds(615, 13, 97, 25);
panelTop.add(btnX);
JPanel parentPanel = new JPanel();
parentPanel.setBackground(Color.GRAY);
parentPanel.setBounds(148, 54, 569, 405);
contentPane.add(parentPanel);
parentPanel.setLayout(new CardLayout(0, 0));
JPanel Forside = new JPanel();
parentPanel.add(Forside, "name_1472174211097300");
Forside.setFocusable(false);
JButton btnTest = new JButton("test");
Forside.add(btnTest);
JPanel Dagbog = new JPanel();
parentPanel.add(Dagbog, "name_1472176236196000");
JLabel lblTest = new JLabel("dagbog");
Dagbog.add(lblTest);
JPanel Aftaler = new JPanel();
parentPanel.add(Aftaler, "name_1472177885026100");
JPanel Kontakt = new JPanel();
parentPanel.add(Kontakt, "name_1472179607862700");
}
}
I'd just want it so the right buttons leads to the right cards.
first of all please next time take #AndrewThompson advise about making a MCVE of your code and #camickr advise about the test and debug in little steps before going to the real code (this is the expert programming 101).
the CardLayout object switches between the content of the container via the method
CardLayout.show(Container parent, String name);
keep in mind when making navigation in your swing code DO-NOT make your Components fields in a method instead make it local variables (at least in your case the parentPanel and the CardLayout)
so in order to make your parentPanel switch between your 4 panels (sorry am not familiar with your language) i did a fairly refactored version of your code .
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class Main extends JFrame {
private JPanel contentPane;
int xx, xy;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setUndecorated(true); // Hides the jframe top bar
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 735, 506);
contentPane = new JPanel();
contentPane.setBackground(new Color(102, 102, 102));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Forside = new JPanel();
JPanel Dagbog = new JPanel();
JPanel Aftaler = new JPanel();
JPanel Kontakt = new JPanel();
JPanel panelLeft = new JPanel();
panelLeft.setBackground(new Color(51, 51, 51));
panelLeft.setForeground(Color.DARK_GRAY);
panelLeft.setBounds(0, 54, 150, 459);
contentPane.add(panelLeft);
panelLeft.setLayout(null);
JButton btnForside = new JButton("Forside");
btnForside.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setCardLayoutView("name_1472174211097300");
}
});
btnForside.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnForside.setForeground(Color.WHITE);
btnForside.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnForside.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Home_32px_1.png")));
btnForside.setContentAreaFilled(false);
btnForside.setBorderPainted(false);
btnForside.setBorder(null);
btnForside.setBounds(16, 60, 112, 30);
panelLeft.add(btnForside);
JButton btnDagbog = new JButton("Dagbog");
btnDagbog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setCardLayoutView("name_1472176236196000");
}
});
btnDagbog.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnDagbog.setContentAreaFilled(false);
btnDagbog.setBorderPainted(false);
btnDagbog.setBorder(null);
btnDagbog.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnDagbog.setForeground(Color.WHITE);
btnDagbog.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Book_32px.png")));
btnDagbog.setBounds(16, 116, 112, 30);
panelLeft.add(btnDagbog);
JButton btnAftaler = new JButton("Aftaler");
btnAftaler.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setCardLayoutView("name_1472177885026100");
}
});
btnAftaler.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnAftaler.setContentAreaFilled(false);
btnAftaler.setBorderPainted(false);
btnAftaler.setBorder(null);
btnAftaler.setForeground(Color.WHITE);
btnAftaler.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnAftaler.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Planner_32px.png")));
btnAftaler.setBounds(16, 173, 112, 30);
panelLeft.add(btnAftaler);
JButton btnKontakt = new JButton("Kontakt");
btnKontakt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setCardLayoutView("name_1472179607862700");
}
});
btnKontakt.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnKontakt.setContentAreaFilled(false);
btnKontakt.setBorder(null);
btnKontakt.setBorderPainted(false);
btnKontakt.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnKontakt.setForeground(Color.WHITE);
btnKontakt.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Phone_32px.png")));
btnKontakt.setBounds(16, 231, 112, 30);
panelLeft.add(btnKontakt);
JPanel panelTop = new JPanel();
panelTop.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent arg0) {
int x = arg0.getXOnScreen(); // makes uggerhøj picture dragable
int y = arg0.getYOnScreen(); // makes uggerhøj picture dragable
Main.this.setLocation(x - xx, y - xy); // makes uggerhøj picture dragable
}
});
panelTop.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
xx = e.getX(); // makes uggerhøj picture dragable
xy = e.getY(); // makes uggerhøj picture dragable
}
});
panelTop.setBackground(new Color(51, 51, 51));
panelTop.setBounds(0, 0, 737, 60);
contentPane.add(panelTop);
panelTop.setLayout(null);
JButton btnX = new JButton("X");
btnX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnX.setRolloverIcon(null);
btnX.setFont(new Font("Tahoma", Font.BOLD, 18));
btnX.setFocusTraversalKeysEnabled(false);
btnX.setFocusPainted(false);
btnX.setBorderPainted(false);
btnX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnX.setContentAreaFilled(false);
btnX.setForeground(SystemColor.activeCaption);
btnX.setBorder(null);
btnX.setBounds(615, 13, 97, 25);
panelTop.add(btnX);
parentPanel = new JPanel();
parentPanel.setBackground(Color.GRAY);
parentPanel.setBounds(148, 54, 569, 405);
contentPane.add(parentPanel);
cardLayoutObject = new CardLayout(0, 0);
parentPanel.setLayout(cardLayoutObject);
parentPanel.add(Forside, "name_1472174211097300");
Forside.setFocusable(false);
JButton btnTest = new JButton("test");
Forside.add(btnTest);
parentPanel.add(Dagbog, "name_1472176236196000");
JLabel lblTest = new JLabel("dagbog");
Dagbog.add(lblTest);
parentPanel.add(Aftaler, "name_1472177885026100");
parentPanel.add(Kontakt, "name_1472179607862700");
}
private CardLayout cardLayoutObject;
private JPanel parentPanel;
private void setCardLayoutView(String viewName) {
cardLayoutObject.show(parentPanel, viewName);
}
}
and happy coding ^-^.
I am making a program which will open a class GUI called "Menu" when correct login info is put into a text field password field and a button called "login" is pressed. The problem is that the Menu window will open blank, not displaying what I have programmed into the Menu.
This is my code for Login class,
package ems;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.SystemColor;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login extends JFrame implements ActionListener{
private JFrame loginFrame;
private JTextField usernameField;
private JPasswordField passwordField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.loginFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
loginFrame = new JFrame();
loginFrame.setTitle("Login");
loginFrame.setBounds(100, 100, 450, 300);
loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginFrame.getContentPane().setLayout(null);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(112, 116, 74, 16);
loginFrame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(112, 165, 74, 16);
loginFrame.getContentPane().add(lblPassword);
usernameField = new JTextField();
usernameField.setBounds(198, 110, 134, 28);
loginFrame.getContentPane().add(usernameField);
usernameField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(198, 159, 134, 28);
loginFrame.getContentPane().add(passwordField);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String uname = usernameField.getText();
String pword = passwordField.getText();
if (uname.equals("test") && pword.equals("test")){
JOptionPane.showMessageDialog(loginFrame, "Login successful.");
loginFrame.setVisible(false);
Menu menu = new Menu ();
menu.setVisible (true);
}else{
JOptionPane.showMessageDialog(loginFrame, "Login unsuccessful.");
}
}
});
btnLogin.setBounds(238, 210, 90, 30);
loginFrame.getContentPane().add(btnLogin);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(108, 210, 90, 30);
loginFrame.getContentPane().add(btnExit);
JPanel panel = new JPanel();
panel.setBackground(new Color(192, 192, 192));
panel.setBounds(91, 86, 258, 163);
loginFrame.getContentPane().add(panel);
JLabel lblLoginToThe = new JLabel("LOGIN TO THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(26, 23, 418, 16);
loginFrame.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
loginFrame.getContentPane().add(panel_1);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
This is the code for the Menu class,
package ems;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import ems.Login;
public class Menu extends Login implements ActionListener{
private JFrame menuFrame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.menuFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
menuFrame = new JFrame();
menuFrame.setTitle("Menu");
menuFrame.setBounds(100, 100, 450, 300);
menuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menuFrame.getContentPane().setLayout(null);
JLabel lblLoginToThe = new JLabel("THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(64, 22, 331, 16);
menuFrame.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
menuFrame.getContentPane().add(panel_1);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
menuFrame.setVisible(false);
Login login = new Login ();
login.setVisible(true);
}
});
btnLogout.setBounds(307, 222, 117, 29);
menuFrame.getContentPane().add(btnLogout);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(10, 222, 117, 29);
menuFrame.getContentPane().add(btnExit);
}
}
Both of these classes are under a package called ems.
I am very new to programming and help would be greatly appreciated.
Thank you
You are creating another JFrame inside of Login and Menu, which is wrong, theres also no need that Menu extends Login
Here is the fixed version for Login:
package ems;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField usernameField;
private JPasswordField passwordField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
this.setTitle("Login");
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(112, 116, 74, 16);
this.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(112, 165, 74, 16);
this.getContentPane().add(lblPassword);
usernameField = new JTextField();
usernameField.setBounds(198, 110, 134, 28);
this.getContentPane().add(usernameField);
usernameField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(198, 159, 134, 28);
this.getContentPane().add(passwordField);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String uname = usernameField.getText();
String pword = passwordField.getText();
if (uname.equals("test") && pword.equals("test")){
JOptionPane.showMessageDialog(Login.this, "Login successful.");
Login.this.setVisible(false);
Menu menu = new Menu ();
menu.setVisible (true);
}else{
JOptionPane.showMessageDialog(Login.this, "Login unsuccessful.");
}
}
});
btnLogin.setBounds(238, 210, 90, 30);
this.getContentPane().add(btnLogin);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(108, 210, 90, 30);
this.getContentPane().add(btnExit);
JPanel panel = new JPanel();
panel.setBackground(new Color(192, 192, 192));
panel.setBounds(91, 86, 258, 163);
this.getContentPane().add(panel);
JLabel lblLoginToThe = new JLabel("LOGIN TO THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(26, 23, 418, 16);
this.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
this.getContentPane().add(panel_1);
}
}
And for Menu
package ems;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Menu extends JFrame{
private static final long serialVersionUID = 1L;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
this.setTitle("Menu");
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
JLabel lblLoginToThe = new JLabel("THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(64, 22, 331, 16);
this.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
this.getContentPane().add(panel_1);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Menu.this.setVisible(false);
Login login = new Login ();
login.setVisible(true);
}
});
btnLogout.setBounds(307, 222, 117, 29);
this.getContentPane().add(btnLogout);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(10, 222, 117, 29);
this.getContentPane().add(btnExit);
}
}
Still looking, but:
menuFrame.getContentPane().add(lblLoginToThe);
The content pane isn't a container, you can't add multiple things to it. You need to put everything in a panel (note panel != pane) and then add one panel to the content pane.
Also don't call setBounds() directly, use a layout manager. That's another reason you could be seeing nothing: all your components are drawn outside of the window or some other similar error. Layout managers will fix that.
EDIT: And as Edwardth said you have a habit of declaring your classes to be a thing (like JFrame) and then creating a second JFrame inside the initialize method. Don't do that.
public class Login extends JFrame implements ActionListener{
...
private void initialize() {
loginFrame = new JFrame(); // BAD!
The JFrame was already made when you declared that Login extends JFrame you don't need a second frame.
Edwardth got the answer before me so go ahead and study his example and then mark his answer correct. Ask in the comments below if you have further questions.
Here's my example of the Login class, without the setBounds().
class Login extends JFrame implements ActionListener{
private JTextField usernameField;
private JPasswordField passwordField;
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
setTitle("Login");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblUsername = new JLabel("Username");
JLabel lblPassword = new JLabel("Password");
usernameField = new JTextField();
usernameField.setColumns(10);
passwordField = new JPasswordField();
JPanel loginPanel = new JPanel( new GridLayout( 0,2 ) );
loginPanel.add( lblUsername );
loginPanel.add( usernameField );
loginPanel.add( lblPassword );
loginPanel.add( passwordField );
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String uname = usernameField.getText();
String pword = passwordField.getText();
if (uname.equals("test") && pword.equals("test")){
JOptionPane.showMessageDialog( Login.this, "Login successful.");
setVisible(false);
Menu menu = new Menu ();
menu.setVisible (true);
}else{
JOptionPane.showMessageDialog( Login.this, "Login unsuccessful.");
}
}
});
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JPanel panel = new JPanel();
panel.setBackground(new Color(192, 192, 192));
panel.add( btnLogin );
panel.add( btnExit );
JLabel lblLoginToThe = new JLabel("LOGIN TO THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.add( lblLoginToThe );
Box topBox = Box.createVerticalBox();
topBox.add( panel_1 );
topBox.add( loginPanel );
topBox.add( panel );
add( topBox );
pack();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
And the Main class:
class Menu extends JFrame {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
setTitle("Menu");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box topBox = Box.createVerticalBox();
JLabel lblLoginToThe = new JLabel("THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
topBox.add( lblLoginToThe ); // **********
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
topBox.add( panel_1 ); // *************
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Menu.this.setVisible(false);
Login login = new Login ();
login.setVisible(true);
}
});
topBox.add( btnLogout ); //****************
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
topBox.add( btnExit );
add( topBox );
pack();
}
}
I m creating a GUI in java and would like to use a JTextArea, however I am having a lot of trouble adding it to the frame. How would I go about creating a text Area and then using it to read text or display text?
Here is my GUI code so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class addMemoUI extends JFrame {
JFrame frame = new JFrame();
/**
* Create the application.
*/
public addMemoUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame.getContentPane().setBackground(new Color(255, 255, 255));
frame.getContentPane().setLayout(null);
JButton button = new JButton("Create");
button.setBackground(new Color(100, 149, 237));
button.setBounds(135, 350, 130, 50);
frame.getContentPane().add(button);
JLabel lblMemos = new JLabel("MEMOS");
lblMemos.setForeground(new Color(100, 149, 237));
lblMemos.setFont(new Font("Moire", Font.BOLD, 30));
lblMemos.setBounds(22, 21, 234, 37);
frame.getContentPane().add(lblMemos);
JButton button_1 = new JButton("Cancel");
button_1.setBackground(new Color(100, 149, 237));
button_1.setBounds(5, 350, 130, 50);
frame.getContentPane().add(button_1);
frame.setBounds(100, 100, 270, 400);
frame.setUndecorated(true); //REMOVES MENU BAR
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnExit = new JButton("");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MemoUI window = new MemoUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Thanks very much :)
Here is example for how to use JTextArea. You can set, get or append text. You can find the others by google.
public class Example {
private JTextArea jtextbox;
private void initialize() {
JFrame frm = new JFrame();
:
JScrollPane scroll = new JScrollPane();
jtextbox= new JTextArea();
scroll.setViewportView(jtextbox); // add scroll panel
jtextbox.setTabSize(4);
jtextbox.setLineWrap(true);
jtextbox.setBackground(SystemColor.window);
}
private void setText(String text) {
jtextbox.append(text); // or setText(text)
}
private String getText() {
return jtextbox.getText();
}
}
I was looking in to my Java project when I realized I have yet to make my title screen. But one problem came to mind: How do I make it in where when they press on the new file button it will clear everything on the screen and put the new stuff in?
In simpler words, how to make a action listener so when they click the button the screen will clear and put a new screen on?
package Main_Config;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class SET_UP extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JLabel consol;
public static Dimension size = new Dimension(800, 700);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SET_UP frame = new SET_UP();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SET_UP() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(370, 70, 0, 0);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
setSize(size);
setLocationRelativeTo(null);
textField = new JTextField();
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input = textField.getText();
consol.setText(input);
}
});
textField.setBounds(10, 452, 243, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton enter = new JButton("Enter");
enter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
enter.setBounds(253, 452, 89, 20);
contentPane.add(enter);
JLabel consol = new JLabel("");
consol.setBounds(0, 483, 335, 189);
contentPane.add(consol);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(352, 451, 200, 23);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("New button");
btnNewButton_1.setBounds(584, 451, 200, 23);
contentPane.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("New button");
btnNewButton_2.setBounds(0, 0, 89, 23);
contentPane.add(btnNewButton_2);
}
}
To clear the screen, I do this:
Button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
frame.remove(panelTwo);
frame.remove(panelThree);
frame.add(panelFour);
frame.setVisible(true);
}
});
What I am trying to do is this,
when I enter the details it will validate if the textFiled is empty when a button is pressed, if it is empty it will display a message saying that.
Then it will move to the next textFile similar to many web based registration forms,
what I am trying to find out is why wont the message change?
Pasting this code into an ecilpse file and running it should display the simple frame and what I am trying to do.
The message displays on the bottom of the frame when the firstname field is empty,
can anyone explain why it doesn't show the next message when the firstname field containes text and the middlename contains no text?
Most of the logic is at the bottom of the code.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Color;
import javax.swing.UIManager;
import javax.swing.JPanel;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JRadioButton;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JButton;
import javax.swing.JComboBox;
public class start {
private JFrame frame;
private JTextField tfFirstname;
private JTextField tfMiddlenames;
private JTextField tfSurname;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
start window = new start();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public start() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 505, 429);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
final JPanel panelClientNew = new JPanel();
panelClientNew.setBackground(new Color(0, 102, 255));
panelClientNew.setBounds(10, 11, 469, 299);
frame.getContentPane().add(panelClientNew);
panelClientNew.setLayout(null);
JLabel lblFirstname = new JLabel("Firstname :");
lblFirstname.setHorizontalAlignment(SwingConstants.RIGHT);
lblFirstname.setVerticalAlignment(SwingConstants.BOTTOM);
lblFirstname.setForeground(new Color(255, 255, 255));
lblFirstname.setFont(new Font("Tahoma", Font.BOLD, 13));
lblFirstname.setBounds(10, 16, 163, 14);
panelClientNew.add(lblFirstname);
tfFirstname = new JTextField();
tfFirstname.setFont(new Font("Tahoma", Font.PLAIN, 13));
tfFirstname.setBounds(177, 10, 282, 27);
panelClientNew.add(tfFirstname);
tfFirstname.setColumns(10);
JLabel lblMiddlenames = new JLabel("Middlenames :");
lblMiddlenames.setHorizontalAlignment(SwingConstants.RIGHT);
lblMiddlenames.setForeground(new Color(255, 255, 255));
lblMiddlenames.setFont(new Font("Tahoma", Font.BOLD, 13));
lblMiddlenames.setBounds(10, 47, 163, 14);
panelClientNew.add(lblMiddlenames);
tfMiddlenames = new JTextField();
tfMiddlenames.setFont(new Font("Tahoma", Font.PLAIN, 13));
tfMiddlenames.setBounds(177, 41, 282, 27);
panelClientNew.add(tfMiddlenames);
tfMiddlenames.setColumns(10);
JLabel lblSurname = new JLabel("Surname :");
lblSurname.setHorizontalAlignment(SwingConstants.RIGHT);
lblSurname.setForeground(new Color(255, 255, 255));
lblSurname.setFont(new Font("Tahoma", Font.BOLD, 13));
lblSurname.setBounds(10, 78, 163, 14);
panelClientNew.add(lblSurname);
tfSurname = new JTextField();
tfSurname.setFont(new Font("Tahoma", Font.PLAIN, 13));
tfSurname.setBounds(177, 72, 282, 27);
panelClientNew.add(tfSurname);
tfSurname.setColumns(10);
JButton btnAdd = new JButton("Add");
btnAdd.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent arg0) {
/*
*
*
*
*I am trying to create a message that validates on certain circumstances
*
*
*
*/
if(tfFirstname.getText().equals(null) || tfFirstname.getText().equals("") || tfFirstname.getText().equals(false)) {
JPanel panelMessage = new JPanel();
panelMessage.setBackground(new Color(30, 144, 255));
panelMessage.setBounds(10, 321, 469, 29);
frame.getContentPane().add(panelMessage);
JLabel lblPersonSaved = new JLabel("Please Enter Firstname :");
lblPersonSaved.setForeground(new Color(255, 255, 255));
lblPersonSaved.setFont(new Font("Tahoma", Font.BOLD, 15));
panelMessage.add(lblPersonSaved);
frame.revalidate();
panelMessage.revalidate();
frame.repaint();
}
else if (tfMiddlenames.getText().equals(null) || tfMiddlenames.getText().equals("") || tfMiddlenames.getText().equals(false)) {
JPanel panelMessage = new JPanel();
panelMessage.setBackground(new Color(30, 144, 255));
panelMessage.setBounds(10, 321, 469, 29);
frame.getContentPane().add(panelMessage);
JLabel lblPersonSaved = new JLabel("Please Enter Middlenames :");
lblPersonSaved.setForeground(new Color(255, 255, 255));
lblPersonSaved.setFont(new Font("Tahoma", Font.BOLD, 15));
panelMessage.add(lblPersonSaved);
frame.revalidate();
panelMessage.revalidate();
frame.repaint();
}
else if (tfSurname.getText().equals(null) || tfSurname.getText().equals("") || tfSurname.getText().equals(false)) {
JPanel panelMessage = new JPanel();
panelMessage.setBackground(new Color(30, 144, 255));
panelMessage.setBounds(10, 321, 469, 29);
frame.getContentPane().add(panelMessage);
JLabel lblPersonSaved = new JLabel("Please Enter Surname :");
lblPersonSaved.setForeground(new Color(255, 255, 255));
lblPersonSaved.setFont(new Font("Tahoma", Font.BOLD, 15));
panelMessage.add(lblPersonSaved);
frame.revalidate();
panelMessage.revalidate();
frame.repaint();
}
else {
//Validation has passed
}
}
});
btnAdd.setBounds(370, 265, 89, 23);
panelClientNew.add(btnAdd);
}
}
I recommend that you use an InputVerifier as this will verify that the contents of the JTextField are correct (any way that you wish to define this) before allowing you to even leave the JTextField. Now it won't stop you from pressing other JButtons and whatnot, so you'll need to take other precautions if you have a submit button. An example of a simple InputVerifier that checks to see if the JTextField is empty is shown below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class InputVerifierExample extends JPanel {
public static final Color WARNING_COLOR = Color.red;
private JTextField firstNameField = new JTextField(10);
private JTextField middleNameField = new JTextField(10);
private JTextField lastNameField = new JTextField(10);
private JTextField[] nameFields = {
firstNameField,
middleNameField,
lastNameField };
private JLabel warningLabel = new JLabel(" ");
public InputVerifierExample() {
warningLabel.setOpaque(true);
JPanel namePanel = new JPanel();
namePanel.add(new JLabel("Name:"));
MyInputVerifier verifier = new MyInputVerifier();
for (JTextField field : nameFields) {
field.setInputVerifier(verifier);
namePanel.add(field);
}
namePanel.add(new JButton(new SubmitBtnAction()));
setLayout(new BorderLayout());
add(namePanel, BorderLayout.CENTER);
add(warningLabel, BorderLayout.SOUTH);
}
private class SubmitBtnAction extends AbstractAction {
public SubmitBtnAction() {
super("Submit");
}
#Override
public void actionPerformed(ActionEvent e) {
// first check all fields aren't empty
for (JTextField field : nameFields) {
if (field.getText().trim().isEmpty()) {
return; // return if empty
}
}
String name = "";
for (JTextField field : nameFields) {
name += field.getText() + " ";
field.setText("");
}
name = name.trim();
JOptionPane.showMessageDialog(InputVerifierExample.this, name, "Name Entered",
JOptionPane.INFORMATION_MESSAGE);
}
}
private class MyInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
JTextField field = (JTextField) input;
if (field.getText().trim().isEmpty()) {
warningLabel.setText("Please do not leave this field empty");
warningLabel.setBackground(WARNING_COLOR);
return false;
}
warningLabel.setText("");
warningLabel.setBackground(null);
return true;
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("InputVerifier Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new InputVerifierExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
have look at DocumentListener,
on start_up to enable only first JTextField, if any (up to you) character was typed into first JTextField, then enable second JTextField, and so on...,
if you want to filtering, change or replace output came from keyboard the to use DocumentFilter
change background for example to Color.red (from DocumentListeners events), in the case that one of JTextFields contains incorect lenght, data e.g.
agree with HFOE about LayoutManagers