How insert or delete row of JPanel consisting of 3 elements - swing

I am using JPanel of three elements row: JLabel, JTextField, JButton.
jPanel.setLayout(new GridLayout(0,3));
I need button of a row to delete its row from JPanel.
for(Pair<JLabel, JTextField> pair: labelTextFieldPairs) {
jPanel.add(pair.getFirst());
jPanel.add(pair.getSecond());
jPanel.add(createDeleteButton());//how to implement that method?
}
Also I have a button to add row to JPanel.
How to do that? Or is it better to use JTable for that?
What if I need to insert row consisting of 3 elements somewhere in the middle of JPanel. How to do that?
JButton addNumberToListButton = new JButton("add number to list");
addNumberToListButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Pair<JLabel, JTextField> pair = new Pair<>(new JLabel(), new JTextField());
labelTextFieldPairs.add(pair);
jPanel.add(pair.getFirst(), labelTextFieldPairs.size());
jPanel.add(pair.getSecond(), labelTextFieldPairs.size());
jPanel.add(createDeleteButton(), labelTextFieldPairs.size());
//will this 3 lines work?
}
});

Deletion operation looks like this:
public void removeRow(int firstComponentInRow) {
labelTextFieldPairs.remove(firstComponentInRow / numberOfColumns);
jPanel.remove(firstComponentInRow);
jPanel.remove(firstComponentInRow);
jPanel.remove(firstComponentInRow);
jPanel.revalidate();
jPanel.repaint();
}
and add operation looks like this:
public void addRow(Pair<JLabel, JFormattedTextField> labelAndTextField) {
labelTextFieldPairs.add(labelAndTextField);
jPanel.add(labelAndTextField.getFirst(), (labelTextFieldPairs.size() - 1) * numberOfColumns);
jPanel.add(labelAndTextField.getSecond(), (labelTextFieldPairs.size() - 1) * numberOfColumns + 1);
jPanel.add(createDeleteButton((labelTextFieldPairs.size() - 1) * numberOfColumns), (labelTextFieldPairs.size() - 1) * numberOfColumns + 2);
jPanel.revalidate();
jPanel.repaint();
}
where labelTextFieldPairs.size() used as insertion index.

Related

two text fields, one input, one output

