Adding a button in one column of a table - java

I am using lwuit to create a table with some values and a row listener. in j2me.
I am trying to add a button and a listener to it so that i have a value in the table by which i can implement a row listener. I have used the following link: http://lwuit.blogspot.in/2010/06/headon-that-table.html. But when i add the button to the table it comes to the end of the table because the table model only accepts the object as its input that is added to the table.
By using this link i added the button by the button by the following command:
container.addComponent(new Button("Details"));
Also i tried to create a grid layout or a table layout and added buttons with the number rows*columns but still the listener for the last button works, not for the rest. Any ideas on how can implement this logic. My actual task is to add a row click listener to the table. Any conceptual or coding help is appreciated.

Mean while i got the answer for a friend which i am sharing with you. He said me to add buttons in grid or table layout and the buttons should be adding like a 2d array so that their listeners are properly managed.
public class Midlet extends MIDlet implements ActionListener{
Form f;
Container c;
private int ROWS=100;
Button b[][];
private int COLUMNS=3;
public void startApp() {
Display.init(this);
f=new Form("grid with buttons");
c=new Container(new TableLayout(ROWS, COLUMNS));
b=new Button[ROWS][COLUMNS];
c.setScrollableX(true);
c.setScrollableY(true);
//c.setDraggable(true);
addElements();
//f.setScrollable(false);
f.setScrollVisible(true);
f.addComponent(c);
f.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void addElements()
{
for(int i=0;i<ROWS;i++)
{
for(int j=0;j<COLUMNS;j++)
{
b[i][j]=new Button(i+" sdkljf "+j);
c.addComponent(b[i][j]);
b[i][j].addActionListener(this);
}
}
}
/**
*
* #param message message to be displayed
* #param title title of the alert
*/
public void showMsg(String message, String title)
{
final Dialog d=new Dialog(title);
d.setLayout(new GridLayout(1, 1));
Button b=new Button("Ok");
TextArea msg=new TextArea(message);
msg.setUIID(message);
msg.setEditable(false);
//dialogContainer.addComponent(msg);
//dialogContainer.addComponent(b);
d.addComponent(msg);
d.addComponent(b);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
d.dispose();
}
});
d.show();
}
public void actionPerformed(ActionEvent evt) {
for(int i=0;i<ROWS;i++)
{
for(int j=0;j<COLUMNS;j++)
{
if(b[i][j]==evt.getComponent())
{
showMsg(i+","+j, "sl;dkf;");
}
}
}
}
}

Related

How to use button from one class in another class using swingworker

I am trying to get a progress bar to load after a button has been clicked the button is in another class and the swing worker is a class within a class. Here is some code
public class BigramProgbarTest extends JFrame
{
//Create the connection to Neo4j
//MAIN METHOD
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
//INITIALIZE JFRAME FORM
BigramProgbarTest form=new BigramProgbarTest();
form.setVisible(true);
}
});
}
private static JButton btn;
//CONSTRUCTOR
public BigramProgbarTest()
{
//the form
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(200,200,800,300);
setTitle("Netword Data Table");
getContentPane().setLayout(null);
//ADD SCROLLPANE
JScrollPane scroll=new JScrollPane();
scroll.setBounds(70,80,600,200);
getContentPane().add(scroll);
//THE TABLE
final JTable table=new JTable();
scroll.setViewportView(table);
//THE MODEL OF THE TABLE
DefaultTableModel model=new DefaultTableModel()
{
}
}
};
//Create and run the query here for table
//ASSIGN THE MODEL TO TABLE
table.setModel(model);
model.addColumn("Select"); //Column for check boxes
model.addColumn("Bigrams"); //Column for Bigrams
//A while loop here
} //ENDWHILE
//OBTAIN SELECTED ROW
// BigramProgbarTest fr = new BigramProgbarTest();
JButton btn=new JButton("Get Selected");
btn.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{//A method for the button to do something with seleted rows
}
}
}
});
//ADD BUTTON TO FORM
btn.setBounds(71,39,130,30);
getContentPane().add(btn);
So here you can see that the class has tables and a scroll pane (just showed them in case they have an impact). The I have a swing worker class and progress bar in another class within this class. Here is some code from the swingworker class.
JProgressBar progressBar = new JProgressBar();
progressBar.setBounds(211, 42, 146, 14);
getContentPane().add(progressBar);
ProgressWorker worker = new ProgressWorker(progressBar);
worker.execute();
}
class ProgressWorker extends SwingWorker<Void, Integer> {
private final JProgressBar progress;
public ProgressWorker(JProgressBar progress) {
this.progress = progress;
}
//btn.addActionListener(new ActionListener() //Trying to find somewhere to use this
#Override
protected Void doInBackground() throws Exception { //This should be done after a button click
//Some code and for loop for the progress bar
final int progr = (int) ((100L * (results.length - i2)) / results.length);
publish(progr);
}//ENDFOR each record// | | ENDFOR each record//
}
return null;
}
//final int progr = ((int) ((100L * (recordLoop - firstRecord)) / (lastRecord-firstRecord)));
#Override
protected void process(List<Integer> chunks) {
progress.setValue(chunks.get(chunks.size() - 1));
super.process(chunks); //This is the process of how the progress bar will load
}
#Override
protected void done() {
progress.setValue(100); //This is the value when process is complete
}
}
}
Now what I expect this to do is run the swingworker class after the button has been clicked.
At the moment the progress bar just loads to right to the end before clicking anything and even before I even select a checkbox. So I want the swingworker to be able to listen to the button click from the main class before performing any tasks.

