PictureCount does not change - java

the code is used to create an application which shows picture and if your anwser is correct your supposed to see the next picture but the pictureCount does not go up. all of the variables ar declared after the main class and i created an Actionlistener to check if the awnser is correct.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
public static void main(String[] args) {new Main().test();}
public int pictureCount = 1;
JFrame frame = new JFrame();
JButton button1 = new JButton("Submit");
JTextField text = new JTextField();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JLabel label = new JLabel(new ImageIcon("C:\\Users\\Admin\\Desktop\\practicum 3\\" + pictureCount + ".jpg"));
void test(){
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if(text.getText().equals("5")){
pictureCount++;
new Main().test();
}
}
});
panel1.add(button1);
panel2.add(text);
panel3.add(label);
text.setPreferredSize(new Dimension(100,50));
panel1.setPreferredSize(new Dimension(1000, 200));
panel2.setPreferredSize(new Dimension(1000, 100));
panel3.setPreferredSize(new Dimension(1000, 450));
frame.getContentPane().add(BorderLayout.SOUTH, panel1);
frame.getContentPane().add(BorderLayout.CENTER, panel2);
frame.getContentPane().add(BorderLayout.NORTH, panel3);
frame.setSize(1000,750);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Operation Screen");
frame.setLocationRelativeTo(null);
}
}

You need to read in all the pictures as ImageIcons into an array or ArrayList, say called imageIconArray and then display imageIconArray[0] in your JLabel when you start.
When the button is pressed, increment pictureCount, and then reset the JLabel's icon via its setIcon(...) method:
// in the ActionListener code:
pictureCount++;
label.setIcon(imageIconArray[pictureCount];
Whatever you do, don't create a new Main object, despite what others might say. Why create a new GUI when all you need to do is swap displayed images?

Related

Is it possible to erase text in two separate TextFields depening on which one is clicked using one MouseListener?

I have two JTextFields with text and a MouseListener:
JTextField tf1 = new JTextField("Input your text here: ");
JTextField tf2 = new JTextField("Input your pattern here: ");
tf1.addMouseListener(mm);
tf2.addMouseListener(mm);
I want to erase text in the TextField that I clicked using MouseListener:
MouseListener mm = new MouseAdapter(){
public void mouseClicked(MouseEvent e){
tf1.setText("");
//tf2.setText("");
}
};
Nevertheless I can only manage to erase both or only one. I could add one more MouseListener, but I am curious if it is possible to create such MouseListener that erases text depending on the TextField I clicked.
Try this, it will erase based on mouse click the TextField(s).
import javax.swing.*;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.*;
public class JFrameTest{
public static void main(String[] args){
JFrame frame= new JFrame();
frame.setTitle("JFrame");
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints constr = new GridBagConstraints();
constr.gridx=0;
constr.gridy=0;
JTextField txt1 = new JTextField(20);
txt1.setText("abc");
JTextField txt2= new JTextField(20);
txt2.setText("efg");
constr.gridx=1;
panel.add(txt1, constr);
constr.gridy=1;
panel.add(txt2, constr);
MouseListener mm = new MouseAdapter(){
public void mouseClicked(MouseEvent e){
//System.out.println(e);
//System.out.println(e.getSource());
//be sure to have the component in case that listener is added on more objs
if(e.getSource() instanceof JTextField)
{
//set whatever you wanted on each TF individualy
((JTextField)e.getSource()).setText("");
}
}
};
//add the same listener on both but process on each as click
txt1.addMouseListener(mm);
txt2.addMouseListener(mm);
mainPanel.add(panel);
frame.add(mainPanel);
frame.pack();
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Is there an option to add ScrollPane without disabling CardLayout?

I have a card layout where I switch panels with a button. However, the code (switching panels) works only when lines:
JScrollPane scrPane = new JScrollPane(card1);
frame.add(scrPane);
are removed. In other case, clicking button achieves nothing. Is there an option to keep the scrolling (I need this, since the main application will have a lot of wrapped text) without disabling an option to switch cards?
package com.code;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.event.*;
public class Card {
public static void main(String[] args) {
JFrame frame = new JFrame("App");
frame.setVisible(true);
frame.setSize(1200, 800);//Give it a size
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel mainPanel = new JPanel(new CardLayout());
frame.add(mainPanel);
JPanel menu = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel card1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel card2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
mainPanel.add(menu, "menu");
mainPanel.add(card1, "card1");
mainPanel.add(card2, "card2");
JLabel l1 = new JLabel("label 1");
JLabel l2 = new JLabel("label 2");
card1.add(l1);
card2.add(l2);
JButton click = new JButton("Click!");
menu.add(click);
JScrollPane scrPane = new JScrollPane(card1);
frame.add(scrPane);
click.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) mainPanel.getLayout();
cardLayout.show(mainPanel, "card1");
}
});
}
}
A JFrame (its content pane) uses BorderLayout by default. That means you can have only 1 component at BorderLayout.CENTER. When you frame.add(component) the default constraints is BorderLayout.CENTER.
Now, you frame.add(mainPanel); and then frame.add(scrPane);. So main panel is removed, since scrPane is being added after it.
Doing JScrollPane scrPane = new JScrollPane(card1); it means you add a scrollpane to card1, and not in content pane. I guess that you want it to the content pane (the whole frame). So the fix is to delete frame.add(mainPanel); and do the following:
JScrollPane scrPane = new JScrollPane(mainPanel);
frame.add(scrPane);
Now, the main panel is added to scrPane and scrPane is added to the frame.
However, your GUI will be empty after that, because you frame.setVisible(true); before you are finished adding components to it. Take a look at Why shouldn't I call setVisible(true) before adding components?
Eventually, full code is:
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("App");
frame.setSize(1200, 800);//Give it a size
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel mainPanel = new JPanel(new CardLayout());
JPanel menu = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel card1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel card2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
mainPanel.add(menu, "menu");
mainPanel.add(card1, "card1");
mainPanel.add(card2, "card2");
JLabel l1 = new JLabel("label 1");
JLabel l2 = new JLabel("label 2");
card1.add(l1);
card2.add(l2);
JButton click = new JButton("Click!");
menu.add(click);
JScrollPane scrPane = new JScrollPane(mainPanel);
frame.add(scrPane);
click.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) mainPanel.getLayout();
cardLayout.show(mainPanel, "card1");
}
});
frame.setVisible(true);
});
}
Some good links I suggest you to read are the Initial Threads and What does .pack() do?