I have to complete this code with these simple measures. Cannot do anything overly complicated. I want to translate from the top input text field and output on the bottom text field. So far, it looks right, but my translation simply outputs in the same text field as my input. I am a noob, and checked my notes and textbook, and cannot figure out how to change the output to the bottom field. It just doesn't seem to be possible with this level of code. The translation is right. I think I need to modify the Translate button, but am not sure where to indicate what. It works fine if I just wanted to output in my input box. Well, here is my code so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Translator4 extends JFrame implements ActionListener
{
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public static final int NUMBER_OF_CHAR = 50;
private JTextField phrase;
private JTextField translatedphrase;
public static void main(String[] args)
{
Translator4 gui = new Translator4();
gui.setVisible(true);
}
public Translator4()
{
//title bar and overall size
super("Pig Latin Translator v.4.0");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3,1));
//create input text filed
JPanel namePanel = new JPanel();
namePanel.setLayout(new BorderLayout());
namePanel.setBackground(Color.WHITE);
phrase = new JTextField(NUMBER_OF_CHAR);
namePanel.add(phrase, BorderLayout.CENTER);
JLabel nameLabel = new JLabel("Enter the phrase in English to be translated:");
namePanel.add(nameLabel, BorderLayout.NORTH);
add(namePanel);
//create the buttons
JPanel buttonPanel= new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBackground(Color.GREEN);
JButton actionButton = new JButton("Translate");
actionButton.addActionListener(this);
buttonPanel.add(actionButton);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(this);
buttonPanel.add(clearButton);
add(buttonPanel);
//create the output text field
JPanel namePanel2 = new JPanel();
namePanel2.setLayout(new BorderLayout());
namePanel2.setBackground(Color.WHITE);
translatedphrase = new JTextField(NUMBER_OF_CHAR*2); //output will be larger so I multiplied it by 2
namePanel.add(phrase, BorderLayout.CENTER);
JLabel nameLabel2 = new JLabel("Translation:");
namePanel2.add(nameLabel2, BorderLayout.NORTH);
add(namePanel2);
}
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if (actionCommand.equals("Translate")) //when the user wants a translation, this block executes
{
String[] words=new String[100]; //takes up to 100 words
String sentence = phrase.getText(); //the user input made into a string
String newSentence=""; //the output string generated
words = sentence.split(" "); //splits based on spaces, no other punctuation allowed
for (int index=0; index< words.length; index++) //steps thru the array of words
{
char firstChar = words[index].charAt(0); //rules for vowels, 'one' becomes 'oneway'
if (firstChar=='a'||firstChar=='e'||firstChar=='i'||firstChar=='o'||firstChar=='u')
{
words[index] = words [index] + "way";
newSentence=newSentence + " " + words[index]; //adds the word just now modified to new sentence
}
else //rules for words that don't start with vowels, 'blank' becomes 'lankbay'
{
firstChar = ' ';
words[index] = (words[index]).substring(1,(words[index].length()))
+ (words[index]).charAt(0) + "ay";
newSentence=newSentence + " " + words[index]; //adds the word just now modified to new sentence
}
phrase.setText(newSentence); //sends the new sentence back for output... problem here
}
}
else if (actionCommand.equals("Clear"))
phrase.setText("");
else
phrase.setText("Unexpected error.");
}
}
but my translation simply outputs in the same text field as my input
That's because that's what you're telling it to do
phrase.setText(newSentence); //sends the new sentence back for output... problem here
So I assume, phrase is the input and translatedphrase is the output, so that would mean, to fix your immediate issue, all you need to do is replace phrase with translatedphrase
translatedphrase.setText(newSentence); //sends the new sentence back for output... no more problem
I would also suggest you change the other setText calls you're making against phrase to translatedphrase as well
This...
translatedphrase = new JTextField(NUMBER_OF_CHAR * 2); //output will be larger so I multiplied it by 2
namePanel.add(phrase, BorderLayout.CENTER);
JLabel nameLabel2 = new JLabel("Translation:");
namePanel2.add(nameLabel2, BorderLayout.NORTH);
is also an issue, as you never actually add translatedphrase to anything, you just re-add phrase to namePanel again
So, I assume it should be
translatedphrase = new JTextField(NUMBER_OF_CHAR * 2); //output will be larger so I multiplied it by 2
namePanel2.add(translatedphrase, BorderLayout.CENTER);
JLabel nameLabel2 = new JLabel("Translation:");
namePanel2.add(nameLabel2, BorderLayout.NORTH);

update text of textblock every a half of second in windows phone 8

I want to random a number of my array. Then I show it in a textblock. I want to do it every second. How to update my textblock every second ?. Please to help me.
Create a dispatcher timer and for every ticks update your textbock.
number = 0
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,0,1);
dispatcherTimer.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
//if you use binding and mvvm
this.Text = number.tostring();
//if you don't use binding
yourTextblock.Text = number.toString();
number ++;
}
create dispatcher timer and every half second update text box
int number=0;
private DispatcherTimer _timer;
public sample()
{
InitializeComponent();
_timer = new DispatcherTimer();
_timer.Interval = new TimeSpan(0, 0, 0,0,500);
_timer.Tick += _timer_Tick;
_timer.Start();
}
void _timer_Tick(object sender, EventArgs e)
{
number++;
yourTextblock.Text = number.toString();
}

How to use KeyReleased event on a cell of JTable

