Scrollbar not scrolling - java

I have a program that is designed simply to make and test a user interface. The current setup is that it displays a large black screen with text, and a box for user input at the bottom, and a scrollbar on the right side. I've got everything working the way I want it except that the scrollbar absolutely will not scroll. It is there, but doesn't seem connected at all to the textarea. You can press the buttons on the bar, but they don't do anything. Any help would be appreciated!
Here is the code I have so far:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class RandomTest extends JFrame implements KeyListener{
JPanel panel = new JPanel();
JScrollPane scrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JFrame frame = new JFrame();
static JTextArea txt;
static JTextField inputField;
static String text;
static String choice;
static boolean enter = false;
Container positioner = frame.getContentPane();
RandomTest(){
text = "";
txt = new JTextArea(text);
txt.setEditable(false);
inputField = new JTextField("");
txt.setBackground(Color.black);
txt.setFont(new Font("Courier New", Font.PLAIN, 18));
txt.setForeground(Color.lightGray);
inputField.setBackground(Color.black);
inputField.setFont(new Font("Courier New", Font.PLAIN, 18));
inputField.setForeground(Color.lightGray);
panel.add(txt);
panel.add(inputField);
//Dimension d = new Dimension(500,500);
//scrollPane.setPreferredSize(d);
panel.add(scrollPane);
frame.add(panel);
frame.setSize(500,500);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
positioner.setLayout(new BorderLayout());
positioner.add(inputField, BorderLayout.PAGE_END);
positioner.add(scrollPane, BorderLayout.EAST);
positioner.add(txt, BorderLayout.CENTER);
positioner.setBackground(Color.black);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
inputField.addKeyListener(this);
}
public static void main(String[] arg){
new RandomTest();
println("Please enter the letter 'm'");
for(;;){
println("/\n/\n/\n/\n/\n/\n/\n/\n");
if(input().equals("m")){
println("Thank you.");
}else{
println("Try again.");
}
}
}
public static void println(String line){
text += line + "\n";
txt.setText(text);
}
public static String input(){
for(;;){
if(enter == true){
enter = false;
return choice;
}else{
try {
Thread.sleep(10);
} catch (InterruptedException e) {
if(enter == true){
enter = false;
return choice;
}
}
}
}
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
choice = inputField.getText();
inputField.setText("");
enter = true;
try{
Thread.currentThread().interrupt();
}catch(Exception E){
}
}
}
#Override
public void keyTyped(KeyEvent e) {
}
}

There's nothing attached to the scroll pane's view, so there is nothing for it to scroll...
You need to supply a component view for the scroll, using something like scrollPane.setViewportView(...);
You may want to take a look at How to use scroll panes for some more details
There's a lot of things in you code that worry me...
Thread.sleep in a GUI environment is always of concern, given that this could actually cause your application to become unresponsive. The use of infinite loops, for the same reason.
The use of KeyListener which is simply performing the same function of an ActionListener
The fact that you are adding txt and inputField and scrollPane to two different containers and txt is actually supplementing panel...
You may like to spend some time reading through
Creating a GUI With JFC/Swing
Using Text Components
How to Write an Action Listener
Concurrency in Swing

Related

Update jPanel background color when a button is pressed

