addActionListener(other Class) - java

I have a class PanelLogiciel ( a cardLayout to show interface for connexion or interface for the market) and the Class PanelAcces(interface for connection):
I would like to use an ActionListener on a JButton from PanelAcces,if you use the JButton,PanelLogiciel will change from PanelAcces to another JPanel with the CardLayout. Hope you can help and sorry if it's a stupid question but can't find ...
package e_commerce;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PanelLogiciel extends JPanel implements ActionListener {
CardLayout diaporama = new CardLayout();
PanelAcces panelAcces;
PanelSite panelSite;
String connexion = new String("connexion");
String site = new String("site");
Connection connexBD;
public PanelLogiciel(){
this.setLayout(diaporama);
panelAcces = new PanelAcces(this);
panelSite = new PanelSite();
//PanelProduit panelProduit = new PanelProduit();
//PanelPanier panelPanier = new PanelPanier();
//this.add(panelProduit);
//this.add(panelPanier);
this.add(panelAcces,connexion);
this.add(panelSite,site);
}
public void actionPerformed(ActionEvent parEvt){
Object source = parEvt.getSource();
if (source == panelAcces.boutonConnexion){
try {
if (SQL.methodeConnexion(connexBD, panelAcces.entrerIdentifiant.getText(), panelAcces.entrerMotDePasse.getText()) == 0){
System.out.println("cc");
diaporama.show(panelSite,site);
}
else {
System.out.println("marche ap");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
and the Class PanelAcces(interface for connection):
package e_commerce;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class PanelAcces extends JPanel implements ActionListener{
JLabel labelIdentifiant; //= new JLabel("Identifiant:");
JTextField entrerIdentifiant; //= new JTextArea();
JLabel labelMotDePasse; //= new JLabel("Mot de passe:");
JTextField entrerMotDePasse; //= new JTextArea();
JButton boutonConnexion = new JButton("Connexion");
PanelLogiciel panelLogiciel;
public PanelAcces(PanelLogiciel parLogiciel){
panelLogiciel = parLogiciel;
labelIdentifiant = new JLabel("Identifiant:");
entrerIdentifiant = new JTextField(10);
labelMotDePasse = new JLabel("Mot de passe:");
entrerMotDePasse = new JTextField(10);
this.add(labelIdentifiant);
this.add(entrerIdentifiant);
//entrerIdentifiant.addActionListener(this);
this.add(labelMotDePasse);
this.add(entrerMotDePasse);
//entrerMotDePasse.addActionListener(this);
this.add(boutonConnexion);
boutonConnexion.addActionListener(panelLogiciel);
}
public void actionPerformed(ActionEvent parEvt) {
Object source = parEvt.getSource();
if (source == boutonConnexion){
System.out.println("beub");
}
}
}

Related

how to update the JList in JScrollPane when I changed the cursor,Also,I'd want to know how to add video from http video API

When I started my project about a Dictionary from Chinese to English, I got some problems.First,
I used the addCaretListener method to realize that when I changed the cursor in wordLine,changed the context in JList and show the result.But here a problem comes,If I changed the cursor, the JList were clear,and not show anything.
Another problem is I want to invoke the http video API to realize the video play. As I add the video button and add the audio method to realize ,I failed.
I'll appreciate if you can solve them.
This is part of my code:
import java.applet.*;
import java.awt.*;
import java.net.*;
import java.lang.Thread;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import org.omg.CORBA.portable.InputStream;
import org.omg.CORBA.portable.OutputStream;
import javax.swing.JScrollPane;
import javax.swing.JList;
public class DictionaryWindow extends JFrame{
public ArrayList<String> wordList = new ArrayList<>();
public ArrayList<String> meaningList = new ArrayList<>();
private JButton searchBn=new JButton("搜索");
private JTextField wordLine=new JTextField();
private JButton addToNote=new JButton("添加入生词本");
private JButton videoBn=new JButton();
private JScrollPane scroll=new JScrollPane();
private String waitForSearch;
private String local="151310421";
private JList list;
private int index=0;
private int wordLocation;//查找想要找单词的序号
private JTextField showMean=new JTextField();
private String []str;
private String []str1;
//private String []str2;
private TrieTree trie=new TrieTree();
private Vector <String>v=new Vector <String>();
private DefaultListModel dlm = new DefaultListModel();
private boolean wait=false;
public DictionaryWindow()
{
toTrieTree();
}
public void dictionaryInit()
{
this.setResizable(false);
this.setLayout(null);
this.setSize(600,500);
str=wordList.toArray(new String[wordList.size()]);
str1=meaningList.toArray(new String[meaningList.size()]);
for(int i=0;i<str.length;i++)
{
dlm.addElement(str[i]);
}
list=new JList(dlm);//v To str
scroll.setViewportView(list);
scroll.setPreferredSize(new Dimension(200,200));
searchBn.setBounds(200, 100, 60, 25);
wordLine.setBounds(60, 100, 100, 25);
addToNote.setBounds(60, 150, 200, 25);
scroll.setBounds(300, 200, 100, 200);
showMean.setBounds(300, 100, 200, 25);
videoBn.setBounds(450,100,100,25);
wordLine.addCaretListener(new CaretListener(){
public void caretUpdate(CaretEvent e){
trie.searchNextWords(wordLine.getText());
String []str2=new String[]{};
str2=null;
str2=trie.wordL.toArray(new String[trie.wordL.size()]);
//str=str2;
//v.clear();
//for(int i=0;i<str2.length;i++)
//v.add(str2[i]);`
((DefaultListModel)list.getModel()).removeAllElements();
for(int i=0;i<str2.length;i++)
{
dlm.addElement(str2[i]);
}
list.setModel(dlm);
scroll.setViewportView(list);
//JScrollPane scroll=new JScrollPane(list);
//scroll.setPreferredSize(new Dimension(200,200));
//scroll.setBounds(300, 200, 100, 200);
//add(scroll);
}
});
addToNote.addActionListener(e->{
String writeFilePath = local + ".txt";
try {
String note = wordLine.getText() + " " + showMean.getText();
Files.write(Paths.get(writeFilePath), Arrays.asList(note), StandardOpenOption.APPEND);
} catch (Exception e1) {
System.err.println("File Writing error\n" + e);
}
});
videoBn.addActionListener(e->{
class sound extends Applet{
AudioClip loopClip;
public void init()
{
String word=wordLine.getText();
String httpVideo="http://dict.youdao.com/dictvoice?type=1&audio="+word;
try {
loopClip=getAudioClip(new URL(httpVideo));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public sound(){
init();
loopClip.play();
}
}
sound s=new sound();
});
searchBn.addActionListener(e->{
wordLocation=0;
waitForSearch=wordLine.getText();
while(!waitForSearch.equals(str[wordLocation]))
{
wordLocation++;
}
showMean.setText(str1[wordLocation]);
});
list.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(e.getClickCount()==2)
twoClick(list.getSelectedValue());
}
private void twoClick(Object selectedValue) {
// TODO Auto-generated method stub
wordLine.setText((String) selectedValue);
}
});
Border border = BorderFactory.createMatteBorder(1, 1, 2, 2, Color.RED);
showMean.setBorder(border);
showMean.setEditable(false);
this.add(searchBn);
this.add(wordLine);
this.add(addToNote);
this.add(scroll);
this.add(showMean);
this.add(videoBn);
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
/* class doubleClick extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if(e.getClickCount() ==2) {
wordLine.setText((JList)e.getSource());
}
}
}*/
public void toTrieTree()
{
int i=0;
while(i<wordList.size())
{
trie.insert(str[i],str1[i]);
dlm.addElement(str[i]);
i++;
}
}
}

Java selectable JLabel

I have made a GUI with a gallery panel which shows images held in JLabels. I need to make JLabel highlightable and then remove it if the user clicks remove. Is there a way or should I change my approach?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class GalleryPanel extends JPanel
{
private static final long serialVersionUID = 1L;
private int currentImage;
private JLabel[] images;
private final int MAX_IMAGES = 12;
private JScrollPane scrollPane;
private JList<JLabel> imageGallery;
private DefaultListModel<JLabel> listModel;
private JPanel imageHolder;
public void init()
{
setLayout(new BorderLayout());
imageHolder = new JPanel();
imageHolder.setLayout(new BoxLayout(imageHolder, BoxLayout.PAGE_AXIS));
imageHolder.setSize(getWidth(), getHeight());
images = new JLabel[MAX_IMAGES];
listModel = new DefaultListModel<JLabel>();
listModel.addElement(new JLabel(new ImageIcon("Untitled.png")));
imageGallery = new JList<JLabel>(listModel);
imageGallery.setBackground(Color.GRAY);
imageGallery.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
imageGallery.setLayoutOrientation(JList.VERTICAL);
imageGallery.setFixedCellHeight(50);
imageGallery.setFixedCellWidth(100);
scrollPane = new JScrollPane(imageHolder);
scrollPane.setBackground(Color.RED);
add(scrollPane, BorderLayout.CENTER);
}
public void addImageToGallery(File file)
{
if ( currentImage <= images.length - 1)
{
BufferedImage bufImage = null;
try
{
bufImage = ImageIO.read(file); //tries to load the image
}
catch (Exception e)
{
System.out.println("Unable to load file " + file.toString());
}
Image resizedImage = bufImage.getScaledInstance(bufImage.getWidth()/5, bufImage.getHeight()/5, Image.SCALE_SMOOTH);
ImageIcon icon = new ImageIcon(resizedImage);
images[currentImage] = new JLabel(icon, JLabel.CENTER);
//images[currentImage].setSize(resized);
//images[currentImage
images[currentImage].setBorder(new TitledBorder(new LineBorder(Color.GRAY,5), file.toString()));
imageHolder.add(images[currentImage]);
revalidate();
repaint();
currentImage++;
}
else
{
throw new ArrayIndexOutOfBoundsException("The gallery is full");
}
}
public final int getMaxImages()
{
return MAX_IMAGES;
}
public Dimension getPreferredSize()
{
return new Dimension(300, 700);
}
}
So you first of call should be the tutorals
How to use Lists
Selecting items in a list
Adding items to and removing items from a list
Which will give you the basic information you need to proceeded.
Based on your available code, you should not be adding a JLabel to the ListModel, you should never add components to data models, as more often than not, Swing components have there own concept of how they will render them.
In your case, you're actually lucky, as the default ListCellRenderer is based on a JLabel and will render Icon's automatically, for example
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
DefaultListModel model = new DefaultListModel();
model.addElement(new ImageIcon("mt01.jpg"));
model.addElement(new ImageIcon("mt02.jpg"));
model.addElement(new ImageIcon("mt03.jpg"));
JList list = new JList(model);
list.setVisibleRowCount(3);
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
System.out.println(list.getSelectedIndex());
}
}
});
JFrame frame = new JFrame("Test");
frame.add(new JScrollPane(list));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

how to add jpanel to jpanel in java

I have a problem when i add a jpanel to existing jpanel!
i want jlist at center loction and jbuttom in south location!
i can see the jlist, but the jbuttom won't show on!
I'm using Eclipse 3.0 version.
this is my code:
package classes;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.LinkedList;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class JPanelDecorator extends JPanel implements ActionListener
{
private static final long serialVersionUID = 1L;
private JList<String> list = null;
private JButton Change=null;
public JPanelDecorator()
{
super();
setLayout(new BorderLayout());
setSize(450 ,400);
String animals_list[] = new String[AquaPanel.swims.size()];
LinkedList<Swimmable> ir = new LinkedList<Swimmable>(AquaPanel.swims);
for(int i=0;i<ir.size();i++)
{
animals_list[i]=(i+1+". "+ir.get(i).toString());
}
list = new JList<String>(animals_list );
list.setFont(new Font("Tahoma",Font.BOLD,15));
list.setSize(450, 300);
add(list,BorderLayout.CENTER);
Change = new JButton("Change Color");
Change.addActionListener(this);
add(Change,BorderLayout.CENTER);
repaint();
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
please help!
You have a subtle bug. In the constructor of JPanelDecorator you have :
public JPanelDecorator()
{
//....
add(list,BorderLayout.CENTER);
//...
add(Change,BorderLayout.CENTER); // center again...
//...
}
But what you need is this:
public JPanelDecorator()
{
//....
add(list,BorderLayout.CENTER);
//...
add(Change,BorderLayout.SOUTH); // south
//...
}

Jung Factory For Custom Object

I'm new to jung and i need help on how to learn. I searched a lot of places, but i haven't found a step by step guide. Im trying to create a gui that will add vertexes only if they selected the right menu, and entered a proper name.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JMenu;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.algorithms.layout.StaticLayout;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.EditingModalGraphMouse;
import edu.uci.ics.jung.visualization.control.ModalGraphMouse;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import org.apache.commons.collections15.Factory;
public class demo3 {
Graph<State,Transition> g;
Factory<State>stateList;
Factory<Transition>linelist;
ArrayList<State>states = new ArrayList<State>();
ArrayList<Transition>lines = new ArrayList<Transition>();
private static JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
initialize();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
demo3 sgv = new demo3();
Layout<State, Transition> layout = new StaticLayout(sgv.g);
layout.setSize(new Dimension(300,300));
VisualizationViewer<State,Transition> vv = new VisualizationViewer<State,Transition>(layout);
vv.setPreferredSize(new Dimension(350,350));
demo3 window = new demo3();
EditingModalGraphMouse gm = new EditingModalGraphMouse(vv.getRenderContext(),
sgv.stateList, sgv.linelist);
vv.setGraphMouse(gm);
gm.setMode(ModalGraphMouse.Mode.EDITING);
frame.getContentPane().add(vv);
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public demo3() {
g = new SparseMultigraph<State, Transition>();
stateList = new Factory<State>() {
public State create() {
State newState = new State();
states.add(newState);
return newState;
}
};
linelist = new Factory<Transition>(){
public Transition create(){
Transition line = new Transition();
lines.add(line);
return line;
}
};
}
/**
* Initialize the contents of the frame.
*/
private static void initialize() {;
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnAddStateOr = new JMenu("Add State or Transition");
menuBar.add(mnAddStateOr);
JPanel panel = new JPanel();
panel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
String stateName = JOptionPane.showInputDialog("Enter the value of the state");
State newState = new State(Integer.parseInt(stateName));
}
});
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
I need to know how to label each circle based on the state name they enter. Also any tips for learning JUNG would help.

Look and feel is not updating in Swing JTabbedPane

I have created an application in Java Swing. I offer the option to change the look and feel of the application from a menu, but after adding a new tab in JTabbedPane, it is not getting updated with the new look and feel.
I have already used this code:
Window windows[] = Frame.getWindows();
for(Window window : windows) {
SwingUtilities.updateComponentTreeUI(window);
}
Leveraging #Andrew's example and this old thing, it seems to work for me.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
/**
* #see https://stackoverflow.com/a/11949899/230513
* #see https://stackoverflow.com/a/5773956/230513
*/
public class JTabbedText {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
private final JTabbedPane jtp = new JTabbedPane();
#Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtp.addTab("Model", createPanel());
jtp.addTab("View", createPanel());
jtp.addTab("Control", createPanel());
f.add(createToolBar(f), BorderLayout.NORTH);
f.add(jtp, BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
private static JToolBar createToolBar(final Component parent) {
final UIManager.LookAndFeelInfo[] available =
UIManager.getInstalledLookAndFeels();
List<String> names = new ArrayList<String>();
for (LookAndFeelInfo info : available) {
names.add(info.getName());
}
final JComboBox combo = new JComboBox(names.toArray());
String current = UIManager.getLookAndFeel().getName();
combo.setSelectedItem(current);
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
int index = combo.getSelectedIndex();
try {
UIManager.setLookAndFeel(
available[index].getClassName());
SwingUtilities.updateComponentTreeUI(parent);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
});
JToolBar bar = new JToolBar("L&F");
bar.add(combo);
return bar;
}
private static Box createPanel() {
Box panel = new Box(BoxLayout.X_AXIS);
JLabel label = new JLabel("Code: ", JLabel.LEFT);
label.setAlignmentY(JLabel.TOP_ALIGNMENT);
JTextArea text = new JTextArea(4, 16);
text.setAlignmentY(JTextField.TOP_ALIGNMENT);
text.append("#" + panel.hashCode());
text.append("\n#" + label.hashCode());
text.append("\n#" + label.hashCode());
panel.add(label);
panel.add(text);
return panel;
}
}

Categories