Help with JTextField
Hi all,
If I have the text content is longer than the JTextField, by default, it show me the last part of the text content on the JTextField. How can I make it to show the left (first) part of the content. Thanks for you help.
I forgot the code:
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.SpringLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
public class Untitled1 extends JFrame
JMenu mFile;
public JLabel stateid, taxpayerName,_title;
public JTextField stateidText, taxpayerNameText;
private SpringLayout layout;
private Container contentPane;
public Untitled1()
contentPane = this.getContentPane();
layout = new SpringLayout();
contentPane.setLayout(layout);
JMenuBar menubar = createMenuBar();
setJMenuBar(menubar);
setLocation(200, 100);
this.setResizable(false);
setSize(300, 250);
constructGUI();
this.setTaxpayerName("This is long name and you only see the last part");
public void constructGUI()
String title = "TAXPAYER INFORMATION";
_title = new JLabel(title);
_title.setLocation(255, 0);
_title.setSize(200, 15);
contentPane.add(_title);
layout.putConstraint(SpringLayout.WEST, _title, 70,
SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, _title, 15,
SpringLayout.NORTH, contentPane);
_stateid = new JLabel("State ID * :");
contentPane.add(_stateid);
layout.putConstraint(SpringLayout.WEST, _stateid, 15,
SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, _stateid, 15,
SpringLayout.SOUTH, _title);
_stateidText = new JTextField(13);
contentPane.add(_stateidText);
layout.putConstraint(SpringLayout.WEST, _stateidText, 50,
SpringLayout.EAST, _stateid);
layout.putConstraint(SpringLayout.NORTH, _stateidText, 15,
SpringLayout.SOUTH, _title);
_taxpayerName = new JLabel("Taxpayer Name:");
contentPane.add(_taxpayerName);
layout.putConstraint(SpringLayout.WEST, _taxpayerName, 15,
SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, _taxpayerName, 15,
SpringLayout.SOUTH, _stateid);
_taxpayerNameText = new JTextField(13);
contentPane.add(_taxpayerNameText);
layout.putConstraint(SpringLayout.WEST, _taxpayerNameText, 15,
SpringLayout.EAST, _taxpayerName);
layout.putConstraint(SpringLayout.NORTH, _taxpayerNameText, 15,
SpringLayout.SOUTH, _stateid);
public JMenuBar createMenuBar()
final JMenuBar menuBar = new JMenuBar();
menuBar.add(createFileMenu()); //add File to menu bar
return menuBar;
public JMenu createFileMenu()
mFile = new JMenu("File");
mFile.setMnemonic('f');
mFile.add(createTaxpayer()); //add exit to file
return mFile;
public JMenuItem createTaxpayer()
JMenuItem taxpayer = new JMenuItem("Taxpayer");
taxpayer.addActionListener(taxpayerActionListener);
return taxpayer;
ActionListener taxpayerActionListener = new ActionListener()
public void actionPerformed(ActionEvent e)
Untitled1 test = new Untitled1();
test.setVisible(true);
public void setStateid(String stateid)
this._stateidText.setText(stateid);
public void setTaxpayerName(String taxpayerName)
this._taxpayerNameText.setText(taxpayerName);
public String getTaxpayerName()
return this._taxpayerNameText.getText();
public String getStateid()
return this._stateidText.getText();
public static void main(String[] args) {
Untitled1 untitled1 = new Untitled1();
untitled1.setVisible(true);
}
Similar Messages
-
Need help with JTextArea and Scrolling
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import javax.swing.*;
public class MORT_RETRY extends JFrame implements ActionListener
private JPanel keypad;
private JPanel buttons;
private JTextField lcdLoanAmt;
private JTextField lcdInterestRate;
private JTextField lcdTerm;
private JTextField lcdMonthlyPmt;
private JTextArea displayArea;
private JButton CalculateBtn;
private JButton ClrBtn;
private JButton CloseBtn;
private JButton Amortize;
private JScrollPane scroll;
private DecimalFormat calcPattern = new DecimalFormat("$###,###.00");
private String[] rateTerm = {"", "7years @ 5.35%", "15years @ 5.5%", "30years @ 5.75%"};
private JComboBox rateTermList;
double interest[] = {5.35, 5.5, 5.75};
int term[] = {7, 15, 30};
double balance, interestAmt, monthlyInterest, monthlyPayment, monPmtInt, monPmtPrin;
int termInMonths, month, termLoop, monthLoop;
public MORT_RETRY()
Container pane = getContentPane();
lcdLoanAmt = new JTextField();
lcdMonthlyPmt = new JTextField();
displayArea = new JTextArea();//DEFINE COMBOBOX AND SCROLL
rateTermList = new JComboBox(rateTerm);
scroll = new JScrollPane(displayArea);
scroll.setSize(600,170);
scroll.setLocation(150,270);//DEFINE BUTTONS
CalculateBtn = new JButton("Calculate");
ClrBtn = new JButton("Clear Fields");
CloseBtn = new JButton("Close");
Amortize = new JButton("Amortize");//DEFINE PANEL(S)
keypad = new JPanel();
buttons = new JPanel();//DEFINE KEYPAD PANEL LAYOUT
keypad.setLayout(new GridLayout( 4, 2, 5, 5));//SET CONTROLS ON KEYPAD PANEL
keypad.add(new JLabel("Loan Amount$ : "));
keypad.add(lcdLoanAmt);
keypad.add(new JLabel("Term of loan and Interest Rate: "));
keypad.add(rateTermList);
keypad.add(new JLabel("Monthly Payment : "));
keypad.add(lcdMonthlyPmt);
lcdMonthlyPmt.setEditable(false);
keypad.add(new JLabel("Amortize Table:"));
keypad.add(displayArea);
displayArea.setEditable(false);//DEFINE BUTTONS PANEL LAYOUT
buttons.setLayout(new GridLayout( 1, 3, 5, 5));//SET CONTROLS ON BUTTONS PANEL
buttons.add(CalculateBtn);
buttons.add(Amortize);
buttons.add(ClrBtn);
buttons.add(CloseBtn);//ADD ACTION LISTENER
CalculateBtn.addActionListener(this);
ClrBtn.addActionListener(this);
CloseBtn.addActionListener(this);
Amortize.addActionListener(this);
rateTermList.addActionListener(this);//ADD PANELS
pane.add(keypad, BorderLayout.NORTH);
pane.add(buttons, BorderLayout.SOUTH);
pane.add(scroll, BorderLayout.CENTER);
addWindowListener( new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
public void actionPerformed(ActionEvent e)
String arg = lcdLoanAmt.getText();
int combined = Integer.parseInt(arg);
if (e.getSource() == CalculateBtn)
try
JOptionPane.showMessageDialog(null, "Got try here", "Error", JOptionPane.ERROR_MESSAGE);
catch(NumberFormatException ev)
JOptionPane.showMessageDialog(null, "Got here", "Error", JOptionPane.ERROR_MESSAGE);
if ((e.getSource() == CalculateBtn) && (arg != null))
try{
if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 1))
monthlyInterest = interest[0] / (12 * 100);
termInMonths = term[0] * 12;
monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest, -termInMonths))));
lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 2))
monthlyInterest = interest[1] / (12 * 100);
termInMonths = term[1] * 12;
monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest, -termInMonths))));
lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 3))
monthlyInterest = interest[2] / (12 * 100);
termInMonths = term[2] * 12;
monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest, -termInMonths))));
lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
catch(NumberFormatException ev)
JOptionPane.showMessageDialog(null, "Invalid Entry!\nPlease Try Again", "Error", JOptionPane.ERROR_MESSAGE);
} //IF STATEMENTS FOR AMORTIZATION
if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 1))
loopy(7, 5.35);
if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 2))
loopy(15, 5.5);
if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 3))
loopy(30, 5.75);
if (e.getSource() == ClrBtn)
rateTermList.setSelectedIndex(0);
lcdLoanAmt.setText(null);
lcdMonthlyPmt.setText(null);
displayArea.setText(null);
if (e.getSource() == CloseBtn)
System.exit(0);
private void loopy(int lTerm,double lInterest)
double total, monthly, monthlyrate, monthint, monthprin, balance, lastint, paid;
int amount, months, termloop, monthloop;
String lcd2 = lcdLoanAmt.getText();
amount = Integer.parseInt(lcd2);
termloop = 1;
paid = 0.00;
monthlyrate = lInterest / (12 * 100);
months = lTerm * 12;
monthly = amount *(monthlyrate/(1-Math.pow(1+monthlyrate,-months)));
total = months * monthly;
balance = amount;
while (termloop <= lTerm)
displayArea.setCaretPosition(0);
displayArea.append("\n");
displayArea.append("Year " + termloop + " of " + lTerm + ": payments\n");
displayArea.append("\n");
displayArea.append("Month\tMonthly\tPrinciple\tInterest\tBalance\n");
monthloop = 1;
while (monthloop <= 12)
monthint = balance * monthlyrate;
monthprin = monthly - monthint;
balance -= monthprin;
paid += monthly;
displayArea.setCaretPosition(0);
displayArea.append(monthloop + "\t" + calcPattern.format(monthly) + "\t" + calcPattern.format(monthprin) + "\t");
displayArea.append(calcPattern.format(monthint) + "\t" + calcPattern.format(balance) + "\n");
monthloop ++;
termloop ++;
public static void main(String args[])
MORT_RETRY f = new MORT_RETRY();
f.setTitle("MORTGAGE PAYMENT CALCULATOR");
f.setBounds(600, 600, 500, 500);
f.setLocationRelativeTo(null);
f.setVisible(true);
}need help with displaying the textarea correctly and the scroll bar please.
Message was edited by:
new2this2020What's the problem you're having ???
PS. -
Need help with my graphic calculator!!!
Hello everybody!! I need help with my little program I made.... The problem is that I am unable to use to calculate but it is possible to compile the code!! What should I do?? Thanks in advance.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Aritmetik extends JFrame implements ActionListener{
private JLabel l1 = new JLabel("Tal1: ", JLabel.LEFT);
private JLabel l2 = new JLabel("Tal2: ", JLabel.LEFT);
private JLabel l3 = new JLabel("Resultat",JLabel.LEFT);
private JLabel l4 = new JLabel(" ", JLabel.RIGHT);
private JTextField t1 = new JTextField(" ",10);
private JTextField t2 = new JTextField(" ",10);
private JButton b1 = new JButton("+");
private JButton b2 = new JButton("-");
private JButton b3 = new JButton("*");
private JButton b4 = new JButton("/");
public Aritmetik(){
Container v = getContentPane();
v.setLayout(new GridLayout(5,2));
v.add(l1);
v.add(t1);
v.add(l2);
v.add(t2);
v.add(b1);
v.add(b2);
v.add(b3);
v.add(b4);
v.add(l3);
v.add(l4);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
pack();
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
public void actionPerformed(ActionEvent e){
int tal1 = Integer.parseInt(t1.getText());
int tal2 = Integer.parseInt(t2.getText());
if(e.getSource() == b1){
if(t1.getText().equals("") || t2.getText().equals(""))
JOptionPane.showMessageDialog(null, "Mata in tal!");
else{
l3.setText("Resultat ");
l4.setText(" " + (tal1+tal2));
else if(e.getSource() == b2){
int sub = tal1-tal2;
l4.setText(" " + (sub));
else if(e.getSource() == b3){
int multi = tal1*tal2;
l4.setText(" " + (multi));
else if(e.getSource() == b4){
int div = tal1/tal2;
l4.setText(" " + (div));
public static void main(String[] arg){
Aritmetik A =new Aritmetik();Here is your problem:
public void actionPerformed(ActionEvent e){
int tal1 = Integer.parseInt(t1.getText().trim()); // add the trim()
int tal2 = Integer.parseInt(t2.getText().trim()); // add the trim()
if(e.getSource() == b1){
if(t1.getText().equals("") || t2.getText().equals(""))
JOptionPane.showMessageDialog(null, "Mata in tal!");
else{
l3.setText("Resultat ");
l4.setText(" " + (tal1+tal2));
}... Better ...
public void actionPerformed(ActionEvent e) throws NumberFormatException {
String tala = t1.getText().trim();
String talb = t2.getText().trim();
if ( tala == null || "".equals(tala) || talb == null || "".equals(talb) ) {
JOptionPane.showMessageDialog(null, "Mata in tal!");
return();
int tal1 = Integer.parseInt(tala);
int tal2 = Integer.parseInt(talb);
if(e.getSource() == b1){
l3.setText("Resultat ");
l4.setText(" " + (tal1+tal2));
else if(e.getSource() == b2){
int sub = tal1-tal2;
l4.setText(" " + (sub));
else if(e.getSource() == b3){
int multi = tal1*tal2;
l4.setText(" " + (multi));
else if(e.getSource() == b4){
int div = tal1/tal2;
l4.setText(" " + (div));
}Message was edited by:
abillconsl -
Need help with my addressbook program
hi,
i need help with my program here. this one should works as:
- saves user input into a txt file
- displays name of the saved person on the jlist whenever i run the program
- displays info about the person when clicked via textboxes given by reading the txt file where the user inputs are
- should scroll when the list exceeds the listbox
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.JList;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.event.*;
import java.io.FilterInputStream;
public class AddressList extends JPanel implements ActionListener
JTextField txt1 = new JTextField();
JTextField txt2 = new JTextField();
JTextField txt3 = new JTextField();
DefaultListModel mdl = new DefaultListModel();
JList list = new JList();
JScrollPane listScroller = new JScrollPane(list);
ListSelectionModel listSelectionModel;
File fob = new File("Address3.txt");
String name;
char[] chars;
public void ListDisplay()
try
RandomAccessFile rand = new RandomAccessFile(fob,"rw");
BufferedReader br = new BufferedReader(new FileReader("Address3.txt"));
if(fob.exists())
while((name = rand.readLine()) != null)
chars = name.toCharArray();
if(chars[0] == '*')
mdl.addElement(name);
list.setModel(mdl);
if(chars[0] == '#')
continue;
else
System.out.println("No such file..");
catch(IOException a)
System.out.println(a.getMessage());
public AddressList()
this.setLayout(null);
listSelectionModel = list.getSelectionModel();
listSelectionModel.addListSelectionListener(new ListInfo());
list.setBounds(10,40,330,270);
listScroller.setBounds(320,40,20,100);
add(list);
add(listScroller);
JLabel lbl4 = new JLabel("Name: ");
lbl4.setBounds(400,10,80,30);
add(lbl4);
JLabel lbl5 = new JLabel("Cellphone #: ");
lbl5.setBounds(400,50,80,30);
add(lbl5);
JLabel lbl6 = new JLabel("Address: ");
lbl6.setBounds(400,90,80,30);
add(lbl6);
JLabel lbl7 = new JLabel("List ");
lbl7.setBounds(10,10,100,30);
add(lbl7);
txt1.setBounds(480,10,200,30);
add(txt1);
txt2.setBounds(480,50,200,30);
add(txt2);
txt3.setBounds(480,90,200,30);
add(txt3);
JButton btn1 = new JButton("Add");
btn1.setBounds(480,130,100,30);
btn1.addActionListener(this);
btn1.setActionCommand("Add");
add(btn1);
JButton btn2 = new JButton("Save");
btn2.setBounds(480,170,100,30);
btn2.addActionListener(this);
btn2.setActionCommand("Save");
add(btn2);
JButton btn3 = new JButton("Cancel");
btn3.setBounds(480,210,100,30);
btn3.addActionListener(this);
btn3.setActionCommand("Cancel");
add(btn3);
JButton btn4 = new JButton("Close");
btn4.setBounds(480,250,100,30);
btn4.addActionListener(this);
btn4.setActionCommand("Close");
add(btn4);
public static void main(String[]args)
JFrame frm = new JFrame("Address List");
AddressList panel = new AddressList();
frm.getContentPane().add(panel,"Center");
frm.setSize(700,350);
frm.setVisible(true);
panel.ListDisplay();
public void actionPerformed(ActionEvent e)
String cmd;
cmd = e.getActionCommand();
if(cmd.equals("Add"))
txt1.setText("");
txt2.setText("");
txt3.setText("");
else if(cmd.equals("Save"))
mdl.addElement(txt1.getText());
list.setModel(mdl);
try
RandomAccessFile rand = new RandomAccessFile(fob,"rw");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
LineNumberReader line = new LineNumberReader(br);
if(fob.exists())
rand.seek(fob.length());
rand.writeBytes("* " + txt1.getText());
rand.writeBytes("\r\n" + "# " + txt2.getText());
rand.writeBytes("\r\n" + "# " + txt3.getText() + "\r\n");
else
System.out.println("No such file..");
txt1.setText("");
txt2.setText("");
txt3.setText("");
catch(IOException a)
System.out.println(a.getMessage());
else if(cmd.equals("Cancel"))
txt1.setText("");
txt2.setText("");
txt3.setText("");
else if(cmd.equals("Close"))
System.exit(0);
class ListInfo implements ListSelectionListener
public void valueChanged(ListSelectionEvent e)
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
int minIndex = lsm.getMinSelectionIndex();
int maxIndex = lsm.getMaxSelectionIndex();
try //*this one should display the info of the person whenever i click the person's name at the list box via textbox.. but i cant seem to get it right since it always display the info of the first person inputed.. i tried to get the program to display them whenever it reads lines with * on them....
File fob = new File("Address3.txt");
RandomAccessFile rand = new RandomAccessFile(fob,"rw");
BufferedReader br = new BufferedReader(new FileReader("Address3.txt"));
LineNumberReader line = new LineNumberReader(br);
if(fob.exists())
for(int i = minIndex; i<=maxIndex; i++)
if(lsm.isSelectedIndex(i))
while((name = rand.readLine()) != null)
chars = name.toCharArray();
if(chars[0] == '#')
continue;
if(chars[0] == '*')
txt1.setText(rand.readLine());
txt2.setText(rand.readLine());
txt3.setText(rand.readLine());
else
System.out.println("No such file..");
catch(IOException a)
System.out.println(a.getMessage());
}the only problem now is about how it should display the right info about the person whenever i click its name on the list.. something about file reading or something, i just cant figure it out.
and also about how to make it scroll once it exceeds the list.. i cant make it work, maybe something about wrong declaration..
thanks in advance..
Edited by: syder on Mar 14, 2008 2:26 AMLike said before, do one thing at a time. At startup, something like:
//put all the content in a list
ArrayList<String> lines = new ArrayList<String>();
while(String line=rand.readLine()!=null) {
lines.add(line);
}If you follow the good advice to create a class to encapsulate the entries, you could populate a list of such entries like this:
static final int ENTRY_SIZE = 3;//you have 3 fields now, better to have a constant if that changes
ArrayList<Entry> entries = new ArrayList<Entry>();
for(int i=0; i<lines.size(); i+=ENTRY_SIZE) {
Entry entry = new Entry(lines.get(i), lines.get(i+1), lines.get(i+2);
entries.add(newEntry);
}You could also do both of the above in one run, but I think you will understand better what's happening if you do one thing at a time.
If you don't want to put the entries in an encapsulating class, you can still access this without looping:
int listStartIdx = <desired_entry_index>*ENTRY_SIZE;
String att1 = lines.get(listStartIdx).substring(1);
String att2 = lines.get(listStartIdx+1).substring(1);
String att3 = lines.get(listStartIdx+2).substring(1); -
Need Help with a getText method
Gday all,
I need help with a getText method, i need to extract text from a JTextField. Although this text then needs to converted to a double so that i can multiply a number that i have already specified. As you may of guessed that the text i need to extract already will be in a double format.e.g 0.1 or 0.0000004 etc
Thanks for your help
ps heres what i have already done its not very good though
ToBeConverted.getText();
( need help here)
double amount = (and here)
total = (amount*.621371192);
Converted.setText("= " + total);Double.parseDouble( textField.getText() );
-
Hi, I'm not sure if I'm allowed to post questions on this forum but I can't find anywhere to talk to helpful people about programming.
I'm making a dnd interface for JComponents. So far I've made a simple program that has a Component that can be lifted from a container and braught to the glass pane then later moved to anywhere on the screen and dropped into the container below it. Here's where my problems come:
1) Rite now my 'Movable Component' is a JPanel which is just colored in. I want to either take a Graphic2d from a JComponent/Component and draw it on the JPanel or change the JPanel to the component I want to paint and disable the component.
The problem with getting the Graphics2d is that if the component isn't on the screen it doesn't make a graphic object. I tried messing with the ui delicate and overriding parental methods for paintComponent, repaint, and that repaintChildren(forget name) but I haven't had luck getting a good graphics object. I was thinking of, at the beginning of running the program, putting 1 of each component onto the screen for a second then removing it but I'd rather not. I'd also like to change the graphics dynamicly if someone stretches the component there dropping and what not.
The problem with disabling is that it changes some of the visual features of Components. I want to be able to update the Component myself to change how it looks and I don't want disabling to gray out components.
I mainly just dont want the components to do any of there normal fuctions. This is for a page builder, by the way.
Another problem I'm having is that mouseMotionListener is allowing me to select 2 components that are on top of one another when there edges are near each other. I don't know if theres a fix to this other than changing the Java Class.
My next problem is a drop layout manager, but I'm doing pretty good with that rite now. It'll problem just move components out of the way of the falling component.
One last thing I need help with is that I don't want the object that's being carried to go across the menu bar and certain areas. When I'm having the object being carried I have it braught up to the glass pane which allows it to move anywhere. Does anyone have any idea how I could prevent the component from being over the menu bars and other objects? I might have to make 1 panel is the movable area that can then be broken down into the 'component bank', 'building page' and whatever else I'm gonna need.
This is all just test code to get together for when I make the real program but I need to make sure it'll be possible without a lot of hacking of code.
Sorry for the length. Thanks for any help you can give.The trick to making viewable components that have no behaviour, is to render them onto an image of some sort (eg a BufferedImage). You can then display the Image on a JLabel that can be dragged around the desktop.
Here is a piece of code that does the component rendering for you. This particular example uses a fixed component size, but you can modify that as you choose of course...public class JComponentImage
private static GraphicsConfiguration gConfig;
private static Dimension compSize = new Dimension(80, 22);
private static Image image = null;
public static Image getImage(Class objectClass)
if (gConfig == null)
GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gDevice = gEnv.getDefaultScreenDevice();
gConfig = gDevice.getDefaultConfiguration();
image = gConfig.createCompatibleImage(compSize.width, compSize.height);
JComponent jc = (JComponent) ObjectFactory.instantiate(objectClass);
jc.setSize(compSize);
Graphics g = image.getGraphics();
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 0, compSize.width, compSize.height);
g.setColor(Color.BLACK);
jc.paint(g);
return image;
}And here is the class that makes the dragable JLabel using the class above...public class Dragable extends JLabel
private static DragSource dragSource = DragSource.getDefaultDragSource();
private static DragGestureListener dgl = new DragMoveGestureListener();
private static TransferHandler th = new ObjectTransferHandler();
private Class compClass;
private Image image;
Dragable(Class compClass)
this.compClass = compClass;
image = JComponentImage.getImage(compClass);
setIcon(new ImageIcon(image));
setTransferHandler(th);
dragSource.createDefaultDragGestureRecognizer(this,
DnDConstants.ACTION_COPY,
dgl);
public Class getCompClass()
return compClass;
}Oh and here is ObjectFactory which simply instantiates Objects of a given class and sets their text to their classname (very crudely)...public class ObjectFactory
public static Object instantiate(Class objectClass)
Object o = null;
try
o = objectClass.newInstance();
catch (Exception e)
System.out.println("ObjectFactory#instantiate: " + e);
String name = objectClass.getName();
int lastDot = name.lastIndexOf('.');
name = name.substring(lastDot + 1);
if (o instanceof JLabel)
((JLabel)o).setText(name);
if (o instanceof JButton)
((JButton)o).setText(name);
if (o instanceof JTextComponent)
((JTextComponent)o).setText(name);
return o;
}Two more classes required by this codepublic class ObjectTransferHandler extends TransferHandler {
private static DataFlavor df;
* Constructor for ObjectTransferHandler.
public ObjectTransferHandler() {
super();
try {
df = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
} catch (ClassNotFoundException e) {
Debug.trace(e.toString());
public Transferable createTransferable(JComponent jC) {
Transferable t = null;
try {
t = new ObjectTransferable(((Dragable) jC).getCompClass());
} catch (Exception e) {
Debug.trace(e.toString());
return t;
public int getSourceActions(JComponent c) {
return DnDConstants.ACTION_MOVE;
public boolean canImport(JComponent comp, DataFlavor[] flavors) {
if (!(comp instanceof Dragable) && flavors[0].equals(df))
return true;
return false;
public boolean importData(JComponent comp, Transferable t) {
JComponent c = null;
try {
c = (JComponent) t.getTransferData(df);
} catch (Exception e) {
Debug.trace(e.toString());
comp.add(c);
comp.validate();
return true;
public class ObjectTransferable implements Transferable {
private static DataFlavor df = null;
private Class objectClass;
ObjectTransferable(Class objectClass) {
try {
df = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
} catch (ClassNotFoundException e) {
System.out.println("ObjectTransferable: " + e);
this.objectClass = objectClass;
* @see java.awt.datatransfer.Transferable#getTransferDataFlavors()
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { df };
* @see java.awt.datatransfer.Transferable#isDataFlavorSupported(DataFlavor)
public boolean isDataFlavorSupported(DataFlavor testDF) {
return testDF.equals(df);
* @see java.awt.datatransfer.Transferable#getTransferData(DataFlavor)
public Object getTransferData(DataFlavor arg0)
throws UnsupportedFlavorException, IOException {
return ObjectFactory.instantiate(objectClass);
}And of course the test class:public class DragAndDropTest extends JFrame
JPanel leftPanel = new JPanel();
JPanel rightPanel = new JPanel();
Container contentPane = getContentPane();
Dragable dragableJLabel;
Dragable dragableJButton;
Dragable dragableJTextField;
Dragable dragableJTextArea;
* Constructor DragAndDropTest.
* @param title
public DragAndDropTest(String title)
super(title);
dragableJLabel = new Dragable(JLabel.class);
dragableJButton = new Dragable(JButton.class);
dragableJTextField = new Dragable(JTextField.class);
dragableJTextArea = new Dragable(JTextArea.class);
leftPanel.setBorder(new EtchedBorder());
BoxLayout boxLay = new BoxLayout(leftPanel, BoxLayout.Y_AXIS);
leftPanel.setLayout(boxLay);
leftPanel.add(dragableJLabel);
leftPanel.add(dragableJButton);
leftPanel.add(dragableJTextField);
leftPanel.add(dragableJTextArea);
rightPanel.setPreferredSize(new Dimension(500,500));
rightPanel.setBorder(new EtchedBorder());
rightPanel.setTransferHandler(new ObjectTransferHandler());
contentPane.setLayout(new BorderLayout());
contentPane.add(leftPanel, "West");
contentPane.add(rightPanel, "Center");
public static void main(String[] args)
JFrame frame = new DragAndDropTest("Drag and Drop Test");
frame.pack();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}I wrote this code some time ago, so it won't be perfect but hopefully will give you some good ideas.
Regards,
Tim -
Need help with basic program.....!
I've to write a program that generates a random number, which the user has to try and guess, after each guess they're told whether it's too high or too low etc., I've gotten this far, however, the user has only 10 guesses.... In my program I've used a while loop and the user gets an infinite number of guesses, I know I'm supposed to use a for loop, but can't seem to get it to work properly. Also, when the user guesses the number, the program then has to print out how many guesses it took, and I have no idea how to get it to do this AT ALL!!! I'd really appreciate some help with this, thanks v. much!!!!
I've to write a program that generates a random
number, which the user has to try and guess, after
each guess they're told whether it's too high or too
low etc., I've gotten this far, however, the user has
only 10 guesses.... In my program I've used a while
loop and the user gets an infinite number of guesses,
I know I'm supposed to use a for loop, but can't seem
to get it to work properly. Also, when the user
guesses the number, the program then has to print out
how many guesses it took, and I have no idea how to
get it to do this AT ALL!!! I'd really appreciate some
help with this, thanks v. much!!!!Hey not every book covers every aspect of Java (if you haven't got a book and don't want to buy 1 i recommend an online tutorial) If u want the user to have an infinate number of guesses, use an infinate while loop. Put this in a file called app.java:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class app extends Applet implements ActionListener
JLabel lbl=new JLabel("Guess a number between 0 and 10:");
JTextField txtfield=new JTextField(20);
JButton button=new JButton("Guess...");
JLabel lbl2=new JLabel();
int randomnumber=Math.round((float)Math.random()*10);
public void init()
add(lbl);
add(txtfield);
add(button);
button.addActionListener(this);
public void actionPerformed (ActionEvent e)
String s=new String("");
s+=randomnumber;
if (e.getSource().equals(button) && txtfield.getText().equals(s))
setBackground(Color.white);
setForeground(Color.black);
lbl2.setText("Got it!");
add(lbl2);
validate();
else
setBackground(Color.white);
setForeground(Color.black);
if (Integer.parseInt(txtfield.getText())>randomnumber)
lbl2.setText("Too High!");
else
lbl2.setText("Too Low!");
add(lbl2);
validate();
Then create a HTML document in the classes folder:
<HTML>
<HEAD>
<TITLE>APPLET</TITLE>
</HEAD>
<BODY>
<HR>
<CENTER>
<APPLET
CODE=app.class
WIDTH=400
HEIGHT=200 >
</APPLET>
</CENTER>
<HR>
</BODY>
</HTML>
It will do what you wish. If you want to have more then 10 numbers to guess, for example 100, do this:
int randomnumber=Math.round((float)Math.random()*100);
Does that answer your question? -
Need help with a simple program (should be simple anyway)
I'm (starting to begin) writing a nice simple program that should be easy however I'm stuck on how to make the "New" button in the file menu clear all the fields. Any help? I'll attach the code below.
====================================================
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Message extends JFrame implements ActionListener {
public void actionPerformed(ActionEvent evt) {
text1.setText(" ");
text2.setText("RE: ");
text3.setText(" ");
public Message() {
super("Write a Message - by Kieran Hannigan");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(370,270);
FlowLayout flo = new FlowLayout(FlowLayout.RIGHT);
setLayout(flo);
//Make the bar
JMenuBar bar = new JMenuBar();
//Make "File" on Menu
JMenu File = new JMenu("File");
JMenuItem f1 = new JMenuItem("New");f1.addActionListener(this);
JMenuItem f2 = new JMenuItem("Open");
JMenuItem f3 = new JMenuItem("Save");
JMenuItem f4 = new JMenuItem("Save As");
JMenuItem f5 = new JMenuItem("Exit");
File.add(f1);
File.add(f2);
File.add(f3);
File.add(f4);
File.add(f5);
bar.add(File);
//Make "Edit" on menu
JMenu Edit = new JMenu("Edit");
JMenuItem e1 = new JMenuItem("Cut");
JMenuItem e2 = new JMenuItem("Paste");
JMenuItem e3 = new JMenuItem("Copy");
JMenuItem e4 = new JMenuItem("Repeat");
JMenuItem e5 = new JMenuItem("Undo");
Edit.add(e5);
Edit.add(e4);
Edit.add(e1);
Edit.add(e3);
Edit.add(e2);
bar.add(Edit);
//Make "View" on menu
JMenu View = new JMenu("View");
JMenuItem v1 = new JMenuItem("Bold");
JMenuItem v2 = new JMenuItem("Italic");
JMenuItem v3 = new JMenuItem("Normal");
JMenuItem v4 = new JMenuItem("Bold-Italic");
View.add(v1);
View.add(v2);
View.add(v3);
View.addSeparator();
View.add(v4);
bar.add(View);
//Make "Help" on menu
JMenu Help = new JMenu("Help");
JMenuItem h1 = new JMenuItem("Help Online");
JMenuItem h2 = new JMenuItem("E-mail Programmer");
Help.add(h1);
Help.add(h2);
bar.add(Help);
setJMenuBar(bar);
//Make Contents of window.
//Make "Subject" text field
JPanel row2 = new JPanel();
JLabel sublabel = new JLabel("Subject:");
row2.add(sublabel);
JTextField text2 = new JTextField("RE:",24);
row2.add(text2);
//Make "To" text field
JPanel row1 = new JPanel();
JLabel tolabel = new JLabel("To:");
row1.add(tolabel);
JTextField text1 = new JTextField(24);
row1.add(text1);
//Make "Message" text area
JPanel row3 = new JPanel();
JLabel Meslabel = new JLabel("Message:");
row3.add(Meslabel);
JTextArea text3 = new JTextArea(6,22);
messagearea.setLineWrap(true);
messagearea.setWrapStyleWord(true);
JScrollPane scroll = new JScrollPane(text3,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//SpaceLine
JPanel spaceline = new JPanel();
JLabel spacer = new JLabel(" ");
spaceline.add(spacer);
row3.add(scroll);
add(row1);
add(row2);
add(spaceline);
add(spaceline);
add(row3);
setVisible(true);
public static void main(String[] arguments) {
Message Message = new Message();
}persiandude wrote:
Topic: Need help with if, else, and which statements and loops.
How would I display 60 < temp. <= 85 in java
System.out.println("60 < temp. <= 85 in java");
another question is how do I ask a question like want to try again (y/n) after a output and asking that everytime I type in yes after a output and terminate when saying No.Sun's [basic Java tutorial|http://java.sun.com/docs/books/tutorial/]
Sun's [New To Java Center|http://java.sun.com/learning/new2java/index.html].Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
[http://javaalmanac.com|http://javaalmanac.com]. A couple dozen code examples that supplement [The Java Developers Almanac|http://www.amazon.com/exec/obidos/tg/detail/-/0201752808?v=glance].
jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
Bruce Eckel's [Thinking in Java|http://mindview.net/Books/DownloadSites] (Available online.)
Joshua Bloch's [Effective Java|http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683/ref=pd_bbs_1?ie=UTF8&s=books&qid=1214349768&sr=8-1]
Bert Bates and Kathy Sierra's [Head First Java|http://www.amazon.com/exec/obidos/tg/detail/-/0596004656?v=glance].
James Gosling's [The Java Programming Language|http://www.bookpool.com/sm/0321349806]. -
Need Help for - JTextField outputs
Hello everyone im back =P
Just finished a code...and now i'd like to print the output using the JTextField , but it seems im having some problems :) ....don't know how to print the String.
for JOptionPane its easy , we use JOptionPane.showMessag....etc
we have also System.out...but i want to print this string with the JTextField, does anyone can help with that? thnks
double m = complexo.module(r,i);
double a = complexo.angle(r,i);
String text = "Module: "+ Double.toString(m) + "\nAngle: " + Double.toString(a);
// I want to print that String -> text
JTextField output = new JTextField(100);
JPanel p = new JPanel();
p.add(output);
output.setText(text);
output.setEditable(false);
/** Is that ok ? do i have to use the JPanel or the JFrame ? , well i just
* want to print that string (text) using the JTextField */ thnksIn the future, Swing related questions should be posted in the Swing forum.
and now i'd like to print the output using the JTextFieldLets get some terminoligy correct first. "Print" means you want to send the text to a printer so it can be printed on paper. I don't think thats what you want to do.
You want to display the text on your monitor using a GUI. In that case you need to create a GUI container that contains a JTextField that will display the text.
Start by read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html]How to Use Top Level Containers. The tutorial also has a section on using text components which shows you how to use a text field. -
Help with dropdown menu in JCombo box,Pleaseeeeeee
Hi,
I posted earlier but I`II try again. Someone must know how to do this. I have a JComboBox and I want the drop down menu to be a bit wider then the comboBox.
I tried using this method
public void setPreferredSize()
Dimension d = jcbo.getPreferredSize(d);
jcbo.setPreferredSize(new Dimension(20, d.height));
jcbo.setPopupWidth(d.width);
but I recieved a couldn`t resolve symbol error for the last line.
I imported these into the program]
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Is there something else I should of imported as well to make this work, or is it another problem all together.Any help would be greatly appreciated.Hi , What I want to do is have the dropmenu a bit wider then the comboBox. Here is my code.Please excuse any odd ball mistakes, At this point I have been trying anything.This is an exercise that I have to do fo a java assignment, Hence the weird GUI. In the example pic they gave me.It shows the dropmenu a bit wider than the comboBox, I am sure they through this in to screw with my brain, I have put comment tags Around the stuff I tried to use. Any help with this would be greatly appreciated.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//import javax.swing.plaf.basic.*;
public class Exercise9_3 extends JFrame implements ActionListener
private JTextField nameField;
private JTextArea nameArea;
private JButton storeButton;
private JComboBox jcbo;
private JPopupMenu popup;
protected int popupWidth;
String newline = "\n";
public Exercise9_3()
createComponets();
addComponets();
setTitle("Exercise9_3");
private void createComponets ()
nameField = new JTextField(19);
nameArea = new JTextArea(10, 15);
storeButton = new JButton("Store");
storeButton.addActionListener(this);
jcbo = new JComboBox();
jcbo.addActionListener(this);
/*8public void setPreferredSize()
Dimension d = jcbo.getPreferredSize(d);
//jcbo.setPreferredSize(new Dimension(20, d.height));
//jcbo.setPopupWidth(d.width);
private void addComponets()
JPanel p1 = new JPanel();
p1.setLayout (new FlowLayout());
p1.add(nameField);
p1.add(nameArea);
p1.add(jcbo);
JPanel p2 = new JPanel();
p2.setLayout (new FlowLayout());
p2.add (storeButton);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(p1, BorderLayout.CENTER);
getContentPane().add(p2, BorderLayout.SOUTH);
public void actionPerformed(ActionEvent e)
if(e.getSource() == storeButton)
String s = nameField.getText();
jcbo.addItem(s);
jcbo.setSelectedItem(s);
String textArea = s ;
String text = nameField.getText();
nameArea.append(text + newline);
nameField.selectAll();
nameField.setText("");
nameField.requestFocus();
if (e.getSource() == jcbo)
/**retrieve the input as a string*/
String selectedName = (String)jcbo.getSelectedItem();
/**set the name that was selected from the ComboBox and add it to textfield*/
nameField.setText(selectedName);
public static void main(String [] args)
Exercise9_3 frame = new Exercise9_3();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
// Get dimension of the frame
Dimension frameSize = frame.getSize();
int x = (screenWidth - frameSize.width)/2;
int y = (screenHeight- frameSize.height)/2;
frame.setLocation(x,y); -
Need Help with Listener on JInternalFrame
Below is the code as it is currently.
public class addCustomer extends JInternalFrame implements ActionListener{
//Variable declarations here
private JPanel panel = new JPanel();
private JLabel label1,label2,label3,label4,label5,label6,label7,label8,label9,icon1;
private JTextField CustNum,CFName,CSName,Address1,Address2,City,PostCode,Tel,Cell;
private JButton Cancel, Add;
private ImageIcon pic,FrmPic;
addCustomer() {
super ("Add New Customer",true,true,true,true);
setSize(350,370);
setResizable(false);
On the Frame I have a textfield that I would like to add a listener to. When text is typed into the textfield it should enable a JButton on the frame. My problem is that as soon as I implement KeyListener or EventListener on the above code I get an error of the class is not defined as abstract. If I define it as abstract my main declaration that looks like this gives me an error :
public static void main(String args[]){
new Video().show();
Can anyone help me with a work around.
AlexanderStill have an error in the code. I don't know what I am doing wrong. this is the code so far.
//This class will create the the Panel for Adding new Customers
package VideoShop;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.io.*;
import javax.swing.event.*;
public class addCustomer extends JInternalFrame implements ActionListener{
//Variable declarations here
private JPanel panel = new JPanel();
private JLabel label1,label2,label3,label4,label5,label6,label7,label8,label9,icon1;
private JTextField CustNum,CFName,CSName,Address1,Address2,City,PostCode,Tel,Cell;
private JButton Cancel, Add;
private ImageIcon pic,FrmPic;
addCustomer() {
super ("Add New Customer",true,true,true,true);
setSize(350,370);
setResizable(false);
//Sets the layout for the panel
panel.setLayout(null);
//Creates the labels
label1 = new JLabel("Customer Nr");
label2 = new JLabel("First Name");
label3 = new JLabel("Surname");
label4 = new JLabel("Address");
label5 = new JLabel("Address");
label6 = new JLabel("City");
label7 = new JLabel("Postcode");
label8 = new JLabel("Tel Nr");
label9 = new JLabel("Cell Nr");
//Creates the Textfields
CustNum = new JTextField();
CustNum.setEditable(false);
CFName = new JTextField();
CSName = new JTextField();
Address1 = new JTextField();
Address2 = new JTextField();
City = new JTextField();
PostCode = new JTextField();
Tel = new JTextField();
Cell = new JTextField();
//Creates the buttons
Cancel = new JButton("Cancel");
Add = new JButton("Add");
//Sets the alignment of the label controls
label1.setBounds(20, 20, 90, 20);
label2.setBounds(20, 50, 90, 20);
label3.setBounds(20, 80, 90, 20);
label4.setBounds(20, 110, 90, 20);
label5.setBounds(20, 140, 90, 20);
label6.setBounds(20, 170, 90, 20);
label7.setBounds(20, 200, 90, 20);
label8.setBounds(20, 230, 90, 20);
label9.setBounds(20,260,90,20);
//Sets the alignment of the Textfield controls
CustNum.setBounds(100,20,90,20);
CFName.setBounds(100, 50, 90, 20);
CSName.setBounds(100, 80, 90, 20);
Address1.setBounds(100, 110, 130, 20);
Address2.setBounds(100, 140, 130, 20);
City.setBounds(100, 170, 100, 20);
PostCode.setBounds(100, 200, 65, 20);
Tel.setBounds(100,230, 90,20);
Cell.setBounds(100, 260, 90, 20);
//Sets the alignment of the Button controls
Add.setBounds(200, 310, 90, 20);
Cancel.setBounds(85,310,90,20);
//Creates an icon on the panel
pic = new ImageIcon("/VideoShop/NotePad.gif");
icon1 = new JLabel(pic);
icon1.setBounds(280,10,50,50);
//Adds Mnemonics
Cancel.setMnemonic('c');
Add.setMnemonic('a');
//Adds listener to the Cell TextField to help with validation
Cell.getDocument().addDocumentListener(new DocumentListener(){
public void changeUpdate(DocumentEvent e){
public void removeUpdate (DocumentEvent e){
adjust(e);
public void insertUpdate(DocumentEvent e){ //ERROR////////////
adjust(e);
//Adds listeners to the buttons on the panel
Cancel.addActionListener(this);
Add.addActionListener(this);
//Adds the controls to the panel
panel.add(label1);
panel.add(label2);
panel.add(label3);
panel.add(label4);
panel.add(label5);
panel.add(label6);
panel.add(label7);
panel.add(label8);
panel.add(label9);
panel.add(CustNum);
panel.add(CFName);
panel.add(CSName);
panel.add(Address1);
panel.add(Address2);
panel.add(City);
panel.add(PostCode);
panel.add(Tel);
panel.add(Cell);
panel.add(Cancel);
panel.add(Add);
panel.add(icon1);
//Gets the next customer number from the database
//Variables for the database
String dbuser = "";
String dbpasswd = "";
String DriverPrefix = "jdbc:odbc:";
String DataSource = "Video";
//Holds the value from the database
String val1;
//SQL String for writing data to database
String SQLstring = "SELECT CustNum FROM Customers";
//Loads the driver for the database
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Error Loading driver\n"+e,"Driver Load Error",JOptionPane.WARNING_MESSAGE);
Statement stmt = null;
Connection con = null;
//Create a connection to the database.
try {
con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser, dbpasswd);
stmt = con.createStatement();
}catch (Exception e) {
JOptionPane.showMessageDialog(null,"Cannot connect to Database\n"+e,"Connection Error",JOptionPane.WARNING_MESSAGE);
ResultSet rs = null;
//Gets data from the database
try {
rs = stmt.executeQuery(SQLstring);
while (rs.next()){
val1 = rs.getString(1);
int val2 = Integer.parseInt(val1);
val2++;
CustNum.setText(String.valueOf(val2));
} catch (Exception e){
JOptionPane.showMessageDialog(null,"Cannot connect to database\n"+e,"Communication Error",JOptionPane.WARNING_MESSAGE);
try {
con.close();
} catch (Exception e){
JOptionPane.showMessageDialog(null,"Cannot close database\n"+e,"Error",JOptionPane.WARNING_MESSAGE);
//Adds the panel to the InternalFrame and display it
getContentPane().add(panel);
show();
//Here all action events are processed
public void actionPerformed(ActionEvent e) {
if (e.getSource() == Cancel){
dispose();
if (e.getSource() == Add){
ToDatabase();
//Here the document event is processed
public void adjust(DocumentEvent e){
Cell.setEnabled(e.getDocument().getLength()>0);
//Here the data will be sent to the database
public void ToDatabase() {
//Variables for the database
String dbuser = "";
String dbpasswd = "";
String DriverPrefix = "jdbc:odbc:";
String DataSource = "Video";
//SQL String for writing data to database
String SQLstring ="INSERT INTO Customers VALUES('"+CustNum.getText()+"', '"+CFName.getText()+"','"+CSName.getText()+"','"+Address1.getText()+"','"+Address2.getText()+"','"+City.getText()+"','"+PostCode.getText()+"','"+Tel.getText()+"','"+Cell.getText()+"')";
//Loads the driver for the database
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Error Loading driver\n"+e,"Driver Load Error",JOptionPane.WARNING_MESSAGE);
Statement stmt = null;
Connection con = null;
//Create a connection to the database.
try {
con = DriverManager.getConnection(DriverPrefix+DataSource,dbuser, dbpasswd);
stmt = con.createStatement();
}catch (Exception e) {
JOptionPane.showMessageDialog(null,"Cannot connect to Database\n"+e,"Connection Error",JOptionPane.WARNING_MESSAGE);
//Transfer data to database
try {
stmt.executeUpdate(SQLstring);
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Cannot update database\n"+e,"Communication Error",JOptionPane.WARNING_MESSAGE);
dispose();
The error that I receive is this:
VideoShop/addCustomer.java [98:1] <anonymous VideoShop.addCustomer$1> is not abstract and does not override abstract method changedUpdate(javax.swing.event.DocumentEvent) in javax.swing.event.DocumentListener
public void insertUpdate(DocumentEvent e){ //ERROR////////////
^
1 error
Errors compiling addCustomer.
Is there a way around this or should I rewrite the whole class.
Thanks
Alexander -
Need a little help with some errors.
Receiving some errors..
btn2.addActionListener(new ActionListener() {
and also
frame.setLocation(400,400);
frame.setVisible(true);
}<<~~has 2 errors here...
Both above have class or interface expected errors..clueless on what i'm missing at the moment.
Anyone mind pointing out what {'s and }'s i'm missing?
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
btn1actions();
private void btn1actions() {
if (radio1.isSelected()) System.out.println("Radio Button 1 is selected.");
if (radio2.isSelected()) System.out.println("Radio Button 2 is selected.");
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
btn2actions();
private void btn2actions() {
if (radio1.isSelected()) System.out.println("Radio Button 1 is selected.");
if (radio2.isSelected()) System.out.println("Radio Button 2 is selected.");
btn3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
btn1actions();
private void btn3actions() {
txt1.setText("");
txt1.requestFocus();
public static void main(String[] args) {
Test2 frame = new Test2();
frame.setTitle("Test Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLocation(400,400);
frame.setVisible(true);
}All my code..finally posted...just need help with more errors.
F:\DocumentsTest2.java:169: ';' expected
btn1.addActionListener(new ActionListener()) {
^
F:\Documents\Test2.java:176: illegal start of expression
private void btn1actions() {
^
F:\Documents\Test2.java:191: illegal start of expression
private void btn2actions() {
^
F:\Documents\.java:202: illegal start of expression
private void btn3actions() {
^
4 errors
Tool completed with exit code 1
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test2 extends JFrame{
static JButton btn1,btn2,btn3;
static JTextField txt1;
static JRadioButton radio1,radio2;
public Test2() {
Container container = getContentPane();
container.setLayout(new BorderLayout());
//Create Panels
JPanel Panel1 = new JPanel();
JPanel Panel2 = new JPanel();
JPanel Panel3 = new JPanel();
JPanel Panel4 = new JPanel();
JPanel Panel5 = new JPanel();
JPanel Panel6 = new JPanel();
JPanel Panel7 = new JPanel();
JPanel Panel8 = new JPanel();
JPanel Panel9 = new JPanel();
JPanel Panel10 = new JPanel();
//Set Layout for Panels
Panel3.setLayout(new BorderLayout());
Panel4.setLayout(new BorderLayout());
Panel5.setLayout(new BorderLayout());
Panel6.setLayout(new BorderLayout());
Panel10.setLayout(new BorderLayout());
//Create the Various Fonts and Colors for this GUI
Font font1 = new Font("SansSerif", Font.BOLD, 20);
Font font2 = new Font("Serif", Font.PLAIN, 15);
Color color1 = new Color(3,15,125);//A Dark Blue Color
Color color2 = new Color(201,29,10);//A Red Color
Color color3 = new Color(127,127,127);//A Grey Color
//Create Buttons and Labels
btn1 = new JButton("Submit");
btn2 = new JButton("Display Schedule");
btn3 = new JButton("Enter New Name");
JLabel label1 = new JLabel("Student Name");
JLabel label2 = new JLabel("Course Number");
JLabel label3 = new JLabel("Welcome to the Java Community College");
JLabel label4 = new JLabel("Registration System!");
//Declare Text Field For Entering Student Names
txt1 = new JTextField(15);
//"Put Course Number from another Method Here"
String[] courseStrings = { "CISM2230 A", "CISM2230 B", "CISM1110 A", "CISM1110 B", "CISM1120 A", "CISM1120 B" };
JComboBox Combo1 = new JComboBox(courseStrings);
//Declare Radio Buttons for Add and Drop Course
radio1 = new JRadioButton("Add a Course", false);
radio2 = new JRadioButton("Drop a Course", false);
ButtonGroup radioButtons = new ButtonGroup();
radioButtons.add(radio1);
radioButtons.add(radio2);
//Panel 10 is the Main Displaying Panel
Panel10.add(Panel3, BorderLayout.NORTH);
Panel10.add(Panel4, BorderLayout.CENTER);
Panel10.add(Panel8, BorderLayout.SOUTH);
//Panel 3 Used to Display Label 3 and 4 using Panels 1 and 2
Panel3.add(Panel1, BorderLayout.NORTH);
Panel3.add(Panel2, BorderLayout.CENTER);
Panel1.add(label3);
Panel2.add(label4);
//Panel 4 Used to Display Student Name, Txt1, Course Number, Combo Box and Radio Buttons
Panel5.add(label1, BorderLayout.NORTH);
Panel5.add(txt1, BorderLayout.CENTER);
Panel6.add(label2, BorderLayout.NORTH);
Panel6.add(Combo1, BorderLayout.CENTER);
Panel7.add(radio1, BorderLayout.NORTH);
Panel7.add(radio2, BorderLayout.CENTER);
Panel4.add(Panel5, BorderLayout.NORTH);
Panel4.add(Panel6, BorderLayout.CENTER);
Panel4.add(Panel7, BorderLayout.SOUTH);
//Panel 8 Used to Display the Buttons
Panel9.add(btn1, BorderLayout.CENTER);
Panel9.add(btn2, BorderLayout.CENTER);
Panel9.add(btn3, BorderLayout.SOUTH);
Panel8.add(Panel9, BorderLayout.CENTER);
//Setting Background, ForeGround and Font of all Text.
Panel1.setBackground(color3);
Panel2.setBackground(color3);
Panel3.setBackground(color3);
Panel4.setBackground(color3);
Panel5.setBackground(color3);
Panel6.setBackground(color3);
Panel7.setBackground(color3);
Panel8.setBackground(color3);
Panel9.setBackground(color3);
Panel10.setBackground(color3);
btn1.setBackground(color3);
btn2.setBackground(color3);
btn3.setBackground(color3);
radio1.setBackground(color3);
radio2.setBackground(color3);
btn1.setFont(font2);
btn2.setFont(font2);
btn3.setFont(font2);
Combo1.setFont(font2);
Combo1.setBackground(color3);
Combo1.setForeground(color1);
label1.setFont(font2);
label2.setFont(font2);
label3.setFont(font1);
label4.setFont(font1);
label1.setForeground(color2);
label2.setForeground(color2);
label3.setForeground(color1);
label4.setForeground(color1);
container.add(Panel10);
//Setting Keyboard Shortcuts to Radio Buttons and Regular Buttons
btn1.setMnemonic('S');
btn2.setMnemonic('D');
btn3.setMnemonic('E');
radio1.setMnemonic('A');
radio2.setMnemonic('C');
//ActionListener
btn1.addActionListener(new ActionListener()) {
public void actionPerformed(ActionEvent evt) {
btn1actions();
private void btn1actions() {
if (radio1.isSelected()){ System.out.println("Radio Button 1 is selected. Button 1")};
if (radio2.isSelected()){ System.out.println("Radio Button 2 is selected. Button 1")};
btn2.addActionListener(new ActionListener()) {
public void actionPerformed(ActionEvent evt) {
btn2actions();
private void btn2actions() {
if (radio1.isSelected()) System.out.println("Radio Button 1 is selected(Button 2).");
if (radio2.isSelected()) System.out.println("Radio Button 2 is selected.Button 2");
btn3.addActionListener(new ActionListener()) {
public void actionPerformed(ActionEvent evt) {
btn1actions();
private void btn3actions() {
txt1.setText("");
txt1.requestFocus();
public static void main(String[] args) {
JavaCollegeTest2 frame = new JavaCollegeTest2();
frame.setTitle("Project 4");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLocation(400,400);
frame.setVisible(true);
} -
Help with if statement in cursor and for loop to get output
I have the following cursor and and want to use if else statement to get the output. The cursor is working fine. What i need help with is how to use and if else statement to only get the folderrsn that have not been updated in the last 30 days. If you look at the talbe below my select statement is showing folderrs 291631 was updated only 4 days ago and folderrsn 322160 was also updated 4 days ago.
I do not want these two to appear in my result set. So i need to use if else so that my result only shows all folderrsn that havenot been updated in the last 30 days.
Here is my cursor:
/*Cursor for Email procedure. It is working Shows userid and the string
You need to update these folders*/
DECLARE
a_user varchar2(200) := null;
v_assigneduser varchar2(20);
v_folderrsn varchar2(200);
v_emailaddress varchar2(60);
v_subject varchar2(200);
Cursor c IS
SELECT assigneduser, vu.emailaddress, f.folderrsn, trunc(f.indate) AS "IN DATE",
MAX (trunc(fpa.attemptdate)) AS "LAST UPDATE",
trunc(sysdate) - MAX (trunc(fpa.attemptdate)) AS "DAYS PAST"
--MAX (TRUNC (fpa.attemptdate)) - TRUNC (f.indate) AS "NUMBER OF DAYS"
FROM folder f, folderprocess fp, validuser vu, folderprocessattempt fpa
WHERE f.foldertype = 'HJ'
AND f.statuscode NOT IN (20, 40)
AND f.folderrsn = fp.folderrsn
AND fp.processrsn = fpa.processrsn
AND vu.userid = fp.assigneduser
AND vu.statuscode = 1
GROUP BY assigneduser, vu.emailaddress, f.folderrsn, f.indate
ORDER BY fp.assigneduser;
BEGIN
FOR c1 IN c LOOP
IF (c1.assigneduser = v_assigneduser) THEN
dbms_output.put_line(' ' || c1.folderrsn);
else
dbms_output.put(c1.assigneduser ||': ' || 'Overdue Folders:You need to update these folders: Folderrsn: '||c1.folderrsn);
END IF;
a_user := c1.assigneduser;
v_assigneduser := c1.assigneduser;
v_folderrsn := c1.folderrsn;
v_emailaddress := c1.emailaddress;
v_subject := 'Subject: Project for';
END LOOP;
END;
The reason I have included the folowing table is that I want you to see the output from the select statement. that way you can help me do the if statement in the above cursor so that the result will look like this:
emailaddress
Subject: 'Project for ' || V_email || 'not updated in the last 30 days'
v_folderrsn
v_folderrsn
etc
[email protected]......
Subject: 'Project for: ' Jim...'not updated in the last 30 days'
284087
292709
[email protected].....
Subject: 'Project for: ' Kim...'not updated in the last 30 days'
185083
190121
190132
190133
190159
190237
284109
286647
294631
322922
[email protected]....
Subject: 'Project for: Joe...'not updated in the last 30 days'
183332
183336
[email protected]......
Subject: 'Project for: Sam...'not updated in the last 30 days'
183876
183877
183879
183880
183881
183882
183883
183884
183886
183887
183888
This table is to shwo you the select statement output. I want to eliminnate the two days that that are less than 30 days since the last update in the last column.
Assigneduser....Email.........Folderrsn...........indate.............maxattemptdate...days past since last update
JIM......... jim@ aol.com.... 284087............. 9/28/2006.......10/5/2006...........690
JIM......... jim@ aol.com.... 292709............. 3/20/2007.......3/28/2007............516
KIM......... kim@ aol.com.... 185083............. 8/31/2004.......2/9/2006............. 928
KIM...........kim@ aol.com.... 190121............. 2/9/2006.........2/9/2006.............928
KIM...........kim@ aol.com.... 190132............. 2/9/2006.........2/9/2006.............928
KIM...........kim@ aol.com.... 190133............. 2/9/2006.........2/9/2006.............928
KIM...........kim@ aol.com.... 190159............. 2/13/2006.......2/14/2006............923
KIM...........kim@ aol.com.... 190237............. 2/23/2006.......2/23/2006............914
KIM...........kim@ aol.com.... 284109............. 9/28/2006.......9/28/2006............697
KIM...........kim@ aol.com.... 286647............. 11/7/2006.......12/5/2006............629
KIM...........kim@ aol.com.... 294631............. 4/2/2007.........3/4/2008.............174
KIM...........kim@ aol.com.... 322922............. 7/29/2008.......7/29/2008............27
JOE...........joe@ aol.com.... 183332............. 1/28/2004.......4/23/2004............1585
JOE...........joe@ aol.com.... 183336............. 1/28/2004.......3/9/2004.............1630
SAM...........sam@ aol.com....183876.............3/5/2004.........3/8/2004.............1631
SAM...........sam@ aol.com....183877.............3/5/2004.........3/8/2004.............1631
SAM...........sam@ aol.com....183879.............3/5/2004.........3/8/2004.............1631
SAM...........sam@ aol.com....183880.............3/5/2004.........3/8/2004.............1631
SAM...........sam@ aol.com....183881.............3/5/2004.........3/8/2004.............1631
SAM...........sam@ aol.com....183882.............3/5/2004.........3/8/2004.............1631
SAM...........sam@ aol.com....183883.............3/5/2004.........3/8/2004.............1631
SAM...........sam@ aol.com....183884.............3/5/2004.........3/8/2004............ 1631
SAM...........sam@ aol.com....183886.............3/5/2004.........3/8/2004............ 1631
SAM...........sam@ aol.com....183887.............3/5/2004.........3/8/2004............ 1631
SAM...........sam@ aol.com....183888.............3/5/2004.........3/8/2004............ 1631
PAT...........pat@ aol.com.....291630.............2/23/2007.......7/8/2008............ 48
PAT...........pat@ aol.com.....313990.............2/27/2008.......7/28/2008............28
NED...........ned@ aol.com.....190681.............4/4/2006........8/10/2006............746
NED...........ned@ aol.com......95467.............6/14/2006.......11/6/2006............658
NED...........ned@ aol.com......286688.............11/8/2006.......10/3/2007............327
NED...........ned@ aol.com.....291631.............2/23/2007.......8/21/2008............4
NED...........ned@ aol.com.....292111.............3/7/2007.........2/26/2008............181
NED...........ned@ aol.com.....292410.............3/15/2007.......7/22/2008............34
NED...........ned@ aol.com.....299410.............6/27/2007.......2/27/2008............180
NED...........ned@ aol.com.....303790.............9/19/2007.......9/19/2007............341
NED...........ned@ aol.com.....304268.............9/24/2007.......3/3/2008............ 175
NED...........ned@ aol.com.....308228.............12/6/2007.......12/6/2007............263
NED...........ned@ aol.com.....316689.............3/19/2008.......3/19/2008............159
NED...........ned@ aol.com.....316789.............3/20/2008.......3/20/2008............158
NED...........ned@ aol.com.....317528.............3/25/2008.......3/25/2008............153
NED...........ned@ aol.com.....321476.............6/4/2008.........6/17/2008............69
NED...........ned@ aol.com.....322160.............7/3/2008.........8/21/2008............4
MOE...........moe@ aol.com.....184169.............4/5/2004.......12/5/2006............629
[email protected]/27/2004.......3/8/2004............1631
How do I incorporate a if else statement in the above cursor so the two days less than 30 days since last update are not returned. I do not want to send email if the project have been updated within the last 30 days.
Edited by: user4653174 on Aug 25, 2008 2:40 PManalytical functions: http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96540/functions2a.htm#81409
CASE
http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96624/02_funds.htm#36899
http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96624/04_struc.htm#5997
Incorporating either of these into your query should assist you in returning the desired results. -
I installed Sunbird in one computer and my calendar has all my infos, events, and task that i would like to see on another computer that i just downloaded Sunbird into. Also, is it possible I can access Sunbird on my iphone?
Thank you in advance,Try the forum here - http://forums.mozillazine.org/viewforum.php?f=46 - for help with Sunbird, this forum is for Firefox support.
-
Hoping for some help with a very frustrating issue!
I have been syncing calendar and contacts on my iPhone 5 and Outlook 2007 using iCloud 2.1.3 (my PC is running Vista). All was well until the events I entered on the phone were showing up in Outlook, but not the other way around. I’ve tried the usual recommended steps: deselecting calendar and contacts in the iCloud control panel and then re-selecting, signing out of the panel and back in, and repairing the Outlook installation in control panel. I even uninstalled iCloud on the PC and downloaded it again (same version).
The furthest I’ve gotten is step 2 (and once, step 3) of 7 while performing “Outlook Setup For iCloud.” At that point I get, “Your setup couldn’t be started because of an unexpected error.” After the first attempt at all this, all my calendar events disappeared from Outlook, although they are still in iCloud calendar and on my phone.
Sound familiar? Any ideas on how to solve this iCloud/Outlook issue? Thanks much in advance!Hoping for some help with a very frustrating issue!
I have been syncing calendar and contacts on my iPhone 5 and Outlook 2007 using iCloud 2.1.3 (my PC is running Vista). All was well until the events I entered on the phone were showing up in Outlook, but not the other way around. I’ve tried the usual recommended steps: deselecting calendar and contacts in the iCloud control panel and then re-selecting, signing out of the panel and back in, and repairing the Outlook installation in control panel. I even uninstalled iCloud on the PC and downloaded it again (same version).
The furthest I’ve gotten is step 2 (and once, step 3) of 7 while performing “Outlook Setup For iCloud.” At that point I get, “Your setup couldn’t be started because of an unexpected error.” After the first attempt at all this, all my calendar events disappeared from Outlook, although they are still in iCloud calendar and on my phone.
Sound familiar? Any ideas on how to solve this iCloud/Outlook issue? Thanks much in advance!
Maybe you are looking for
-
HP Officejet Pro 8600 and OSX 10.9 Mavericks
Am not able to duplex print. The duplex print accessory is properly installed. I have tried opening the System Preferences and going to Print & Fax. I have opened the print queue and clicked on Printer Setup, but then there is no Driver tab. Wher
-
Fraudulent application for more credit
An application [removed for privacy] for Euro15 credit was made today BUT NOT BY ME OR ANYONE AUTHORISED BY ME. Please check the source. Meanwhile I am ordering Euro25 more credit and please do not refuse this.
-
10.6 Performance Problems
Although I installed Snow Leopard from scratch, I encountered severe performance problems after a while. To copy a file, for instance, took minutes instead of seconds for a some 100 MB file. To switch between windows took long time. The processing wa
-
I'm new to MainStage. Does anyone know if i create multiple channel strips of the same plugin ( i'm using Ivory ) will MainStage try to share samples/resources between the channel strips? Or does each additional Channel Strip of the same plugin doubl
-
When we have a new employee transfer to us from another department, their email is created and hidden until they actually make the transfer so they don't have two different email addresses in our global address list. When the transfer is made, the e