I'm just starting with Java and I wanted to make a little program that opens a jFrame with a text field in which you can write a number. Then you press a button and another jFrame with a jPanel, which will turn green if the number is even, and black if it's odd. I edited the code of the jPanel so that the color changes depending on the number, but the problem is that it will only work once. If I write "2" and press the button, the jFrame will appear with a green panel, but then if I write another odd number and press it again, the frame will stay green.
How could I solve this so that the background color changes whenever I press the button? I should also say that I made an "if-else", so that you could only open the second jFrame once because I didn't know how to make it close and then open again, so maybe that has to do with the problem. Thanks!
This is the code in the Panel. To make it easier, I tried to just turn it green if a zero was introduced, and now it doesn't even work:
jPanel1 = new javax.swing.JPanel();
if ("0".equals(Taller2.opcion)) {
jPanel1.setBackground(new java.awt.Color(0, 255, 0));
}
else {
jPanel1.setBackground(new java.awt.Color(0, 0, 0));
}
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
// Code of sub-components - not shown here
// Layout setup code - not shown here
// Code adding the component to the parent container - not shown here
Here is the pretty basic main class:
public class Taller2 {
/**
* #param args the command line arguments
*/
public static String opcion;
public static boolean panelabierto;
public static void main(String[] args) {
Pregunta a = new Pregunta();
a.setVisible(true);
opcion = null;
panelabierto = false;
}
}
The second jFrame (the one with the jPanel inside) only has the basic code generated by Netbeans on the designer. If you need the code for the jFrame with the text field, I could add it too, although I believe the problem lies within the jPanel.
Don't create more instances of JPanel, simply create one and change it's state.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
JFormattedTextField field = new JFormattedTextField(NumberFormat.getInstance());
field.setColumns(4);
setLayout(new GridBagLayout());
add(field);
field.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
long value = (Long)field.getValue();
if ((value % 2) == 0) {
setBackground(Color.GREEN);
} else {
setBackground(Color.RED);
}
}
});
setBackground(Color.BLACK);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Are you sure your code is correct? My best guess (without you providing your code) is that your code for checking whether the number is odd or even does not work correctly.
The best way to determine whether a number is odd or even in Java is to use the modulus (%) operator:
if ((num%2)==0) {
// Number is even
} else {
// Number is odd
}
(Replace "num" with the number you want to test.)

Toggle visibility of a JComponent Swing

I am trying to toggle visibility of a JTextField with a checkbox. If the checkbox is selected I want the JTextField to be displayed and vice-versa. My program works fine until I add the line that initializes the JTextField to be invisible at the start. If I remove this the segment works fine! Can you help me?
final JCheckBox chckbxNewCheckBox_1 = new JCheckBox("New Folder");
panel_3.add(chckbxNewCheckBox_1);
final JTextField textField_3 = new JTextField();
panel_3.add(textField_3);
textField_3.setColumns(20);
//textField_3.setVisible(false); if a comment it in.. it never becomes visible
chckbxNewCheckBox_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
if(chckbxNewCheckBox_1.isSelected()){
textField_3.setVisible(true);
}
else
textField_3.setVisible(false);
}
});
Try with ActionListener instead of MouseListener
checkBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
textField_3.setVisible(checkBox.isSelected());
}
});
--EDIT--
call panel_3.revalidate(); after changing its visibility.
When an element is invisible during container initialization, it never gets its dimensions initialized. You can check it by calling getWidth() and getHeight() on the text area after you set it to visible. They're both zero. So follow #Braj edit and call panel.revalidate() after you change element visibility to let layout manager know that it's time to reposition/recalculate some elements and give them proper size.
You will do better with ItemListener
chckbxNewCheckBox_1.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.DESELECTED))
textField_3.setVisible(false);
else if (e.getStateChange() == ItemEvent.SELECTED))
textField_3.setVisible(true);
textField_3.revalidate();
}
});
Note: pelase follow naming conventions and use underscores only for constants.
Consider calling pack() method
Below is the complete code I experimented with:
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
final JCheckBox chckbxNewCheckBox_1 = new JCheckBox("New Folder");
final JPanel panel_3 = new JPanel();
frame.add(panel_3);
panel_3.add(chckbxNewCheckBox_1);
final JTextField textField_3 = new JTextField();
panel_3.add(textField_3);
textField_3.setColumns(20);
textField_3.setVisible(false); //if a comment it in.. it never becomes visible
chckbxNewCheckBox_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
if (chckbxNewCheckBox_1.isSelected()) {
textField_3.setVisible(true);
} else
textField_3.setVisible(false);
frame.pack();
}
});
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

JFrame to JApplet doesnt work in browser

