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
//...
}
Related
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++;
}
}
}
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");
}
}
}
I am developing one java swing application for task remainder.Please find the below code for the same.But the problem is i am not able to maintain session here since i am using ScheduledExecutorService class which will help to trigger this Swing app one hour once.When triggering new one all changes has been made in previous session of app is gone.
Kindly help me on this and let me know how can i use session on my Swing application.
Example : If you run the below app yon can see two buttons when we click on button it will change color to "green" and status change to "Done" but when the application trigger after one minute all changes were erased launching as new one.
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.awt.Toolkit;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.Timer;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class Taskschdeuler {
private final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public static void main(String[] args) {
final Runnable beeper = new Runnable()
{
public void run()
{
// do anything here that you want to execute in a scheduler.
Task r=new Task();
}
};
final ScheduledFuture<?> beeper1 = scheduler.scheduleAtFixedRate(beeper, 0, 1, TimeUnit.MINUTES);
}
}
class Task extends JFrame implements ActionListener
{
JButton b1,b2,b3;
JLabel l1,l2;
public Task()
{
l1=new JLabel("Pending");
l2=new JLabel("Pending");
b1=new JButton("AVM DART");
b2=new JButton("HANDSHAKE");
b3=new JButton("Remind me later!!");
add(b1);
add(l1);
add(b2);
add(l2);
add(b3);
b1.setBackground(Color.PINK);
b2.setBackground(Color.PINK);
b3.setBackground(Color.CYAN);
b1.setPreferredSize(new Dimension(200, 50));
b2.setPreferredSize(new Dimension(200, 50));
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice defaultScreen = ge.getDefaultScreenDevice();
Rectangle rect = defaultScreen.getDefaultConfiguration().getBounds();
int x = (int) rect.getMaxX() -300;
int y = 500;
setLocation(x, y);
setLayout(new FlowLayout());
setVisible(true);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(e.getSource()==b1)
{
if (((Component)source).getBackground().equals(Color.GREEN))
{
((Component)source).setBackground(Color.PINK);
l1.setText("Pending");
}
else
{
((Component)source).setBackground(Color.GREEN);
l1.setText(" Done");
}
}
if(e.getSource()==b2)
{
if (((Component)source).getBackground().equals(Color.GREEN))
{
((Component)source).setBackground(Color.PINK);
l2.setText("Pending");
} else
{
((Component)source).setBackground(Color.GREEN);
l2.setText(" Done");
}
}
if(e.getSource()==b3)
{
setVisible(false);
}
}
}
I have this code below. How do I make this JComboBOx run in an Applet? I'm trying to create an applet that allows the user to select a font and type in that font in a JTextArea. I have been searching for answers and made little progress. The error java.lang.reflect.InvocationTargetException keeps popping up. If you need more specifics please just comment.
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Font_Chooser extends JApplet {
JLabel jlbPicture;
public Font_Chooser(){
// Create the combo box, and set first item as Default
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] names = ge.getAvailableFontFamilyNames();
final JComboBox comboTypesList = new JComboBox(names);
comboTypesList.setSelectedIndex(0);
comboTypesList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox jcmbType = (JComboBox) e.getSource();
String cmbType = (String) jcmbType.getSelectedItem();
jlbPicture.setIcon(new ImageIcon(""
+ cmbType.trim().toLowerCase() + ".jpg"));
System.out.println(comboTypesList.getSelectedItem());
//Font myFont = new Font((String)comboTypesList.getSelectedItem(), Font.BOLD, 12);
}
});
// Set up the picture
jlbPicture = new JLabel(new ImageIcon(""
+ names[comboTypesList.getSelectedIndex()] + ".jpg"));
jlbPicture.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
jlbPicture.setPreferredSize(new Dimension(177, 122 + 10));
// Layout the demo
setLayout(new BorderLayout());
add(comboTypesList, BorderLayout.NORTH);
add(jlbPicture, BorderLayout.SOUTH);
}
public static void main(String s[]) {
JFrame frame = new JFrame("JComboBox Usage Demo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setContentPane(new Font_Chooser());
frame.pack();
frame.setVisible(true);
}
}
I've create a program with a JButton(image) and a normal image, now if you click the normal button a image will show, now i have program that the JButton(image) will hide if you click the normal button but i dont work and i get a fault code
package View;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import Controller.HideController;
import Controller.HomeController;
import Controller.SelectieController;
public class Selectie extends JFrame{
private static String Vermeer = "Vermeer";
private JLabel label, label1, label2;
private JButton keeper, kruis;
private JPanel panel;
private Container window = getContentPane();
public Selectie()
{
initGUI();
}
public void initGUI()
{
setLayout(null);
setTitle("Jari");
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
label.setBounds(0, 0, 266, 800);
label.setBackground(Color.RED);
label.setOpaque(true);
window.add(label);
label1 = new JLabel();
label1.setBounds(266, 0, 266, 800);
label1.setBackground(Color.BLACK);
label1.setOpaque(true);
window.add(label1);
label2 = new JLabel();
label2.setBounds(532, 0, 266, 800);
label2.setBackground(Color.RED);
label2.setOpaque(true);
window.add(label2);
JLabel foto = new JLabel();
label1.add(foto);
kruis = new JButton(new ImageIcon("../Ajax/src/img/logotje.gif"));
kruis.setBorderPainted(false);
kruis.setBounds(40, 150, 188, 188);
label1.add(kruis);
keeper = new JButton("1. "+""+" Kenneth Vermeer");
Cursor cur = keeper.getCursor();
keeper.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
keeper.setBounds(20, 50, 186, 12);
keeper.setFocusable(false);
keeper.setBorderPainted(false);
keeper.setContentAreaFilled(false);
keeper.setFont(new Font("Arial",Font.PLAIN,17));
keeper.setForeground(Color.WHITE);
keeper.setActionCommand(Vermeer);
label.add(keeper);
SelectieController s1 = new SelectieController(keeper);
keeper.addActionListener(s1);
}
HideController h1 = new HideController(keeper, kruis);
{
keeper.addActionListener(h1);
}
}
The action listener class:
package Controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
public class HideController implements ActionListener {
private JButton keeper, logo;
private static String Vermeer = "Vermeer";
public HideController(JButton vermeer, JButton kruis)
{
keeper = vermeer;
logo = kruis;
//Kenneth Vermeer
try
{
keeper.setVisible(true);
}
catch(Exception e)
{
e.printStackTrace();
}
logo.setVisible(false);
}
public void actionPerformed(ActionEvent event)
{
String actionCommand = event.getActionCommand();
// Kenneth Vermeer
if (Vermeer.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
logo.setVisible(false);
}
});
}
}}
I hope someone could help me, thanks
If you want the button gone you can use window.remove(keeper). If you want no image but still want the button to be there, you can try logo = null, which will set the icon on logo to nothing, leaving you with a white box. If you are coding on Windows, you can add a background color with keeper.setBackgroundColor(Color.Blue) or whatever color your background is, however the Mac OS's look and feel will not allow this for some reason. (you can change the look and feel with, but that is fairly complicated) If you have a more complex background i would suggest taking a sample from the right point with a screenshot (with the button commented out in the code) and setting logo to that image.