Intellij: What causes a dark green inspection highlight? - java

After searching forums and stackoverflow I can't see to figure out what this inspection highlight is trying to alert me to:
Selecting/hovering over the highlighted text returns nothing besides the standard context actions.
Originally these variables were declared and instantiated before the constructor. (ACTIONS TAKEN TO REPRODUCE) When I used the context action "Move initialization to constructor", the initializations in the constructor are highlighted dark green. See attached img.
Anyone know what's going on here?
example:
public class HoaQueueEditorDialog extends ListDialogBase implements Mutable {
private static final String SAVE = "Save";
private static final String CANCEL = "Cancel";
private static final String CHAR_DELIMITER = ",";
private static final String[] COL_NAMES = {"Workflow Step Name"};
private static final Color NORM_BACKGROUND = TRexUIManager.getColor(TRexUIManager.CONTENT_BACKGROUND);
private static final Color NORM_FOREGROUND = Color.black;
private static final int[] COL_WIDTHS = {325};
private static final ArrayList<AppOptionsUtil.WorkflowStepInfo> SUPPORTED_STEPS_LIST = AppOptionsUtil.getDisplayHoaInfoWfStepsSupportedList();
// UI Elements
private TButton saveButton;
private TButton cancelButton;
private JPanel parentPanel;
private JPanel buttonPanelRight;
private JPanel buttonPanelLeft;
// Stores the data necessary to build a table row and it's corresponding checkbox object.
protected HashMap<AppOptionsUtil.WorkflowStepInfo, TCheckBox> checkBoxMap;
private TTable wfQueuesTable;
private DefaultTableModel tableModel;
private TChangeListener changeListener = null;
private boolean escKeyPressedInsideYesNoCancel = false;
private String originalAppOptionValues = null;
private String returnAppOptionValues = null;
public HoaQueueEditorDialog() {
try {
this.tableModel = new DefaultTableModel(new Object[][]{{}}, COL_NAMES);
this.wfQueuesTable = new TTable();
wfQueuesTable.setModel(tableModel);
wfQueuesTable.setBackground(NORM_BACKGROUND);
wfQueuesTable.setRowHeight(42);
wfQueuesTable.getSelectionModel().addListSelectionListener(new DocumentTableSelectionListener());
init();
initMVC();
this.setResizable(true);
} catch (Exception ex) {
TRexToolkit.showErrorMessage("Error initializing Document Print Screen.", "Error", ex);
}
buttonPanelLeft = new JPanel(new FlowLayout(LEFT));
buttonPanelRight = new JPanel(new FlowLayout(RIGHT));
parentPanel = new JPanel();
}

IntelliJ IDEA is highlighting the changes it made when you invoked the Move initialization to constructor intention. Because the changes are quite far away from the cursor, you might not see them otherwise. Pressing Escape will remove the highlighting.

Related

How to add text and delete text using GUI in Java

I am creating a dumb phone (like old traditional phone) and I'm using GUI programming. I need help with dialing the numbers. I don't know how to get the numbers to pop up on the display and stay there, and also use the delete button to delete the numbers that is up on the display too. I will post a youtube link so you can see a sample run.
I am currently stuck on passing the text from the button of each number that should display the number, however it's displaying the text of the button. I also, don't know how to keep the number there when other buttons are pressed without it being reset.
Here is my code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.*;
public class DumbPhone extends JFrame
{
private static final long serialVersionUID = 1L;
private static final int WIDTH = 300;
private static final int HEIGHT = 500;
private static final String CALL_BUTTON_TEXT = "Call";
private static final String TEXT_BUTTON_TEXT = "Text";
private static final String DELETE_BUTTON_TEXT = "Delete";
private static final String CANCEL_BUTTON_TEXT = "Cancel";
private static final String SEND_BUTTON_TEXT = "Send";
private static final String END_BUTTON_TEXT = "End";
private static final String CALLING_DISPLAY_TEXT = "Calling...";
private static final String TEXT_DISPLAY_TEXT = "Enter text...";
private static final String ENTER_NUMBER_TEXT = "Enter a number...";
private JTextArea display;
private JButton topMiddleButton;
private JButton topLeftButton;
private JButton topRightButton;
private JButton[] numberButtons;
private JButton starButton;
private JButton poundButton;
private boolean isNumberMode = true;
private String lastPressed = "";
private int lastCharacterIndex = 0;
private Date lastPressTime;
public DumbPhone()
{
setTitle("Dumb Phone");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createContents();
setVisible(true);
topLeftButton.setEnabled(false);
}
private void createContents()
{
//create JPanel, and JTextArea display
JPanel panel = new JPanel(new GridLayout(5,3));
display = new JTextArea();
display.setPreferredSize(new Dimension(280, 80));
display.setFont(new Font("Helvetica", Font.PLAIN, 32));
display.setLineWrap(true);
display.setEnabled(false);
panel.add(display);
//create JButtons
topLeftButton = new JButton(DELETE_BUTTON_TEXT);
topMiddleButton = new JButton((CALL_BUTTON_TEXT));
topRightButton = new JButton((TEXT_BUTTON_TEXT));
numberButtons = new JButton[10];
numberButtons[1] = new JButton("<html><center>1<br></center></html>");
numberButtons[2] = new JButton("<html><center>2<br>ABC</center></html>");
numberButtons[3] = new JButton("<html><right>3<br>DEF</right></html>");
numberButtons[4] = new JButton("<html><center>4<br>GHI</center></html>");
numberButtons[5] = new JButton("<html><center>5<br>JKL</center></html>");
numberButtons[6] = new JButton("<html><center>6<br>MNO</center></html>");
numberButtons[7] = new JButton("<html><center>7<br>PQRS</center></html>");
numberButtons[8] = new JButton("<html><center>8<br>TUV</center></html>");
numberButtons[9] = new JButton("<html><center>9<br>WXYZ</center></html>");
numberButtons[0] = new JButton("<html><center>0<br>space</center></html>");
poundButton = new JButton("#");
starButton = new JButton("*");
//add JButtons to buttons JPanel
panel.add(topLeftButton);
panel.add(topMiddleButton);
panel.add(topRightButton);
panel.add(numberButtons[1]);
panel.add(numberButtons[2]);
panel.add(numberButtons[3]);
panel.add(numberButtons[4]);
panel.add(numberButtons[5]);
panel.add(numberButtons[6]);
panel.add(numberButtons[7]);
panel.add(numberButtons[8]);
panel.add(numberButtons[9]);
panel.add(starButton);
panel.add(numberButtons[0]);
panel.add(poundButton);
//add Listener instance (inner class) to buttons
topLeftButton.addActionListener(new Listener());
topMiddleButton.addActionListener(new Listener());
topRightButton.addActionListener(new Listener());
//JButton[] array = new JButton[10];
for (int i = 0; i < numberButtons.length; i++)
{
numberButtons[i].addActionListener(new Listener());
numberButtons[i] = new JButton(String.valueOf(i));
}
starButton.addActionListener(new Listener());
poundButton.addActionListener(new Listener());
//add display and buttons to JFrame
setLayout(new BorderLayout());
add(display, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
}
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == topLeftButton)
{
if(lastPressTime == null)
{
display.setText(ENTER_NUMBER_TEXT);
}
else
{
topLeftButton.setEnabled(true);
lastCharacterIndex--;
lastPressed = lastPressTime.toString();
}
}
else if(e.getSource() == topMiddleButton)
{
if(lastPressTime == null || lastCharacterIndex == 0)
{
display.setText(ENTER_NUMBER_TEXT);
}
else
{
display.setText(CALLING_DISPLAY_TEXT);
}
}
else if(e.getSource() == topRightButton)
{
if(lastPressTime == null || lastCharacterIndex == 0)
{
display.setText(TEXT_DISPLAY_TEXT);
}
else
{
display.setText(CALLING_DISPLAY_TEXT);
}
}
else
{
topLeftButton.setEnabled(true);
if (e.getSource() instanceof JButton)
{
//String text = ((JButton) e.getSource()).getText();
display.setText(lastPressed + " f" + numberButtons[lastCharacterIndex].getText());
}
}
Date currentPress = new Date();
long currentTime = currentPress.getTime();
if(lastPressTime != null)
{
//long lastPressTime = lastPressTime.getTime();
//subtract lastPressTime from currentPress time to find amount of time elapsed since last button pressed.
}
lastPressTime = currentPress;
String buttonLetters = ""; // Parse Letter from button (e.g "abc").
//update lastCharacterIndex.
lastCharacterIndex++;
lastCharacterIndex = lastCharacterIndex % buttonLetters.length();
}
}
for example, if I push the button 2, instead of giving me "2", it will give me < html>< center>2ABC < / center >< / html >
Therefore, I need help with
Having the numberButtons, when pushed to show the numbers that were pushed.
Be able to delete those numbers.
Here is the link to the sample run: https://www.youtube.com/watch?v=evmGWlMSqqg&feature=youtu.be
Try starting the video 20 seconds in.
to delete the number, you can use the labelname.setText("")
At a basic level, you simply want to maintain the "numbers" separately from the UI. This commonly known as a "model". The model lives independently of the UI and allows the model to be represented in any number of possible ways based on the needs of the application.
In your case, you could use a linked list, array or some other simple sequential based list, but the easiest is probably to use a StringBuilder, as it provides the functionality you require (append and remove) and can make a String very simply.
So, the first thing you need to do is create an instance of model as an instance level field;
private StringBuilder numbers = new StringBuilder(10);
this will allow the buffer to be accessed any where within the instance of the class.
Then you need to update the model...
else
{
topLeftButton.setEnabled(true);
if (e.getSource() instanceof JButton)
{
String text = numberButtons[lastCharacterIndex].getText();
numbers.append(text);
}
}
To remove the last character you can simply use something like...
if (numbers.length() > 0) {
numbers.deleteCharAt(numbers.length() - 1);
}
Then, when you need to, you update the UI using something like...
display.setText(numbers.toString());
Now, this is just basic concepts, you will need to take the ideas and apply it to your code base