I have a Java program with a Swing GUI im trying to make it work as a JApplet on a HTML file when I test it on Eclipse launch it as a Applet it works but when I compile it using javac. I get all these files Reverser.class, Reverser$1.class, Reverser$2.class, Reverser$3.class and Reverser$4.class. It doesnt work an help
<HTML>
<BODY>
<applet code="Reverser.class", height="500" width="800">
</applet>
</BODY>
</HTML>
package Applets;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class Reverser extends JApplet
{
/**
*
*/
private static final long serialVersionUID = 1L;
//All Swing elements declared here
private JTextArea userinput, useroutput;
private JScrollPane sbr_userinput, sbr_useroutput;
private JButton runButton, clearButton, homeButton;
private String text; //User input stored here
private String reversed_text; //reversed text stored here
public void init()
{
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
setContentPane(GUI());
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
public Container GUI() //Main GUI container here
{
JPanel totalGUI = new JPanel(); //Main panel set here
totalGUI.setLayout(new GridLayout(1, 2, 3, 3)); //Main panel layout set here.
JPanel lPanel = new JPanel(); //Left panel made here
lPanel.setLayout(new GridLayout(2, 1, 3 , 3)); //Left panel layout set here
totalGUI.add(lPanel); // Left Panel added to main panel.
JPanel rPanel = new JPanel(new GridLayout(3, 1, 3 , 3)); //Right panel made here and its layout set here aswell
totalGUI.add(rPanel);//Right panel added to main panel.
//Userinput TextArea made here
userinput = new JTextArea("Welcome to wicky waky text reverser!!!" + "\n" + "Enter your sentence HERE man!!!!");
userinput.setEditable(true); //TextArea set to editable
userinput.setLineWrap(true);
userinput.setWrapStyleWord(true);
lPanel.add(userinput);//TextArea added to left panel
useroutput = new JTextArea(); //useroutput TextArea set here
useroutput.setEditable(false); //TextArea set to not editable
useroutput.setLineWrap(true);
useroutput.setWrapStyleWord(true);
lPanel.add(useroutput); //TextArea added to the left panel
//Scroll bar made here
sbr_userinput = new JScrollPane(userinput, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
sbr_userinput.setPreferredSize(new Dimension(300, 300));
lPanel.add(sbr_userinput); //Scroll bar added to left panel
//Scroll bar made here
sbr_useroutput = new JScrollPane(useroutput, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
sbr_useroutput.setPreferredSize(new Dimension(300, 300));
lPanel.add(sbr_useroutput); //Scroll bar added to the left panel
runButton = new JButton("RUN"); //Button made here
runButton.addActionListener(new ActionListener() //Action Listener made here
{
public void actionPerformed(ActionEvent e)
{
text = userinput.getText(); //Get userinput here
reversed_text = reverser(text); //reverser method called here
try {
userinput.setText("");
userinput.setText("Processed");
Thread.sleep(500); //sleep 0.5 sec
//Print out all output here
useroutput.setText("Your sentence is ==> " + text + "\n" + "\n"
+ "Your reversed sentence is ==> " + reversed_text);
} catch (InterruptedException e1)
{
e1.printStackTrace();
}
System.out.println("working");
}
});
rPanel.add(runButton); //Add button to right panel
clearButton = new JButton("CLEAR"); //New button made here
clearButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
userinput.setText(""); //Set userinput to empty
useroutput.setText(""); //Set useroutput to empty
System.out.println("cleared");
}
});
rPanel.add(clearButton); //Add button to right panel
homeButton = new JButton("HOME"); //New button made here
homeButton.addActionListener(new ActionListener() //Action Listener added here
{
public void actionPerformed(ActionEvent e)
{
}
});
rPanel.add(homeButton); //add button to right panel
totalGUI.setOpaque(true);
return totalGUI; // return totalGUI
}
public static String reverser(String text)
{
//"text" is now put in the object "reverse_text", StringBuffer used so I can use the reverse method.
StringBuffer reverse_text = new StringBuffer(text);
String reversed = reverse_text.reverse().toString(); //reverse and toString methods used.
return reversed; // return revered
}
}
You don't have the package name in your applet. Consider changing
code="Reverser.class"
to
code="Applets.Reverser.class"
and making sure that the class file is in the Applets subdirectory relative to the HTML file. Or even better, create a jar file.
Also you need to post the error messages that the browser is giving you. You could have a version incompatibility for all we know.

