Add object to panel on every click - java

This is my actionListener for a popup menu button i want to add this picture on the panel after every its clicked
mntmNewMenuItem.addActionListener(new ActionListener() {
//This method will be called whenever you click the button.
int i;
public void actionPerformed(ActionEvent e) {
try {
label.setIcon(new ImageIcon
(new URL("file:/C:/Users/Ashad/JunoWorkspace/FYP1/table.png")));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
panel.add(label);
//redraw panel after addition
panel.validate();
panel.repaint();
handleDrag(label);
}
});

you can only add a UI object once.
if you want just a single instance to be added, you need to remove that element 1st then add. (but it doesn't seem logical removing then adding).
instead you can create a Label() object inside actionperformed
public void actionPerformed(ActionEvent e) {
label = new Label();//Added
try {
label.setIcon(new ImageIcon
(new URL("file:/C:/Users/Ashad/JunoWorkspace/FYP1/table.png")));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}

Related

How to create a shortcut key for a JLabel?

enter image description here
I have a list JLabel. I want when click a label content display in JTextArea the same. Why when I click the label, the text area does not display?
The code:
jLabel0.setText(namelist.get(0));
jLabel1.setText(namelist.get(1));
jLabel2.setText(namelist.get(2));
jLabel3.setText(namelist.get(3));
jLabel4.setText(namelist.get(4));
jLabel5.setText(namelist.get(5));
//String b[]={"jLabel4","jLabel5","jLabel7","jLabel8","jLabel9","jLabel10"};
for (int i=0;i<k;i++){
String f=String.valueOf(i);
JLabel jlb = new JLabel("jLabel"+f);
String Af=file_list.get(i);
FileReader F=new FileReader(Af);
jlb.addMouseListener(new MouseListener(){
public void mouseReleased(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
if(e.getClickCount()==1)
{
try {
jTextArea3.read(F,"");
} catch (IOException ex) {
Logger.getLogger(FAKENEWS.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
}
You can simply achieve it using JButton and just by making the button look like a label.
You will want to do the following once you have created the button:
setFocusPainted(false);
setMargin(new Insets(0, 0, 0, 0));
setContentAreaFilled(false);
setBorderPainted(false);
setOpaque(false);
You may want to exclude setFocusPainted(false) if you want it to actually paint the focus (e.g. dotted line border on Windows look and feel).
And after that you may use the button event handlers to do your desired action.

Added Listener to button which is dynamically createing?

I have problem, i dynamically create the buttons (users write text in JtextArea then is create the new button) and when user clicked in button this text is writing in JtextPane.
I dont know why doing this?
The buttons is created but when user clicked on button doing nothing.
DODAJNOWYButton.addMouseListener(new NewMouseListener(textPane1) {
#Override
public void mouseClicked(MouseEvent e) {
String text = textArea2.getText();
bar.add(new JButton(""+text));
bar.validate();
bar.repaint();
try{
doc.insertString(doc.getLength(),""+text,null);
} catch (BadLocationException e1) {
System.out.println(e);
}
super.mouseClicked(e);
}
});
You can use addClickHandler():
JButton yourButton = new JButton(""+text);
yourButton.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
//do something
}
}

Mouse Listener implementation

I am learning Java and trying to implement a MouseListener for the first time. I have read the java doc
MouseListener but my code doesnt work, as in nothing happens when i press the button. Here is a jbutton with a pressed and released event. Can someone explain where i have gone wrong?
JButton upButton_1 = new JButton("Up");
upButton_1.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent pevt) {
upButtonPressPerformed(pevt);
}
public void mouseReleased(MouseEvent revt) {
upButtonReleasePerformed(revt);
}
public synchronized void upButtonPressPerformed(
MouseEvent pevt) {
resultsTextArea.setText("Up Button Activated, String: " + downString);
try{
//See Above comments for sending ASCII String
byte[] bytes = DatatypeConverter.parseHexBinary(upString);
TwoWaySerialComm.SerialWriter sw = new TwoWaySerialComm.SerialWriter(
twoWaySerCom.serialPort.getOutputStream());
sw.out.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized void upButtonReleasePerformed(
MouseEvent revt) {
resultsTextArea.setText("Up Button released, String: " + downString);
try{
//See Above comments for sending ASCII String
byte[] bytes = DatatypeConverter.parseHexBinary(upString);
TwoWaySerialComm.SerialWriter sw = new TwoWaySerialComm.SerialWriter(
twoWaySerCom.serialPort.getOutputStream());
sw.out.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
});
ActionListener is what you are looking for if you want to work with buttons.
JButton button = new JButton("SomeButton");
button.addActionListener(this);
void ActionPerformed(ActionEvent e) {
if(e.getSource() == button) {
// do whatever you want if button is clicked
}
}
Or you can use anonymous inner class:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//do whatever you want
}
});
//or the Java8 version
button.addActionListener((e) -> {
//do whatever you want
});
Whit MouseListener you can listen to events like:
MouseClicked, MouseEntered, MouseExited, MousePresse, MouseReleased.
You could use these, but for button click its more logical to listen to your buttons not your mouse.

JList to frame from JComboBox selection

I have .txt files and I read them to a JList, then I want to select a name of a file from a JComboBox, read that file, create the list and appear on the frame inside of a JScrollPane.
I have almost everything working the only problem is that I can't add the scroll pane with the list to the frame correctly and the list only appears when I press the button "envia". The way I have my code inserting the list to the scroll pane and then to the window is not correct because the scroll pane are being inserted on top of each other, but its the closest I got to wokring.
I want it to appear on the the scroll pane and on the frame correctly when I press on the combo box and not when I press "envia". I don't understand why the list only appears when I press that button.
combo2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
falarpara = combo2.getSelectedItem().toString();
try {
lista = f.getList(user, falarpara);
janela.add(lista.getlist());
JScrollPane j = new JScrollPane(lista.getlist());
janela.add(j);
janela.validate();
} catch (FileNotFoundException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
}
});
envia.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String a = new String(user + ":" + " " + txt.getText());
f.escreve(user, falarpara, a);
lista.add(a);
txt.setText(null);
}
});