JAVA After adding a seccond button and its actionListener, actions get executed twice

After adding a listener to a second button, the first created button executes twice the same action:
public class ControladorTablaMaterial implements ActionListener {
private VistaTablaMaterial vistaTablaMaterial;
private JPanel jContentPane = null;
private JScrollPane scrollPane = null;
private JTable tablaMaterial;
private JButton mostrarElementoButton;
private JButton eliminarElementoButton;
private ModeloTablaMaterial modeloTablaMaterial;
public ControladorTablaMaterial(ArrayList<Material> coleccionMaterial, ActionListener listener) {
String[] cabecera = {"Material", "Titulo"};
this.vistaTablaMaterial = new VistaTablaMaterial(cabecera, coleccionMaterial);
setupVistaTablaMAterial(listener);
}
private void setupVistaTablaMAterial(ActionListener listener) {
this.scrollPane = vistaTablaMaterial.getScrollPane();
this.tablaMaterial = vistaTablaMaterial.getTablaMaterial();
this.modeloTablaMaterial = vistaTablaMaterial.getModeloTablaMaterial();
this.mostrarElementoButton = vistaTablaMaterial.getMostrarElementoButton();
this.eliminarElementoButton = vistaTablaMaterial.getMostrarElementoButton();
this.initListeners(listener);
}
private void initListeners (ActionListener listener) {
getMostrarElementoButton().addActionListener(listener);
getEliminarElementoButton().addActionListener(listener);
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
Everything works fine if I delete the line:
getEliminarElementoButton().addAtionListener(listener);
but of course I need that button to be listened to too.
Inside the listener class, in the actionPerformed(actionEvent e) method, I use the following code to differentiate both buttons:
if (e.getSource().equals(this.getControladorTablaMaterial().getMostrarElementoButton())) {
That seems to work fine except for this frame. Any guess?
Off topic: why isn't the code indentation working properly on Stackoverflow's editor?
The problem is in these lines:
this.mostrarElementoButton = vistaTablaMaterial.getMostrarElementoButton();
this.eliminarElementoButton = vistaTablaMaterial.getMostrarElementoButton();
That you are getting the same button for both.

Swing Component communication

i am building an algorithm simulation tool and I am struggling to get my mainframe class which instantiates and adds all the subcomponents to the JFrame to get the file system location of where the pseudocode is located (for the psuedocode panel.)
I have made every single algorithm have a string which details where the relevant text file information for each algorithm is.
I have a method which then takes the string when the algorithm is passed in and stores it into a string variable.
This string variable is then passed to the panel.
Unfortunately this is throwing a null pointer and I have been trying to debug this and can't get far.
public class SortAnimator extends JFrame
{
private static final int VALUES_LENGTH = 30;
private static final int FRAME_WIDTH = 1200;
private static final int FRAME_HEIGHT = 700;
private PsuedocodePanel pseudoPanel;
private Menu menu;
private InformationPanel infoPanel;
private String algoName;
public String algoLocation;
public SortAnimator(Sorter s) throws IOException
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu=new Menu();
pseudoPanel=new PsuedocodePanel();
ArrayComponent panel = new ArrayComponent();
infoPanel= new InformationPanel();
add(menu,BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
add(pseudoPanel,BorderLayout.WEST);
add(infoPanel,BorderLayout.SOUTH);
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setVisible(true);
int[] values = new int[VALUES_LENGTH];
for (int i = 0; i < values.length; i++)
values[i] = (int) (Math.random() * panel.getHeight());
s.setValues(values);
s.setPanel(panel);
Thread t = new Thread(s);
t.start();
algoName=s.getAlgorithmName();
algoLocation =s.getAlgorithmLocation();
System.out.println(algoLocation);
pseudoPanel.passFileLocation(algoLocation);
}
}
public class PsuedocodePanel extends JPanel{
private JTextArea txtArea;
private String textFile;
private String fileLocation;
public PsuedocodePanel() throws FileNotFoundException, IOException{
setLayout(new BorderLayout());
txtArea=new JTextArea();
txtArea.setEditable(false);
add(txtArea,BorderLayout.CENTER);
FileReader fr = new FileReader(this.fileLocation);
BufferedReader reader=new BufferedReader(fr);
txtArea.read(reader,null);
Dimension dim=getPreferredSize();//returns object
System.out.println(getPreferredSize());
dim.width=300;
dim.height=75;
setPreferredSize(dim);
Border innerBorder=BorderFactory.createTitledBorder("Algorithm Psuedocode");
Border outerBorder=BorderFactory.createEmptyBorder(5,5,5,5);
setBorder(BorderFactory.createCompoundBorder(outerBorder,innerBorder));
}
public void passFileLocation(String algoLocation) {
this.fileLocation= algoLocation;
}
Your PsuedocodePanel class creates a FileReader in its constructor, using this.fileLocation, but fileLocation will be null at that point in the code - see simplified code fragment below:
public class PsuedocodePanel extends JPanel{
private String fileLocation; // not initialised
// constructor does not accept a fileLocation...
public PsuedocodePanel() throws FileNotFoundException, IOException{
// ... so this.fileLocation is null here:
FileReader fr = new FileReader(this.fileLocation);

How to make Jbutton run another class?

Hi stackoverflow community!
I'm making an AI TicTacToe project for my finals, and I'm having a problem trying to run another class after pressing one of jButtons in the jFrame class.
I'm using NetBean's jFrame class, where you can design easily by placing it from the container, and some of the codes are not editable.
What I want to make is a workable Main Menu (which is a jFrame class) for my gaming project, and it contains three buttons which are Normal, Large and Extra Large. For Normal button, I want to make this button to run TicTacToe (which is a normal java class) after being pressed, but for some reasons I can't make it work. Here are the codes:
MainMenu.java
private void ButtonNormal(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Normal_TicTacToe SIZE1 = new Normal_TicTacToe(); // This is the problem
SIZE1.setVisible(true);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new MainMenu().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton buttonNormal;
// End of variables declaration
}
Normal_TicTacToe.java - I got this code from the internet, and I'm modifying it for Large and Extra Large size. I'll credit this guy as the original author in the documentation.
public final class Normal_TicTacToe extends JApplet
{
private static final long serialVersionUID = 1L;
private final Normal_Tile[] TILES = new Normal_Tile[9];
private final int TILE_SPACING = 96;
private final int WIDTH = 96, HEIGHT = 96;
private final JFrame GAMEFRAME = new JFrame("Tic-Tac-Toe");
private final Normal_TilePainter PAINTER = new Normal_TilePainter(this);
private final Normal_ClickHandler CLICK_HANDLER = new Normal_ClickHandler(this);
private final boolean AI;
private boolean aiTurn = false;
private Normal_Holder turn = Normal_Holder.X;
private int whoseTurn = 0;
private final Dimension FRAME_SIZE = new Dimension(295, 304);
private final int FONT_SIZE = 64;
private int oWins = 0;
private int xWins = 0;
private boolean gameOver = false;
private boolean nextTurn = false;
public final Normal_AI GAME_AI = new Normal_AI(this);
public void init()
{
Normal_TicTacToe game = new Normal_TicTacToe(true);
game.newGame();
}
public Normal_TicTacToe(boolean ai)
{
this.AI = ai;
PAINTER.setSize(FRAME_SIZE);
buildFrame();
loadTiles();
}
Also, both java files are in the same package.
If you're looking for extended codes and all the java files, you can find it here:
My MainMenu.java
Chall's TicTacToe and his java files (Scroll down until you see source files).
The constructor of the Normal_TICTACTOE looks like this:
public Normal_TicTacToe(boolean ai)
{
this.AI = ai;
PAINTER.setSize(FRAME_SIZE);
buildFrame();
loadTiles();
}
It has a boolean variable in its parameter list.
So the default constructor is overwritten.
call the constructor with a boolean value (true or false):
Normal_TicTacToe game = new Normal_TicTacToe(true);
(I think it has something to do with the artifical inteligence on or off)
call the method newGame() on the instance you got.
game.newGame();
You should create an instance of it in your button.
Your code:
buttonXLarge.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ButtonXLarge(evt); // not sure what it does, but it doesn't make Tic Tac Toe
}
});
What you want most likely want it to do is initialize and start a new tic tac toe board.
buttonXLarge.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Normal_TicTacToe myBoard = new Normal_TicTacToe(true);
myBoard.newGame();
}
});
I am unsure of how JApplet will handle inside what you're currently doing, as I normally never mix applets with JFrames, but specifically to activate the tic tac toe board, you should be writing what you want it to do within the actionPerformed listener.
If you REALLY wanted to save time on coding, you could probably rebuild TicTacToe using the guts of the JApplet in a JFrame.

Java Swing -- Jpanel with Jbuttons embedded within a JTable

Im building a Ui in Swing wherein my requirement is to have JPanes within a JTable. These JPanes will have JButtons within them.
My use case is as follows --
Im writing a MethodEditor wherein im providing a UI to store the methods within a supplied file. The UI would also allow editing the parameters being passed to the method on the click of a button.
Every single method would have a UI representation as follows --
My basic representation of the Method class is as follows --
public Class Method {
String methodName;
List<String> InputVariableNames;
String OutputVariableName;
}
Now i have a list of Method objects, List<Method> methodList on which i want to base my JTable.
This List is contained in a MethodModel class as follows --
public class MethodModel {
List<Method> methodModel;
}
I had asked a question earlier and have based my code on the answer provided there. My code however does not seem to be working. My code is as follows --
public class MethodEditor extends JTable {
private static final long serialVersionUID = 1L;
private MethodEditorModel model ;
private MethodCellRenderer cellRenderer;
public MethodEditor(MethodModel bean) {
setRowHeight(25);
this.setPreferredSize(new Dimension(500, 500));
model = new MethodEditorModel(bean);
this.setModel(model);
setupComponent();
}
private void setupComponent() {
cellRenderer = new MethodCellRenderer();
this.setDefaultRenderer(Object.class,cellRenderer);
this.setBorder(BorderFactory.createLineBorder(Color.GRAY));
}
private static class MethodEditorModel extends DefaultTableModel implements PropertyChangeListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private MethodModel bean;
public MethodEditorModel(MethodModel bean) {
this.bean = bean;
bean.addPropertyChangeListener(this);
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
fireTableDataChanged();
}
}
private static class MethodCellRenderer implements TableCellRenderer {
/**
*
*/
private static final long serialVersionUID = 1L;
private MethodEditorCellPanel renderer = new MethodEditorCellPanel();
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
MethodModel methodModel = (MethodModel)value;
for(Method method : methodModel.getMethodList()) {
renderer.setComponents((Method) method);
}
return renderer;
}
}
private static class MethodEditorCellPanel extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton upButton;
private JButton downButton;
private JButton methodDetailsButton;
private Method method;
public MethodEditorCellPanel() {
upButton = new JButton("Up");
downButton = new JButton("Down");
}
public void setComponents(Method method)
{
this.method = method;
methodDetailsButton = new JButton(method.getMethodName());
upButton.addActionListener(this);
downButton.addActionListener(this);
methodDetailsButton.addActionListener(this);
Box verticalBar = Box.createHorizontalBox();
verticalBar.add(upButton);
verticalBar.add(Box.createHorizontalStrut(15));
verticalBar.add(methodDetailsButton);
verticalBar.add(Box.createHorizontalStrut(15));
verticalBar.add(downButton);
add(verticalBar);
}
#Override
public void actionPerformed(ActionEvent evt) {
if(evt.getSource().equals(downButton)) {
}
if(evt.getSource().equals(upButton)) {
}
if(evt.getSource().equals(methodDetailsButton)) {
}
}
}
}
The code compiles but the JTable does not show up.
Any pointers on what i may be doing wrong would be of great help.
Don't include another components to JTable. Let alone components with multiple other components. The reason is that JTable won't pass mouse events to its cells. So even when you have buttons inside JTable, then you would have to take care about pressing them by yourself, by:
get cell it was clicked to
get the exact coordinates
extrapolate these coordinates to the inner component
manually call click on the corresponding button.
And even then you won't get button animation and stuff.
If you need to arrange components into a table, use JPanel with GridLayout or GridBagLayout.

Categories