How to keep Metal L&F when dragging JToolBar

In our aplication we use Metal L&F. We are using a floatable JToolBar; it happens that when doing the drag behavior it appears with the Windows L&F.
May anyone say me how to keep Metal L&F when dragging the JToolBar?
Thanks
P.D. Our JToolBar is within a JPanel container that user BorderLayout Layout Manager.
Maybe I explained badly my question. So I post an example taken from The Java Tutorials to give anyone an idea of what happens to my application.
If you execute the following code the main JFrame appears decorated with Ocean Theme; but when I drag the JToolBar its decorated is not Ocean. What can I do??.
Many thanks in advance
package components;
/*
* ToolBarDemo.java requires the following addditional files:
* images/Back24.gif
* images/Forward24.gif
* images/Up24.gif
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.plaf.metal.OceanTheme;
public class ToolBarDemo extends JPanel
implements ActionListener {
protected JTextArea textArea;
protected String newline = "\n";
static final private String PREVIOUS = "previous";
static final private String UP = "up";
static final private String NEXT = "next";
public ToolBarDemo() {
super(new BorderLayout());
//Create the toolbar.
JToolBar toolBar = new JToolBar("Still draggable");
addButtons(toolBar);
//Create the text area used for output. Request
//enough space for 5 rows and 30 columns.
textArea = new JTextArea(5, 30);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
//Lay out the main panel.
setPreferredSize(new Dimension(450, 130));
add(toolBar, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
}
protected void addButtons(JToolBar toolBar) {
JButton button = null;
//first button
button = makeNavigationButton("Back24", PREVIOUS,
"Back to previous something-or-other",
"Previous");
toolBar.add(button);
//second button
button = makeNavigationButton("Up24", UP,
"Up to something-or-other",
"Up");
toolBar.add(button);
//third button
button = makeNavigationButton("Forward24", NEXT,
"Forward to something-or-other",
"Next");
toolBar.add(button);
}
protected JButton makeNavigationButton(String imageName,
String actionCommand,
String toolTipText,
String altText) {
//Look for the image.
String imgLocation = "images/"
+ imageName
+ ".gif";
URL imageURL = ToolBarDemo.class.getResource(imgLocation);
//Create and initialize the button.
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
if (imageURL != null) { //image found
button.setIcon(new ImageIcon(imageURL, altText));
} else { //no image found
button.setText(altText);
System.err.println("Resource not found: "
+ imgLocation);
}
return button;
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String description = null;
// Handle each button.
if (PREVIOUS.equals(cmd)) { //first button clicked
description = "taken you to the previous <something>.";
} else if (UP.equals(cmd)) { // second button clicked
description = "taken you up one level to <something>.";
} else if (NEXT.equals(cmd)) { // third button clicked
description = "taken you to the next <something>.";
}
displayResult("If this were a real app, it would have "
+ description);
}
protected void displayResult(String actionDescription) {
textArea.append(actionDescription + newline);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ToolBarDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.add(new ToolBarDemo());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setsLF();
createAndShowGUI();
}
});
}
/**
*
*/
private static void setsLF() {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
MetalLookAndFeel.setCurrentTheme(new OceanTheme());
UIManager.setLookAndFeel(new MetalLookAndFeel());
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ToolBarDemo.class.getName()).log (java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ToolBarDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ToolBarDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ToolBarDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
JFrame.setDefaultLookAndFeelDecorated(Boolean.TRUE);
return;
}
}
Looks like nowadays the toplevel container of the ripped of toolBar is of type JDialog, so you have the set the lafDecoration for that as well:
JFrame.setDefaultLookAndFeelDecorated(Boolean.TRUE);
JDialog.setDefaultLookAndFeelDecorated(true);
Works for jdk7 and vista, didn't test other environments.
I made a small project as you described:
public class LafTest
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(500, 500);
JPanel panel = new JPanel(new BorderLayout());
JToolBar toolbar = new JToolBar();
toolbar.add(new JButton("button1"));
toolbar.add(new JButton("button2"));
panel.add(toolbar, BorderLayout.PAGE_START);
frame.add(panel);
frame.setVisible(true);
}
}
Works fine for me, all the time the JToolBar has Metal-LAF.
(OS: Windows 7 x64, java version "1.7.0_09")
Please compare your code with this snippet. Propably you used the UIManager-class somewhere. If you still cannot fix this issue, you should post some of the used code and maybe some more details about your OS and the used Java version.