Can't position Buttons or JLabels

I am new to working with GUI's in Java and I am having a problem moving my text and buttons around. No matter what coordinates I give my button or any of the other JLabel it doesn't move, I was wondering how I could fix it this in such a way that I can place my components where ever I want on the JPanel
public class IntroPage extends JFrame {
public static void main(String[] args) {
IntroPage main = new IntroPage();
main.setVisible(true);
}
private JPanel contentPane;
public IntroPage (){
//make sure the program exits when the frame closes
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Welcome");
contentPane = new JPanel();
setSize(400,700);
//This will center the JFrame in the middle of the screen
setLocationRelativeTo(null);
//Welcome Page stuff :D
JLabel ApplauseLabel = new JLabel("Welcome to U.X.Dot.X");
ApplauseLabel.setFont(new Font("Gill Sans MT", Font.PLAIN, 30));
ApplauseLabel.setLocation(100, 50);
contentPane.add(ApplauseLabel);
JLabel slogan = new JLabel("Register below");
slogan.setFont(new Font("Gill Sans MT", Font.PLAIN, 15));
slogan.setLocation(100, 400);
contentPane.add(slogan);
//FacebookSignUp.
JButton FBbutton = new JButton("Login With FaceBook");
FBbutton.setBackground(Color.BLUE);
FBbutton.setSize(50,50);
FBbutton.setLocation(20, 40);
FBbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Add JPanel to go to FB API. Much later
}
});
contentPane.add(FBbutton);
add(contentPane);
//make sure the JFrame is visible
setVisible(true);
}
}
You're ignoring the layout managers of your contentPane JPanel. Understand that it uses FlowLayout by default, and will ignore your setLocation and setBounds statements. Ror the JPanel to accept absolute positioning, you would have to give it a null layout via contentPane.setLayout(null).
Having said that, I do not advise you to do this! While null layouts, setLocation(...) and setBounds(...) might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
For example the following GUI
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import javax.swing.*;
public class IntroPage2 extends JPanel {
public static final String TITLE = "Welcome to U.X.Dot.X";
private JLabel welcomeLabel = new JLabel(TITLE, SwingConstants.CENTER);
private JButton fbButton = new JButton("Login With Facebook");
public IntroPage2() {
fbButton.setBackground(Color.BLUE);
fbButton.setForeground(Color.CYAN);
welcomeLabel.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 30));
int wlGap = 20;
welcomeLabel.setBorder(BorderFactory.createEmptyBorder(wlGap, wlGap, wlGap, wlGap));
JLabel registerBelowLabel = new JLabel("Register Below");
registerBelowLabel.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
JPanel centralPanel = new JPanel(new GridBagLayout());
centralPanel.setPreferredSize(new Dimension(300, 600));
centralPanel.add(registerBelowLabel);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(fbButton, BorderLayout.LINE_START);
topPanel.add(welcomeLabel, BorderLayout.CENTER);
setLayout(new BorderLayout());
int ebGap = 8;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
add(topPanel, BorderLayout.PAGE_START);
add(centralPanel, BorderLayout.CENTER);
}
private static void createAndShowGui() {
IntroPage2 mainPanel = new IntroPage2();
JFrame frame = new JFrame("Welcome");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
would create something like:

JButtons not appearing on my JFrame

I am making a program that includes a GUI. For some reason, the JButton objects that I have created are not showing up onto my JFrame when I run the program. Here is the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ReverseAStringMain extends JPanel {
private JButton enterButton, exitButton;
private JTextField textField;
private JPanel buttonPanel;
private JTextArea textArea;
public ReverseAStringMain(){
JButton enterButton = new JButton("Enter");
JButton exitButton = new JButton("Exit");
enterButton.setPreferredSize(new Dimension(60,60));
exitButton.setPreferredSize(new Dimension(60,60));
ButtonListener listener = new ButtonListener();
enterButton.addActionListener(listener);
exitButton.addActionListener(listener);
buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(200,50));
buttonPanel.setBackground(Color.black);
buttonPanel.add(enterButton);
buttonPanel.add(exitButton);
textField = new JTextField();
textField.setSize(200, 100);
textArea = new JTextArea();
textArea.add(textField);
add(buttonPanel);
add(textField);
}
//Creating a ButtonListener class that implements the ActionListener interface
private class ButtonListener implements ActionListener{
#Override
//Overriding the ActionPerformed method of ActionListener
public void actionPerformed(ActionEvent action) {
if(action.getSource()== enterButton)
enterButton();
if(action.getSource()== exitButton)
System.exit(0);
}
}
private void enterButton() {
// TODO Auto-generated method stub
}
public static void main (String[] args){
JFrame frame = new JFrame("Raj's Reverse a String Program");
frame.setBackground(Color.white);
frame.setVisible(true);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setSize(new Dimension(600,600));
//frame.pack();
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ReverseAStringMain());
}
}
If there are any problems or improvements I can make in my code, please let me know!
You're adding the components to your JFrame after it's visible. You should either add them to the JFrame before it's visible, or revalidate the JFrame after you add the components.
When I load your code (after making it a lot shorter in height), this is what I see:
I suspect this is more along the lines of what you expect to see.
Here is how I did it. Look carefully at:
The numbers provided to the BorderLayout constructor for white space between the panels.
The EmptyBorder for white space around the controls.
The use of pack() to shrink the GUI to the natural size.
The use of size hints in the construction of the text field and text area.
The use of a second layout - commonly known as a combined, or nested, layout.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ReverseAStringMain extends JPanel {
private JButton enterButton, exitButton;
private JTextField textField;
private JPanel pageTopPanel;
private JTextArea textArea;
public ReverseAStringMain(){
super(new BorderLayout(10,10));
setBorder(new EmptyBorder(5,15,5,15));
JButton enterButton = new JButton("Enter");
JButton exitButton = new JButton("Exit");
pageTopPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
pageTopPanel.setBackground(Color.black);
pageTopPanel.add(enterButton);
pageTopPanel.add(exitButton);
textField = new JTextField(5);
pageTopPanel.add(textField);
textArea = new JTextArea(4,40);
add(pageTopPanel, BorderLayout.PAGE_START);
add(textArea); // defaults to CENTER
}
public static void main (String[] args){
Runnable r = new Runnable() {
public void run() {
JFrame frame = new JFrame("XXX's Laid out Program");
frame.setBackground(Color.white);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ReverseAStringMain());
frame.pack();
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
General Tips
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them1, along with layout padding & borders for white space2.
Generally, you want to set the frame visible After adding components
JFrame frame = new JFrame("Raj's Reverse a String Program");
frame.setBackground(Color.white);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setSize(new Dimension(600,600));
//frame.pack();
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ReverseAStringMain());
frame.setVisible(true); <<------
Also, it is better practice to use .pack() insteack of .setSize(), so you had it right in the commented out //.pack()
If you wanted to set a size to the panel, you would override the getPreferredSize() like this
public Dimension getPreferredSize() {
return new Dimension(300, 300); // or whatever size you want
}
When you .pack(), this preferred size will be respected by the frame.
Also, not, setting the size of the JTextField won't work. What you want to do is pass it an integer value for the number of character spaces, like this
textField = new JTextField(20);
See an edited version of your program, with all the above mentioned points. One thing I also did was get rid of all your .setPreferredSizes. You will see the difference
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ReverseAStringMain extends JPanel {
private JButton enterButton, exitButton;
private JTextField textField;
private JPanel buttonPanel;
private JTextArea textArea;
public ReverseAStringMain() {
JButton enterButton = new JButton("Enter");
JButton exitButton = new JButton("Exit");
//enterButton.setPreferredSize(new Dimension(60, 60));
//exitButton.setPreferredSize(new Dimension(60, 60));
ButtonListener listener = new ButtonListener();
enterButton.addActionListener(listener);
exitButton.addActionListener(listener);
buttonPanel = new JPanel();
//buttonPanel.setPreferredSize(new Dimension(200, 50));
buttonPanel.setBackground(Color.black);
buttonPanel.add(enterButton);
buttonPanel.add(exitButton);
textField = new JTextField(20);
//textField.setSize(200, 100); /// <<-----------
textArea = new JTextArea();
textArea.add(textField);
add(buttonPanel);
add(textField);
}
public Dimension getPreferredSize() {
return new Dimension(600, 600);
}
// Creating a ButtonListener class that implements the ActionListener
// interface
private class ButtonListener implements ActionListener {
#Override
// Overriding the ActionPerformed method of ActionListener
public void actionPerformed(ActionEvent action) {
if (action.getSource() == enterButton)
enterButton();
if (action.getSource() == exitButton)
System.exit(0);
}
}
private void enterButton() {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
JFrame frame = new JFrame("Raj's Reverse a String Program");
frame.setBackground(Color.white);
frame.getContentPane().add(new ReverseAStringMain());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Have a look at the Swing tutorial trail for more information on creating GUIs with Swing.
Try to add the buttonPanel to a Container, like this. And extend JFrame instead
Container contentpane = getContentPane();
contentPane.add(buttonPanel);

In a basic GUI, I can only see the frame

This is the information for what I think is a correct basic GUI, but only the frame is showing up. I don't know why this is. I have everything initialized and set to visible and added, but it acts like nothing is added. Thanks for the help!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class basicButtonPress
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton();
JLabel label = new JLabel();
frame = new JFrame("Test Pop - Up");
frame.setVisible(true);
frame.setSize(600,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
panel = new JPanel();
panel.setBackground(Color.YELLOW);
panel.add(button);
panel.add(label);
button = new JButton("Test");
label = new JLabel("This is test label");
}
}
You're calling new JFrame() twice; same with JPanel, JButton and JLabel. Remove the duplicates and you'll be closer to fixing the problem.

Categories