Avoiding deletion of first row when deleting selected row

Before I added the Yes/No options, the delete button deleted only the desired row. However, after adding the Yes/No Option, the first row in the database gets deleted along with the desired row.
b6.addActionListener (new ActionListener ()
{
JFrame f4=new JFrame("Are you sure?");
JPanel p4=new JPanel();
JButton yes=new JButton ("Yes");
JButton no=new JButton ("No");
public void actionPerformed (ActionEvent e)
{
p4.add (yes);
p4.add (no);
f4.add (p4);
f4.setVisible (true);
f4.setSize (300,200);
yes.addActionListener (new ActionListener ()
{
public void actionPerformed (ActionEvent e)
{
try
{
f4.dispose();
rs.deleteRow();
rs.close();//
st.close();//to prevent gap in database
st=conn.createStatement(rs.TYPE_SCROLL_INSENSITIVE,rs.CONCUR_UPDATABLE);
String sql="select * from trial1";
rs= st.executeQuery (sql);
rs.next();
t.setText (rs.getString ("Firstname"));
t1.setText (rs.getString ("Lastname"));
}
catch (Exception ex)
{
}
}
});
no.addActionListener (new ActionListener ()
{
public void actionPerformed (ActionEvent e)
{
f4.dispose();
}
});
}
});
Tentative answer, as I have no way of checking this right now:
I think the fact that you are adding the ActionListener to yes from within the b6's actionPerformed() when it is called means that the second time you click it (b6), you actually have two action listeners on the same yes button.
Therefore when you press the yes button, the action is performed twice. So the first time, the rs cursor is set to the row you selected. But in that action, you set rs to a new query (select * from trial1) in order to fill up the fields.
So when the second action listener is activated, that's where rs is pointing - to the first record of this last query. And that's the record that will get deleted.
To avoid all this, you have to add the ActionListener to yes outside of actionPerformed() - perhaps in an initializer block?
I fixed the glitch by making a small alteration to the position of the f4.dispose(), and also by including a try and catch block in the ActionListener for b6.
b6.addActionListener (new ActionListener ()
{
JFrame f4=new JFrame("Are you sure?");
JPanel p4=new JPanel();
JButton yes=new JButton ("Yes");
JButton no=new JButton ("No");
public void actionPerformed (ActionEvent e)
{
p4.add (yes);
p4.add (no);
f4.add (p4);
f4.setVisible (true);
f4.setSize (300,200);
try {
yes.addActionListener (new ActionListener ()
{
public void actionPerformed (ActionEvent e)
{
try
{
rs.deleteRow();
rs.close();
st.close();
st=conn.createStatement(rs.TYPE_SCROLL_INSENSITIVE, rs. CONCUR_UPDATABLE);
String sql="select * from trial1";
rs= st.executeQuery (sql);
rs.next();
t.setText (rs.getString ("Firstname"));
t1.setText (rs.getString ("Lastname"));
f4.dispose();
}
catch (Exception ex)
{
}
}
});
no.addActionListener (new ActionListener ()
{
public void actionPerformed (ActionEvent e)
{
f4.dispose();
}
});
}
catch (Exception ex)
{
}
}
});

Categories

Resources