Replacing a imageIcon

I have a value called 'AmountWrongGuessed' that gives the amount of wrong guesses the users puts while guessing a word.
Each times the word is not found in the arraylist the AmountWrongGuessed goes ++. (tested this wih a println and it works properly)
Now the problem is each time the AmountWrongGuessed goes 1 up it should display a ImageIcon.
But insteed it displays the last image icon all the time, and skips the other icons.
I use no layout mananger (its set to null, if this makes any difference in the total picture setLayout = null)
Also while initialising this game the amountwrongguessed is default 0, yet it does not display the first imageicon either. (i used different labels before to add each icon on the same position but then i had the problem only the first image displayed and nothing changed).
public HrView(Hrgame hg) {
this.hg = hg;
CreateComponents();
SetLayoutComponents();
UpdateComponents();
AddListeners();
}
Creation of the images:
private void CreateComponents() {
hang0 = new ImageIcon("hang0.gif");
lblHang = new JLabel(hang0);
lblHang.setLocation(60, -10);
lblHang.setSize(200, 200);
hang1 = new ImageIcon("hang1.gif");
lblHang = new JLabel(hang1);
lblHang.setLocation(60, -10);
lblHang.setSize(200, 200);
hang2 = new ImageIcon("hang2.gif");
lblHang = new JLabel(hang2);
lblHang.setLocation(60, -10);
lblHang.setSize(200, 200);
}
private void AddListeners()
{
btnCheck.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
hg.Input(tfToGuessInput.getText().toLowerCase());
Pictures();
lblHang.updateUI();
}
});
}
private void Pictures()
{
//works, does increment
System.out.println(hg.getAmountWrongGuessed());
if (hg.getAmountWrongGuessed() == 0) {
add(lblHang);
}
if (hg.getAmountWrongGuessed() == 1) {
add(lblHang);
}
if (hg.getAmountWrongGuessed() == 2) {
add(lblHang);
}
}
After CreateComponents() your attribute lblHang references the label you created last (the one containing image hang2.) In order to use the 3 labels later on, you need to have 3 label attibutes which you can then use in Pictures().
Btw, in Java the naming convention is that method names start with a lowercase character.
import javax.swing.*;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.ImageIcon;
import java.awt.BorderLayout;
import java.awt.*;
import java.awt.event.*;
public class testgui{
private static int flag = 1;
public static void main(String[] args){
final JLabel label = new JLabel("",new ImageIcon("0.jpg"),JLabel.CENTER);
final JLabel label1 = new JLabel("",new ImageIcon("1.jpg"),JLabel.CENTER);
final JLabel label2 = new JLabel("",new ImageIcon("2.jpg"),JLabel.CENTER);
final JFrame frame = new JFrame();
final JPanel panel = new JPanel();
frame.add(panel,BorderLayout.CENTER);
frame.setVisible(true);
final JButton button = new JButton("Next");
frame.add(button,BorderLayout.SOUTH);
panel.add(label);
frame.pack();
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(flag==0){
System.out.println("0.jpg");
//label image, flag increment
flag = flag+1;
panel.removeAll();
panel.add(label);
frame.pack();
} else if(flag==1){
System.out.println("1.jpg");
//label1 image, flag increment
flag = flag+1;
panel.removeAll();
panel.add(label1);
frame.pack();
} else if (flag==2){
System.out.println("2.jpg");
//label2 image, reset flag to 0
flag = 0;
panel.removeAll();
panel.add(label2);
frame.pack();
}
else{
System.out.println("Wrong flag number !");
}
panel.validate();
panel.updateUI();
}
});
}
}
I think if you want to switch images, using jlabels, the above codes would help. It would help to rotate jlabels containing images but this codes are not optimized.

Categories

Resources