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.
Related
I've made a JTextArea where I input different commands and separate them by newline "\n", and if there is an error in one of the lines then I write it in a console output. Here I made a very simple, and not the best solution to make this line indication, but it's a bit buggy.
How I made it
I've defined a textArea where I can type different information/commands, and if one of the commands/lines is invalid I write it in the console just to display something for now. I basically count the lines by splitting the textArea rows up by "\n" and then count which line the error occurs in, and the left consoleLineNum is using the amount of rows in textArea, to then make a string containing all the numbers of rows+"\n".
But here my question is, is this a good enough way? If so, why/how can I make it more robust? Or how can I make this indication with line numbers, in the left? It has to increase each time the user makes a new line in the textArea.
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width, height);
frame.setLayout(new BorderLayout(3,3));
/*----- Panels -----*/
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
//Add Components to this panel.
JScrollPane scrollPane = new JScrollPane(textArea);
JScrollPane scrollPaneOutput = new JScrollPane(consoleOutput);
textArea.setCaretPosition(textArea.getDocument().getLength());
consoleOutput.setEditable(false);
consoleLineNum.setEditable(false);
ButtonPanel_listener(buttonPanel);
textArea.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
consoleLineNum.setText("");
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= Integer.parseInt(String.valueOf(textArea.getText().split("\n").length)); i++) {
sb.append(i + " \n");
}
consoleLineNum.setText(sb.toString());
}
#Override
public void keyReleased(KeyEvent e) {
}
});
//Background
panel1.setBackground(Color.LIGHT_GRAY);
//Preferred size
panel1.setPreferredSize(new Dimension(100, 100));
scrollPane.setPreferredSize(new Dimension(200, 200));
panel2.setLayout(new BorderLayout());
panel2.add(scrollPane, BorderLayout.CENTER);
panel2.add(buttonPanel, BorderLayout.SOUTH);
panel2.add(consoleLineNum, BorderLayout.WEST);
consoleLineNum.setText(num);
panel3.setLayout(new BorderLayout());
panel3.add(drawCanvas, BorderLayout.CENTER);
panel1.setLayout(new BorderLayout());
panel1.add(scrollPaneOutput, BorderLayout.CENTER);
//textArea.addActionListener(e -> drawCanvas.drawCircle(250, 250, 200));
//Add contents to the window.
frame.add(panel2, BorderLayout.WEST);
frame.add(panel3, BorderLayout.CENTER);
frame.add(panel1, BorderLayout.SOUTH);
//Display the window.
frame.pack();
frame.setVisible(true);
}
Difference between your expected and actual results
When I hit newline/Enter, it doesn't show the number right away, only when I start typing.
Or
Here I want it to match where the user is, so if the user hit enter, and go to the next line, then the number matches and is shown right away.
If I delete all lines, except some, it still shows the numbers
Here I want it to wipe all the numbers and update it to match the amount of data in textArea.
Tried this, and it works almost as expected. The only problem is that when I delete lines, it's one behind.
#Override
public void keyPressed(KeyEvent e) {
numI = textArea.getLineCount();
if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE && numI > 0) {
numI = numI - 1;
}
if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE || e.getKeyCode() == KeyEvent.VK_ENTER){
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= numI; i++) {
sb.append(i+1 + " \n");
}
consoleLineNum.setText(sb.toString());
}
}
Use a DocumentListener to listen for changes in the text of the JTextArea. The API of JTextArea already provides a method that tells you how many lines it contains, namely getLineCount(). After placing the JTextArea in a JScrollPane, set a JList as the row header for the JScrollPane.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JViewport;
import javax.swing.WindowConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class CountLns implements DocumentListener, Runnable {
private JFrame frame;
private JList<Integer> lineNumbersList;
private JTextArea textArea;
public void changedUpdate(DocumentEvent docEvent) {
// Never called.
}
public void insertUpdate(DocumentEvent docEvent) {
handleDocEvent();
}
public void removeUpdate(DocumentEvent docEvent) {
handleDocEvent();
}
#Override
public void run() {
showGui();
}
private JScrollPane createTextArea() {
textArea = new JTextArea(20, 50);
textArea.getDocument().addDocumentListener(this);
JScrollPane scrollPane = new JScrollPane(textArea);
lineNumbersList = new JList<>(new Integer[]{1});
lineNumbersList.setBackground(Color.cyan);
lineNumbersList.setFont(textArea.getFont());
lineNumbersList.setFixedCellHeight(16);
JViewport rowHeader = new JViewport();
rowHeader.setView(lineNumbersList);
scrollPane.setRowHeader(rowHeader);
return scrollPane;
}
private void handleDocEvent() {
DefaultListModel<Integer> model = new DefaultListModel<>();
List<Integer> lineNumbers = IntStream.range(0, textArea.getLineCount())
.boxed()
.map(i -> i + 1)
.collect(Collectors.toList());
model.addAll(lineNumbers);
lineNumbersList.setModel(model);
}
private void showGui() {
frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createTextArea(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
textArea.requestFocusInWindow();
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new CountLns());
}
}
Whenever the contents of the JTextArea change, the DocumentListener counts the lines in the JTextArea and sets the JList model to contain exactly that number of elements. So if the JTextArea has 12 lines, the JList will contain all the numbers from 1 to 12.
Try doing it like this:
yourTextArea.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
// Returns true every time the user presses either backspace or enter.
if (e.getKeyChar() == '\n' || e.getKeyChar() == '\b') {
int lines;
// Checks if the text ends with a newline, if so,
// it adds 1 to the line count, so that would make your line
// appear even if the user just started a new line.
if (yourTextArea.getText().endsWith("\n")) {
lines = yourTextArea.getText().split("\n").length + 1;
} else {
lines = yourTextArea.getText().split("\n").length;
}
// Removes previous count.
linePanel.setText("");
// Appends a new line to the area for every line.
for (int i = 0; i < lines; i++) {
linePanel.append((i + 1) + "\n");
}
}
}
});
I did not write in Java for 1 year so sorry, if I messed up syntax
First of all, why won't you implement line wrap and line count increment by pressing Enter? It looks much more simple to me
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
textArea.append("\n");
Integer lineCount = Integer.parseInt(consoleLineNum.getText());
Integer newLineNumber = new Integer(lineCount.intValue() + 1)
consoleLineNum.append("\n" + newLineNumber.toString())
}
}
However you still will not get actual number of lines, if some of them will be deleted. So you can also add trickier logic to your keyPressed() method
if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
// Well I actually googled this line for counting occurences
Integer linesCountActual = textArea.getText().split("\n", -1).length - 1);
Integer linesCountLeft = consoleLineNum.getText().split("\n", -1).length - 1);
if (linesCountActual > linesCountLeft) {
String oldText = consoleLineNum.getText();
String newText = oldText.substring(0, oldText.length() - 2);
consoleLineNum.setText(newText);
}
}
I am having trouble implementing JLabel with JFrame. The program needs to show either "Hello" or "World" in the center of the screen when the button "study" is pressed. Also with this being a flashcard program, when study is pressed a word is placed on the middle of the screen and the program is suppose to read from the text field for the user input and print whether it is right or wrong. The problem is that the program is reading the text field after study is pressed so it is printing false before the user can input a answer.
Can someone briefly explain why this is not working and what I can do to fix this issue?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class NoteCardGUI implements ActionListener {
public static JFrame frame;
public static JPanel panel;
public static JLabel label;
private NoteCard ex;
private JButton study;
public static Box box1 = new Box(), box2 = new Box(), box3 = new Box();
public NoteCardGUI() {
ex = new NoteCard("Hello", "World");
frame = new JFrame("Flash Card");
panel = new JPanel();
study = new JButton("Study");
study.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String resp = NoteCard.getResponse(ex);
String chal = NoteCard.getChallenge(ex);
String a = text.getText();
label = new JLabel(chal, label.CENTER);
label.setAlignmentX(0);
label.setAlignmentY(0);
frame.add(label, BorderLayout.SOUTH);
frame.revalidate();
if(resp.compareTo(a) == 0)
{
label = new JLabel("Correct!");
}
label = new JLabel("Incorrect");
}
});
panel.add(study);
frame.add(panel);
frame.setSize(500, 500);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
new NoteCardGUI();
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
You are adding the label to your frame, but you already have added a JPanel on top of the frame. The solution is to add the label to the panel instead of the frame.
So change: frame.add(label); to panel.add(label);
By default, a JFrame (or rather, its content pane) has BorderLayout. This means that if you add components to it without specifying a constraint, they will be added at the CENTER. But you can't add more than one element at any of the BorderLayout's regions.
So in order for this to work, you need to add the label somewhere else other than the center, or have the panel added with some other, explicit region.
So if you change the add, for example, to:
frame.add(label, BorderLayout.NORTH);
It will work - but you must not forget to also add:
frame.revalidate();
Whenever you add components to your GUI, you should call this when you've added them all, in order for it to rebuild the hierarchy of components as needed.
Another option would be to change the layout manager of the Frame, or to add to the panel.
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
I am writing a small program that converts files, and I wanted to have a box pop up that asks the user to please wait while the program loops through and converts all the relevant files, but I am running into a small problem. The box that pops up should have a JLabel and a JButton, while the user is "waiting" I wanted to display a message that says please wait, and a disabled "OK" JButton, and then when its finished I wanted to set the text of the JLabel to let them know that It successfully converted their files, and give them a count of how many files were converted. (I wrote a method called alert that sets the text of the label and enables the button.) The problem is That while the program is running, the box is empty, the Label and the Button are not visible, when it finishes, label appears with the final text that I want and the button appears enabled. I am not sure exactly what is going on, I tried changing the modifiers of the JLabel and JButton several times but I cant seem to get it to work correctly. Here is the code for the box that pops up, any help is greatly appricated.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PleaseWait extends javax.swing.JFrame{
private static final int height = 125;
private static final int width = 350;
final static JLabel converting = new JLabel("Please Wait while I convert your files");
private static JButton OK = new JButton("OK");
public PleaseWait(){
// creates the main window //
JFrame mainWindow = new JFrame();
mainWindow.setTitle("Chill For A Sec");
mainWindow.setSize(width, height);
mainWindow.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// creates the layouts//
JPanel mainLayout = new JPanel(new BorderLayout());
JPanel textLayout = new JPanel(new FlowLayout());
JPanel buttonLayout = new JPanel(new FlowLayout());
// Sets Text //
converting.setText("Please wait while I convert your files");
// disables button //
OK.setEnabled(false);
// adds to the layouts //
textLayout.add(converting);
buttonLayout.add(OK);
mainLayout.add(textLayout, BorderLayout.CENTER);
mainLayout.add(buttonLayout, BorderLayout.SOUTH);
// adds to the frame //
mainWindow.add(mainLayout);
// sets everything visible //
mainWindow.setVisible(true);
}
public static void alert(){
OK.setEnabled(true);
String total = String.valueOf(Convert.result());
converting.setText("Sucsess! " + total + " files Converted");
}
}
Okay here's the issue. You are extending the JFrame . That means your class IS a JFrame.
When you create the PleaseWait frame you don't do anything to it. This is the empty box you are seeing. You are instead creating a different JFrame in your constructor. Remove your mainWindow and instead just use this. Now all of your components will be added to your PleaseWait object. That should fix your blank box issue.
You need an application to create your frame first. This is a simple example of such application.
import javax.swing.UIManager;
import java.awt.*;
public class Application {
boolean packFrame = false;
//Construct the application
public Application() {
PleaseWait frame = new PleaseWait();
//Validate frames that have preset sizes
//Pack frames that have useful preferred size info, e.g. from their layout
if (packFrame) {
frame.pack();
}
else {
frame.validate();
}
//Center the window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
frame.convert();
}
//Main method
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e) {
e.printStackTrace();
}
new Application();
}
}
You have to slightly modify your frame to add controls to the content pane. You can do some work after frame is created, then call alert.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PleaseWait extends JFrame {
private static final int height = 125;
private static final int width = 350;
final static JLabel converting = new JLabel();
private static JButton OK = new JButton("OK");
BorderLayout borderLayout1 = new BorderLayout();
JPanel contentPane;
int count;
public PleaseWait(){
contentPane = (JPanel)this.getContentPane();
contentPane.setLayout(borderLayout1);
this.setSize(new Dimension(width, height));
this.setTitle("Chill For A Sec");
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// creates the layouts//
JPanel mainLayout = new JPanel(new BorderLayout());
JPanel textLayout = new JPanel(new FlowLayout());
JPanel buttonLayout = new JPanel(new FlowLayout());
// Sets Text //
converting.setText("Please wait while I convert your files");
// disables button //
OK.setEnabled(false);
OK.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// adds to the layouts //
textLayout.add(converting);
buttonLayout.add(OK);
mainLayout.add(textLayout, BorderLayout.CENTER);
mainLayout.add(buttonLayout, BorderLayout.SOUTH);
// adds to the frame //
contentPane.add(mainLayout);
}
public void convert(){
count = 0;
for (int i = 0; i <10; i++){
System.out.println("Copy "+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
count++;
}
alert();
}
public void alert(){
OK.setEnabled(true);
// String total = String.valueOf(Convert.result());
converting.setText("Sucsess! " + count + " files Converted");
}
}
I need to clean my labelResult each time on textField Action, but on the first time it adds 'null' in front of string and then - prints new string right after. Please help.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Frame extends JFrame implements ActionListener {
boolean isDirect = true;
String[] typeStr = {"direct", "invert"};
JLabel labelTip = new JLabel("Choose 'direct' OR 'invert' to print your next line in direct order or inverted respectively.");
JTextField textField = new JTextField("Some text!", 40);
JComboBox comboBox = new JComboBox(typeStr);
EventProcessing eventProcessing = new EventProcessing();
JLabel labelResult = new JLabel();
public Frame() {
setLayout(new BorderLayout());
getContentPane().add(labelTip, BorderLayout.PAGE_START);
getContentPane().add(comboBox, BorderLayout.CENTER);
getContentPane().add(textField, BorderLayout.AFTER_LINE_ENDS);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textField.addActionListener(this);
pack();
}
public void actionPerformed(ActionEvent e) {
getContentPane().remove(labelResult);
labelResult = new JLabel();
labelResult.setText("");
if (!(comboBox.getSelectedItem()).equals("direct")) {
isDirect = false;
}
else {
isDirect = true;
}
labelResult.setText(eventProcessing.action(isDirect, textField.getText()));
getContentPane().add(labelResult, BorderLayout.PAGE_END);
pack();
}
}
#Tim I know that in official tutorial about JComboBox is used ActionListener, but for any of actions from JComboBox to the GUI is better look for ItemListener, there you are two states (always be called twice, but you can filtering between thes two options SELECTED / DESELECTED by wraping to the if ... else)
and your code should be only
Runnable doRun = new Runnable() {
#Override
public void run() {
labelResult.setText(eventProcessing.action(isDirect, textField.getText()));
add(labelResult, BorderLayout.PAGE_END);
//1) this.pack(); if you want to re-layout with effect to size of JFrame too
//2a revalidate();
//2b plus in most cases
//2b repaint(); relayout Container with fitting JComponents inside Container,
//2b but without resize of JFrame
}
};
SwingUtilities.invokeLater(doRun);
Without the code to EventProcessing.action() it's hard to determine, but I would guess you attempt to concatenate two strings, the first of which is null. Null strings get converted to the literal string "null."