Java how to assign id to button and retrieve them?

I'm getting stuck while building a forum like application which has a vote button.
I have vote up and vote down button for each content which are automatically generated. I want this button to only display the up and down arrow but not any text or label.. how can i find out which button is pressed?
Automated content..
ImageIcon upvote = new ImageIcon(getClass().getResource("vote_up.png"));
ImageIcon downvote = new ImageIcon(getClass().getResource("vote_down.png"));
JButton vote_up = new JButton(upvote);
JButton vote_down = new JButton(downvote);
vote_up.addActionListener(voting);
vote_down.addActionListener(voting);
Action voting = new AbstractAction(){
#Override
public void actionPerformed(ActionEvent e){
//What to do here to find out which button is pressed?
}
};
any help is appreciated.
public void a(){
int crt_cnt = 0;
for(ClassA temp : listofClassA)
{
b(crt_cnt);
crt_cnt++;
}
}
public void b(crt_cnt){
//draw button
}
As from above, I have multiple vote_up and vote_down button created by the b function, how can i differentiate which crt_cnt is the button from?
There are multiple ways you might achieve this
You could...
Simply use the source of the ActionEvent
Action voting = new AbstractAction(){
#Override
public void actionPerformed(ActionEvent e){
if (e.getSource() == vote_up) {
//...
} else if (...) {
//...
}
}
};
This might be okay if you have a reference to the original buttons
You could...
Assign a actionCommand to each button
JButton vote_up = new JButton(upvote);
vote_up.setActionCommand("vote.up");
JButton vote_down = new JButton(downvote);
vote_down .setActionCommand("vote.down");
//...
Action voting = new AbstractAction(){
#Override
public void actionPerformed(ActionEvent e){
if ("vote.up".equals(e.getActionCommand())) {
//...
} else if (...) {
//...
}
}
};
You could...
Take full advantage of the Action API and make indiviual, self contained actions for each button...
public class VoteUpAction extends AbstractAction {
public VoteUpAction() {
putValue(SMALL_ICON, new ImageIcon(getClass().getResource("vote_up.png")));
}
#Override
public void actionPerformed(ActionEvent e) {
// Specific action for up vote
}
}
Then you could simply use
JButton vote_up = new JButton(new VoteUpAction());
//...
Which will configure the button according to the properties of the Action and will trigger it's actionPerformed method when the button is triggered. This way, you know 100% what you should/need to do when the actionPerformed method is called, without any doubts.
Have a closer look at How to Use Actions for more details
You can detect by using the method getSource() of your EventAction
Action voting = new AbstractAction(){
#Override
public void actionPerformed(ActionEvent e){
if (e.getSource() == vote_up ) {
// vote up clicked
} else if (e.getSource() == vote_down){
// vote down clicked
}
}
};
hey thanks for all the help and assistance! I've finally got it! I solved it by
assigning a text on the button, +/- for vote up or down, followed by the content id which i required, then change the font size to 0
vote.setText("+"+thistopic.content.get(crt_cnt).get_id());
vote.setFont(heading.getFont().deriveFont(0.0f));
after that i could easily trace which button is pressed by comparing to the
actionEvent.getActionCommand()
which return the text on the button!
I would wrap the JButton similar to this:
JButton createMyButton(final JPanel panel, final String text,
final boolean upOrDown, final int gridx, final int gridy) {
final JButton button = new JButton();
button.setPreferredSize(new Dimension(80, 50));
final GridBagConstraints gbc = Factories.createGridBagConstraints(gridx,
gridy);
panel.add(button, gbc);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
myActionPerformed(text, upOrDown);
}
});
return button;
}
You could use an int instead of the text, if more convenient.