I want to take value from cell of JTable while editing it continuously.So can i apply KeyReleased Event to cell and how?
Don't use a KeyListener.
Instead you can get the default editor for the column which will use a JTextField as the editor. Then you add a DocumentListener to the text field. A DocumentEvent will be generated every time you add/remove text.
public void KeyReleased(MouseEvent e)
{
JTable target = (JTable)e.getSource();
int row = target.getSelectedRow();
int col = target.getSelectedColumn();
Object data = (Object)table.getValueAt(row, col);
JOptionPane.showMessageDialog(null, data);
}

JTable : how to get selected cells?

I have a JTable and its TableModel, it works well but what I want to do now is to get the selected cells of it. I thought of doing something like :
int rows = this.getTable().getRowCount();
int columns = this.getTable().getColumnCount();
for(int i = 0 ; i < rows ; i++)
{
for(int j = 0 ; j < columns ; j++)
{
if(table.getCell(i,j).isSelected() //...
}
}
But of course something like this doesn't exist. What should I do instead?
In JTable, you have the
JTable.getSelectedRow()
and
JTable.getSelectedColumn()
You can try combine this two method with a MouseListener and a KeyListener.
With the KeyListener you check if user is pressing the CTRL key, which means that user is selecting cells, then with a mouse listener, for every click you store maybe in a Vector or ArrayList the selected cells:
//global variables
JTable theTable = new JTable();//your table
boolean pressingCTRL=false;//flag, if pressing CTRL it is true, otherwise it is false.
Vector selectedCells = new Vector<int[]>();//int[]because every entry will store {cellX,cellY}
public void something(){
KeyListener tableKeyListener = new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_CTRL){//check if user is pressing CTRL key
pressingCTRL=true;
}
}
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_CTRL){//check if user released CTRL key
pressingCTRL=false;
}
}
};
MouseListener tableMouseListener = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if(pressingCTRL){//check if user is pressing CTRL key
int row = theTable.rowAtPoint(e.getPoint());//get mouse-selected row
int col = theTable.columnAtPoint(e.getPoint());//get mouse-selected col
int[] newEntry = new int[]{row,col};//{row,col}=selected cell
if(selectedCells.contains(newEntry)){
//cell was already selected, deselect it
selectedCells.remove(newEntry);
}else{
//cell was not selected
selectedCells.add(newEntry);
}
}
}
};
theTable.addKeyListener(tableKeyListener);
theTable.addMouseListener(tableMouseListener);
}
table.getSelectedRow() will get selected row.
table.getSelectedColumns() will get selected columns.
getValueAt(rowIndex, columnIndex) will give the value present at the selected row for each column.
JTable has methods to get the selected rows and get the selected columns.
You can use:
int row = table.rowAtPoint(e.getPoint());
int col = table.columnAtPoint(e.getPoint());
You can get the row and column with ( table.getSelectedRow() and table.getSelectedColumn()) but if you selected more than one cell the method table.getSelectedRow() and table.getSelectedColumn() return cell's position of the first cell that was clicked.
On the other hand, table.rowAtPoint(e.getPoint()) and table.columnAtPoint(e.getPoint()) return the exact cell's table that was clicked for the last time.

How to handle event for nonvisual objects in Flex