Clicking a JButton consecutively

Is there a way to know if a JButton was clicked consecutively? Consider my code.
public void actionPerformed(ActionEvent arg0) {
String bucky[] = new String[2];
String firstclick = null, secondclick = null;
clicks++;
if (clicks == 1) {
bucky[0] = firstclick;
} else if(clicks == 2) {
bucky[1] = secondclick;
if (bucky[0] == bucky[1]) {
//This JButton was clicked twice in a row.
}
}
This code checks the entire number of times my JButton was clicked and displays the message "This button was clicked twice in a row". What I want is to compare two clicks from that button and see if they come one after the other rather than counting the number of clicks made. Or is there a built-in function that does this?
Just use a field remembering what the last clicked button was:
private JButton lastButtonClicked;
...
someButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (lastButtonClicked == e.getSource()) {
displayError();
}
else {
lastButtonClicked = (JButton) e.getSource();
doSomething();
}
}
});
Of course, you'll have to do the same thing with all the other buttons.
I have a different approach to your problem:
You want to not allow the user to press the same button in some group of buttons twice in a row.
You're solutions so far have tried to check which button was pressed last, and then warn the user if the same button has been pressed in a row.
Perhaps a better solution is to create a construct that simply doesn't allow the user to press the same button twice in a row.
You can create your ButtonGroup like object that selectively disables the last button pressed, and enables all the other buttons.
You would give this class an add(AbstractButton btn) method to allow you to add all the buttons that you wish to behave this way to it. The button would then be added to an ArrayList.
You would give it a single ActionListener that listens to all the buttons. Whenever the actionPerformed method has been pressed, it enables all of the buttons, and then selectively disables the last button pressed.
For instance consider my class below:
public class NoRepeatButtonGroup implements ActionListener {
private List<AbstractButton> btnList = new ArrayList<>();
public void add(AbstractButton btn) {
btnList.add(btn);
btn.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent evt) {
for (AbstractButton btn : btnList) {
btn.setEnabled(true);
}
((AbstractButton) evt.getSource()).setEnabled(false);
}
public void reset() {
for (AbstractButton btn : btnList) {
btn.setEnabled(true);
}
}
}
If you create a single object of this in your class that creates the buttons, and add each button to the object of this class, your code will automatically disable the last button pressed, and re-enable it once another button has been pressed.
You could use it like so:
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
NoRepeatButtonGroup noRepeatButtonGroup = new NoRepeatButtonGroup();
JButton yesButton = new JButton(new YesAction());
noRepeatButtonGroup.add(yesButton);
buttonPanel.add(yesButton);
JButton noButton = new JButton(new NoAction());
noRepeatButtonGroup.add(noButton);
buttonPanel.add(noButton);
JButton maybeButton = new JButton(new MaybeAction());
noRepeatButtonGroup.add(maybeButton);
buttonPanel.add(maybeButton);
For example, here is a proof of concept minimal runnable example:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class NoneInARowBtns {
private static void createAndShowGui() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
NoRepeatButtonGroup noRepeatButtonGroup = new NoRepeatButtonGroup();
int buttonCount = 5;
for (int i = 0; i < buttonCount; i++) {
JButton btn = new JButton(new ButtonAction(i + 1));
noRepeatButtonGroup.add(btn);
buttonPanel.add(btn);
}
JOptionPane.showMessageDialog(null, buttonPanel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class ButtonAction extends AbstractAction {
public ButtonAction(int i) {
super("Button " + i);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand() + " Pressed");
}
}
class NoRepeatButtonGroup implements ActionListener {
private List<AbstractButton> btnList = new ArrayList<>();
public void add(AbstractButton btn) {
btnList.add(btn);
btn.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent evt) {
for (AbstractButton btn : btnList) {
btn.setEnabled(true);
}
((AbstractButton) evt.getSource()).setEnabled(false);
}
public void reset() {
for (AbstractButton btn : btnList) {
btn.setEnabled(true);
}
}
}
When the above program runs, and when the second button is pressed, you will see that it is disabled:
Then when the 3rd button has been pressed, the 2nd is re-enabled, and the 3rd one is disabled:
And etc for the 4th button....
A global variable arrau of booleans, one for each button, set true on first click, set false or second, sjould do it

Swing combo box validation error

I have a simple program , that asks for an ip address to connect to , a user id and a password. The IP address is selected through / entered into a combobox.
When the user has entered the address and moved onto another field for entering data , a validation routine is called and in case of an invalid address entered , the combobox background changes to red and a label containing an error message is shown.
The problem is that when the user returns back to the ip combo box , the background color remains red.
it does not change.
How do i code the combobox to overcome my problem ?
Try to use FocusListener on your JComboBox. With it you can manage background color when you enter to combobox and exit from it. Heres simple example:
import java.awt.BorderLayout;
public class Example extends JFrame {
private JComboBox<String> box;
public Example() {
init();
}
private void init() {
box = new JComboBox<String>(getObjects());
box.setBackground(Color.RED);
box.addFocusListener(getFocusListener());
JTextField f = new JTextField();
add(box,BorderLayout.SOUTH);
add(f,BorderLayout.NORTH);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private FocusListener getFocusListener() {
return new FocusAdapter() {
#Override
public void focusGained(FocusEvent arg0) {
super.focusGained(arg0);
box.setBackground(Color.BLACK);
//validate();
}
#Override
public void focusLost(FocusEvent arg0) {
super.focusLost(arg0);
box.setBackground(Color.red);
//validate();
}
};
}
private String[] getObjects() {
return new String[]{"1","22","33"};
}
public static void main(String... s) {
Example p = new Example();
}
}

Make text in JButton not visible

I made a button and did a .setText() on it because I have to compare the value of the .setText() with something else.
I applied the .setText() to a JButton, but I don't want the text to be visible in my button.
If I do setVisible(false) then it hides the whole button, but I only want it to hide the text.
Is there an option for this? I've considered making a custom font and apply it on the text in the .setText() but I'm wondering if there's a more efficient option to my problem.
Thanks in advance guys.
EDIT: I can't use .setText(" ") because I have to compare the value within it.
You state:
EDIT: I can't use .setText(" ") because I have to compare the value within it.
Nonsense. As I've mentioned in a comment, set the JButton's text to " ", and don't use the JButton's text for comparison. Instead use its actionCommand easily obtained via getActionCommand(). Or use a HashMap<JButton, SomethingElse>.
You may consider changing the JButton's Action when you need to change its behavior and state which is easily done by calling setAction(...)
For example,
import java.awt.event.ActionEvent;
import javax.swing.*;
public class ButtonActions {
private static void createAndShowGui() {
JPanel mainPanel = new JPanel();
JButton myButton = new JButton();
StartAction startAction = new StartAction();
PauseAction pauseAction = new PauseAction();
BlankAction blankAction = new BlankAction();
startAction.setNextAction(pauseAction);
pauseAction.setNextAction(blankAction);
blankAction.setNextAction(startAction);
myButton.setAction(startAction);
mainPanel.add(myButton);
JFrame frame = new JFrame("ButtonActions");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class SwappingAction extends AbstractAction {
private Action nextAction;
public SwappingAction(String text) {
super(text);
}
public void setNextAction(Action nextAction) {
this.nextAction = nextAction;
}
public Action getNextAction() {
return nextAction;
}
#Override
/**
* super method needs to be called in child for swap to work
*/
public void actionPerformed(ActionEvent e) {
System.out.println("ActionCommand: " + e.getActionCommand());
((AbstractButton)e.getSource()).setAction(nextAction);
}
}
class StartAction extends SwappingAction {
public static final String START = "Start";
public StartAction() {
super(START);
}
#Override
public void actionPerformed(ActionEvent e) {
super.actionPerformed(e);
// start-specific code goes here
}
}
class PauseAction extends SwappingAction {
public static final String PAUSE = "Pause";
public PauseAction() {
super(PAUSE);
}
#Override
public void actionPerformed(ActionEvent e) {
super.actionPerformed(e);
// pause-specific code goes here
}
}
class BlankAction extends SwappingAction {
public static final String BLANK = " ";
public BlankAction() {
super(BLANK);
}
#Override
public void actionPerformed(ActionEvent e) {
super.actionPerformed(e);
}
}
Write buttonName.setText(" ") this will not display any name to the button. And whenever you feel like displaying the name (on any event) then set it again buttonName.setText("some text")
If you insist not to use setText(""), try setting same colour as a background colour and text colour. Check the below links
setBackground(java.awt.Color)
setForeground(java.awt.Color)
Why don't you name the first button " " (1 space).
the second: " " (2 spaces)
the third: " "(3 spaces) and so on ..
Now, compare:
if((event.getActionCommand()).equals(" "))
{ //1st button }
if((event.getActionCommand()).equals(" "))
{ //2nd button }
..and so on
where event is an object of ActionEvent
This way the buttons will have a unique names and be invisible.
Horrible coding, I know. But it does the trick ;)
Instead of .setText(), use .setTag() and .getTag() to attach some value to a View - including a Button - for later retrieval.
These methods are there directly for that kind of purpose.

Categories

Resources