I am trying to perform two way binding e.g I have a button (out of many controls), on its selection, I am showing the values of its diff properties(like height, width etc) in some textinput. This one way process works fine.
But the reverse process doesn't work. i.e When I select some button, and try to change its dimension by entering some value in height, width textinputs, the dimension are not changed.
How to know which button was selected by me? How events needs to be handled here ?
private void Form1_Load(object sender, System.EventArgs e)
{
//Create some data and bind it to the grid
dt1 = GetData(1000, 3);
this.UltraGrid1.DataSource = dt1;
//Set the grid's CreationFilter to a new instance of the NumbersInRowSelectors class.
this.UltraGrid1.CreationFilter = new NumbersInRowSelectors();
}
private void UltraGrid1_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
{
//Hide the default images that are drawn in the RowSelectors, like the pencil and asterisk, etc.
e.Layout.Override.RowSelectorAppearance.ImageAlpha = Infragistics.Win.Alpha.Transparent;
//Center the text in the RowSelectors.
e.Layout.Override.RowSelectorAppearance.TextHAlign = Infragistics.Win.HAlign.Center;
e.Layout.Override.RowSelectorAppearance.TextVAlign = Infragistics.Win.VAlign.Middle;
//There is no wy to change the width of the RowSelectors.
//Use a smaller font, so that 3-digit numbers will fit.
e.Layout.Override.RowSelectorAppearance.FontData.Name = "Small Fonts";
e.Layout.Override.RowSelectorAppearance.FontData.SizeInPoints = 6;
}
//The NumbersInRowSelectors class. This class Implements a CreationFilter and
//adds a TextUIElement to each RowSelector which displays the row number of
//the row.
public class NumbersInRowSelectors:Infragistics.Win.IUIElementCreationFilter
{
#region Implementation of IUIElementCreationFilter
public void AfterCreateChildElements(Infragistics.Win.UIElement parent)
{
//Don't need to do anything here
}
public bool BeforeCreateChildElements(Infragistics.Win.UIElement parent)
{
//Declare some variables
Infragistics.Win.TextUIElement objTextUIElement;
Infragistics.Win.UltraWinGrid.RowSelectorUIElement objRowSelectorUIElement;
Infragistics.Win.UltraWinGrid.UltraGridRow objRow;
int RowNumber;
//Check to see if the parent is a RowSelectorUIElement. If not,
//we don't need to do anything
if (parent is Infragistics.Win.UltraWinGrid.RowSelectorUIElement)
{
//Get the Row from the RowSelectorsUIElement
objRowSelectorUIElement = (Infragistics.Win.UltraWinGrid.RowSelectorUIElement)parent;
objRow = (Infragistics.Win.UltraWinGrid.UltraGridRow)objRowSelectorUIElement.GetContext(typeof(Infragistics.Win.UltraWinGrid.UltraGridRow));
//Get the Index of the Row, so we can use it as a row number.
RowNumber = objRow.Index;
//Check to see if the TextUIElement is already created. Since
//The RowSelectorsUIElement never has children by default, we
//can just check the count.
if (parent.ChildElements.Count == 0)
{
//Create a new TextUIElement and parent it to the RowSelectorUIElement
objTextUIElement = new Infragistics.Win.TextUIElement(parent, RowNumber.ToString());
parent.ChildElements.Add(objTextUIElement);
}
else
{
//There's already a TextUIElement here, so just set the Text
objTextUIElement = (Infragistics.Win.TextUIElement)parent.ChildElements[0];
objTextUIElement.Text = RowNumber.ToString();
}
//Position the TextUIElement into the RowSelectorUIElement
objTextUIElement.Rect = parent.RectInsideBorders;
//Return True let the grid know we handled this event.
//This doesn't really do anything, since the grid
//does not create any child elements for this object, anyway.
return true;
}
//Return false to let the grid know we did not handle the event.
//This doesn't really do anything, since the grid
//does not create any child elements for this object, anyway.
return false;
}
#endregion
}
}
Create a "currently selected item" member in the class where the button and the text edit are declared.
In the button selection event listener assign the event target to this member. Then use it in the text edit event listener.
For example:
// It's a declaration of the member variable
private var m_current_btn:Button = null;
// It's an event listener for your button
private function on_selection_change(event:Event):void
{
m_current_btn = event.target as Button;
// button_x and button_y are two text edits
button_x.text = m_current_button.x.toString();
button_y.text = m_current_button.y.toString();
}
// Event listener to track changes in the coordinate text inputs
private function on_coordinate_textedit_change(event:Event):void
{
if (m_current_btn != null)
{
m_current_btn.x = parseInt(button_x.text);
m_current_btn.y = parseInt(button_y.text);
}
}