EDIT2: Tested it. It is definetily a problem with the new JPanel.
SOLUTION:
As proposed the answer is that i forgot to explicitely set my JPanel onto my JFrame. Change:
setContentPane(contentPanetagesliste);
to
frame.setContentPane(contentPanetagesliste);
and it works for me!
My Problem is a strange behavior of JFrame.
In my code I got a radioButton on my MainFrame. When it is pressed it opens up the other Frame.
RadioBTNtagesliste.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
frame.setSize(590, 450); ...
In my new Frame I made a JPanel. Before adding the JPanel the other Frame didn't freeze, so I believe the problem got something to do with the new JPanel.
JPanel contentPanetagesliste;
contentPanetagesliste = new JPanel();
contentPanetagesliste.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPanetagesliste);
In the end I add a JScrollPane to the JPanel (that's the reason why I had to make one) and make the JFrame visible.
JScrollPane jsp = new JScrollPane(contentPanetagesliste);
frame.add(jsp);
frame.setVisible(true);
I absolutely have no clue how the new JPanel could interfere with the Main JFrame or the JPanel lying above the MainJFrame. I hope some of you can help me.
EDIT: because it wasn't clear to some: by stuck i mean unresponsive and when i move it, it goes blank grey.
To the image: When I press the radio button to the far top right, the new window opens, is fully functional but the old window is stuck.
image
For additional information I'll post the complete code from my action listener with explanation.
RadioBTNtagesliste.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
try {
if(RadioBTNtagesliste.isSelected() == true){
String Eintrag = HttpClass.httpRequestEintrag(usernamevar,EintragStringPK,"eintragTABLE");
JSONObject jsonObjectEintrag = new JSONObject(Eintrag);
int ProjektJSONlength = jsonObjectEintrag.length() - 1;
frame.setSize(590, 450);
JPanel contentPanetagesliste;
contentPanetagesliste = new JPanel();
contentPanetagesliste.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPanetagesliste);
double[] temp = new double[ProjektJSONlength+2];
temp[0] = 10;
temp[1] = 30;
for(int i = 0; i < ProjektJSONlength; i++){
temp[i+2] = 25;
}
double size[][] = {{2, 90, 90, 90, 90, 90,90, 2}, // Columns
temp}; // Rows
contentPanetagesliste.setLayout(new TableLayout(size));
String label[] = {"Eintrag Nr.", "Projekt", "Aktivität", "Dauer", "Beschreibung", "Symbol"};
JButton button[] = new JButton[label.length];
JTextField textfield[] = new JTextField[label.length];
for (int i = 0; i < label.length; i++) {
button[i] = new JButton(label[i]);
}
contentPanetagesliste.add(button[0], "1, 1");
contentPanetagesliste.add(button[1], "2, 1");
contentPanetagesliste.add(button[2], "3, 1");
contentPanetagesliste.add(button[3], "4, 1");
contentPanetagesliste.add(button[4], "5, 1");
contentPanetagesliste.add(button[5], "6, 1");
EintragStringPK = "Neu";
for (int key=0; key<=ProjektJSONlength;key++) {
JSONObject jsonObjectProjekteObjekt0 = jsonObjectEintrag.getJSONObject(String.valueOf(key));
String Eintraege = jsonObjectProjekteObjekt0.toString();
String EintragStringDauer = jsonObjectProjekteObjekt0.getString("dauer"); // String auslesen!!!
String EintragStringBEschreibung = jsonObjectProjekteObjekt0.getString("beschreibung"); // String auslesen!!!
String EintragStringProjektname = jsonObjectProjekteObjekt0.getString("projektname"); // String auslesen!!!
String EintragStringAktivitaet = jsonObjectProjekteObjekt0.getString("kategorie"); // String auslesen!!!
EintragStringPK = jsonObjectProjekteObjekt0.getString("pk_ei_id"); // String auslesen!!!
System.out.println("test" + key);
System.out.println(ProjektJSONlength);
String labelCONTENT[] = {EintragStringPK, EintragStringProjektname, EintragStringAktivitaet, EintragStringDauer, EintragStringBEschreibung, "Symbol"};
for (int i = 0; i < labelCONTENT.length; i++) {
textfield[i] = new JTextField(labelCONTENT[i]);
}
int keypone = key+2;
String keyString = Integer.toString(keypone);
contentPanetagesliste.add(textfield[0], "1, "+keyString);
contentPanetagesliste.add(textfield[1], "2, "+keyString);
contentPanetagesliste.add(textfield[2], "3, "+keyString);
contentPanetagesliste.add(textfield[3], "4, "+keyString);
contentPanetagesliste.add(textfield[4], "5, "+keyString);
contentPanetagesliste.add(textfield[5], "6, "+keyString);
}
JScrollPane jsp = new JScrollPane(contentPanetagesliste);
frame.add(jsp);
frame.setVisible(true);
System.out.println("ende");
}else{
frame.setVisible(false);
System.out.println("ende2");
}
System.out.println("ende3");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("ende4");
}
});
Explanation:
I create the JFrame, afterwards the JPanel.
Create an Array and the rest necessary for my Table, because the goal is to make a generated table with data from a SQL DB.
There is also a HTTPrequest and a loop to get out the data and put it into the table fields.
Still in the loop the filled table fields are added to the content pane and at the very and the Jpanel get's his JScrollPane and the frame is set visible.
I really hope someone can help me, and if you got tips for making better questions I've got an open ear.
setContentPane(contentPanetagesliste); should be explicit set to the new frame you created like this: frame.setContentPane(contentPanetagesliste);.
Related
I'm trying to create a hangman game using the Swing class and Graphics class for a APCS class I have.
I created a JButton that would take the guess typed in by the user and either add it to the "misses" or fill in all of the corresponding letters in the word. I have a separate txt file where I pick a random word from.
When I run the program, all of the components show up, but the button does not do anything. I have been working on this for a few days and don't know what I am doing wrong. I have only learnt how to use the Swing class recently, so it may be a stupid mistake for all I know. I have put all of the code down below.
public class Hangman extends JFrame {
DrawPanel panel = new DrawPanel();
Graphics g = panel.getGraphics();
JTextField guess;
JTextField outputWord;
JTextField missesString;
boolean play;
JButton button = new JButton();
String output = "";
String word;
int misses = 0;
public Hangman() {
int again = 0;
String[] dictionary = new String[1000];
In words = new In("words.txt");
JFrame app = new JFrame();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setVisible(true);
app.setSize(500, 500);
for (int i = 0; i < 1000; i++) {
dictionary[i] = words.readLine();
}
do {
int num = (int) (Math.random() * 1000);
word = dictionary[num].toLowerCase();
String answer = word;
word = "";
for (int i = answer.length(); i > 0; i--) {
word = word + "*";
}
int length = answer.length();
app.setLayout(new BorderLayout());
JLabel letter = new JLabel();
letter.setFont(new Font("Arial", Font.BOLD, 20));
letter.setText("Enter Your guess");
guess = new JTextField(10);
JLabel output = new JLabel();
output.setFont(new Font("Arial", Font.BOLD, 20));
output.setText("The Word is");
outputWord = new JTextField(30);
outputWord.setText(word);
outputWord.setEditable(false);
JLabel misses = new JLabel();
misses.setFont(new Font("Arial", Font.BOLD, 20));
misses.setText("Misses:");
missesString = new JTextField(52);
missesString.setEditable(false);
button = new JButton("Guess");
button.addActionListener(new ButtonListener());
JPanel panels = new JPanel();
panels.setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.add(letter);
panel1.add(guess);
panel1.add(button);
JPanel panel2 = new JPanel();
panel2.add(output);
panel2.add(outputWord);
JPanel panel3 = new JPanel();
panel3.add(misses);
panel3.add(missesString);
app.add(panel1, BorderLayout.NORTH);
app.add(panel2, BorderLayout.EAST);
app.add(panel3, BorderLayout.SOUTH);
app.add(panels);
app.setVisible(true);
again = JOptionPane.showConfirmDialog(null, "Do you want to play again?");
} while (again == JOptionPane.YES_OPTION);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == guess) {
output = "";
}
for (int i = 0; i <= word.length() - 1; i++) {
if (guess.getText().equalsIgnoreCase(word.substring(i, i + 1))) {
output = output.substring(0, i) + guess + output.substring(i + 1, word.length() - 1);
outputWord.setText(output);
} else {
misses++;
missesString.setText(missesString.getText() + guess + " ");
}
}
}
}
}
The components show up perfectly on the screen, it is only the button that is giving me a hard time by not working as expected.
I am trying to allow a user click a btnGenerate which then generates a random number that is assigned to a phrase that can be called to print out the phrase in a box below the button in the application window in eclipse.
The problem is that the random statement comes up on the Eclipse console instead of the textbox on my GUI.
Any help is appreciated. Here is my code so far:
//generate crime button
JButton generateBtn = new JButton("Generate Crime");
generateBtn.setBackground(Color.LIGHT_GRAY);
generateBtn.setFont(new Font("HGHeiseiKakugothictaiW3", Font.BOLD, 20));
GridBagConstraints gbc_generateBtn = new GridBagConstraints();
gbc_generateBtn.fill = GridBagConstraints.BOTH;
gbc_generateBtn.insets = new Insets(0, 0, 5, 5);
gbc_generateBtn.gridx = 15;
gbc_generateBtn.gridy = 5;
frmHeroVillains.getContentPane().add(generateBtn, gbc_generateBtn);
generateBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
/*random number generator that generates a number between 1-4 and outputs a random crime to the updatePane depending on which
number was generated */
int number = ((int) (Math.random()*4)+1);
switch (number) {
case 1:
System.out.println("Jewelry Heist on main street!");
break;
case 2:
System.out.println("Mugging in China town!");
break;
case 3:
System.out.println("Boeing 247 - Hijacked!");
default:
System.out.println("Nothing to Report.");
break;
}
;
JLabel updateLabel = new JLabel("UPDATE ALERT.... " + number);
GridBagConstraints gbc_updateLabel = new GridBagConstraints();
gbc_updateLabel.gridheight = 3;
gbc_updateLabel.insets = new Insets(0, 0, 5, 5);
gbc_updateLabel.gridx = 15;
gbc_updateLabel.gridy = 12;
frmHeroVillains.getContentPane().add(updateLabel, gbc_updateLabel);} }
);
You need to redirect the System.out.println(...) message to your own component.
Check out the Message Console for one approach to doing this. You can redirect the output to a JTextArea or JTextPane.
public static void main(String[] args) throws Exception {
//Must throws Exception
JPanel myOutput = new JPanel();
myOutput.setVisible(true);
myOutput.setBackground(Color.GRAY);
JTextArea mynewText = new JTextArea();
myOutput.add(mynewText);
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(
oracle.openStream()));
//InputStreamReader wrapped in BufferedReader
String inputLine;
inputLine = in.readLine();
mynewText.setText(inputLine);
in.close();
//In the target window class
mainWindow.add(myOutput);
I need help creating a Java swing form. The form is dynamically created and asks the user for various inputs. The inputs vary and could be Textfields, RadioButton, ComboBox. I'm trying to determine what is the best layout for such a form. Currently, I have something like:
JPanel pnlForm = new JPanel(new SpringLayout());
for (Parameter p : globals) {
JLabel lblName = new JLabel(p.getName() + ": ", JLabel.TRAILING);
pnlForm.add(lblName);
// The input field depends on parameter type
if (p.getType().equals("filename")) {
JPanel pnlFileChooser = new JPanel();
JTextArea txtArea = new JTextArea(p.getValue());
JButton btnFileChooser = new JButton("Browse");
pnlFileChooser.add(txtArea);
pnlFileChooser.add(btnFileChooser);
pnlForm.add(pnlFileChooser);
} else if (p.getType().equals("textbox")) {
JTextArea txtArea = new JTextArea(p.getValue());
pnlForm.add(txtArea);
} else if (p.getType().equals("checkbox")) {
// not yet implemented
} else if (p.getType().equals("radio")) {
ButtonGroup bgRadios = new ButtonGroup();
for(String option : p.getSelections()){
JRadioButton btnOption = new JRadioButton(option);
btnOption.setMnemonic(KeyEvent.VK_B);
btnOption.setActionCommand(option);
bgRadios.add(btnOption);
pnlForm.add(btnOption);
}
} else {
JLabel lblError = new JLabel("ERROR! Unknown type!" + p.getType());
lblName.setLabelFor(lblError);
pnlForm.add(lblError);
}
//Lay out the panel.
SpringUtilities.makeCompactGrid(pnlDetails,
globals.size() - 1, 2, //rows, cols
1, 1, //initX, initY
5, 5); //xPad, yPad
This is currently coming up very choppy (the radio buttons wont stay in the same area). Any thoughts on how I could make this layout better?
Thanks!
[edit]
Adding the following diagram as to what this may look like. The gray lines can be ignored, just there to show where a JPanel might be. Each row is dynamically generated based on some user input. How can I make a form that looks like this?
I ended up getting this working using the SpringLayout with two panels on each row. The left panel contains the label and the right contains the input field. This seems to work well:
for (Parameter p : params) {
// The label for this parameter
JLabel pname = new JLabel(p.getName() + ": ", JLabel.TRAILING);
// Setup the sub panels for this layout, aligned to point each other
JPanel pnlLeft = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JPanel pnlRight = new JPanel(new FlowLayout(FlowLayout.LEFT));
// The value field for this parameter, depends on param type
if (p.getType().equals("filename")) {
JButton btnBrowse = new JButton("Browse");
btnBrowse.setActionCommand(pfilepath + p.getId());
btnBrowse.addActionListener(this);
JTextField pvalue = new JTextField(p.getValue(),50);
pnlRight.add(pvalue);
pnlRight.add(btnBrowse);
} else if (p.getType().equals("directory")) {
JButton btnBrowse = new JButton("Browse");
btnBrowse.setActionCommand(pdirpath + p.getId());
btnBrowse.addActionListener(this);
JTextField pvalue = new JTextField(p.getValue(),50);
pnlRight.add(pvalue);
pnlRight.add(btnBrowse);
} else if (p.getType().equals("textbox")) {
JTextField pvalue = new JTextField(p.getValue(),50);
pnlRight.add(pvalue);
} else if (p.getType().equals("checkbox")) {
for(String option : p.getSelections()){
JCheckBox chkbox = new JCheckBox(option);
if (p.getValue().contains(option)){
chkbox.setSelected(true);
}
chkbox.setName(p.getId() + "_" + option);
chkbox.setActionCommand(pchkbox + p.getId() + "_" + option);
chkbox.addActionListener(this);
pnlRight.add(chkbox);
}
} else if (p.getType().equals("radio")) {
ButtonGroup bgRadios = new ButtonGroup();
for(String option : p.getSelections()){
JRadioButton radio = new JRadioButton(option);
if (p.getValue().equals(option)){
radio.setSelected(true);
}
radio.setName(p.getId() + "_" + option);
radio.setActionCommand(pradio + p.getId() + "_" + option);
radio.addActionListener(this);
bgRadios.add(radio);
pnlRight.add(radio);
}
} else {
JTextField pvalue = new JTextField(p.getValue(),50);
pvalue.setText("ERROR! Invalid global parameter type!" + p.getType());
pvalue.setEditable(false);
pnlRight.add(pvalue);
}
// Add subpanels to this main panel and set labeling
pnlLeft.add(pname);
pname.setLabelFor(pnlRight);
add(pnlLeft);
add(pnlRight);
}
// Correctly setup SpringLayout grid for this main panel
SpringUtilities.makeCompactGrid(this,
params.size(), 2, //rows, cols
1, 1, //initX, initY
1, 1); //xPad, yPad
I'm using a vector to store the information displayed in the JList and I want to use the index of the selected index to copy the data of that row into the JTextField and JTextArea. I am having some issues where the selected item isn't be shown in the JTextField/Area but instead showing the data of a previous selected index. Every second index has an issue of showing the wrong data, 2, 4, 6, 8, 10 and then 11. Each of them will only show the right data if you select first when the program has just been executed. The print lines that I have added to the ListSelectionEvent listener shows the correct data of the selected index but it doesn't correctly copy it into the JTextArea/JTextField.
Selected right after the program was executed.
I selected a few other indices then tried to select it again
code:
public class EditFlashcardGui implements ListSelectionListener {
private JFrame frame;
private JPanel listPanel;
private Vector<Vector> flashcardMasterVector = new Vector<Vector>();
private JList list;
private JPanel tablePanel, dataPanel, textFieldPanel;
private JButton submitButton, cancelButton;
private JTextField frontTextField;
private JTextArea reverseTextArea;
private GridBagLayout gridBagLayout;
private GridBagConstraints constraints;
private JLabel frontTextLabel, reverseTextLabel;
Vector<Vector> masterVector = new Vector<Vector>();
public EditFlashcardGui() {
frame = new JFrame("Edit / Delete Flashcards");
frame.setSize(500, 200);
Container con = frame.getContentPane();
con.setLayout(new BorderLayout());
listPanel = new JPanel(new BorderLayout());
Vector<String> columnNames = new Vector<String>();
columnNames.add("id");
columnNames.add("front text");
columnNames.add("reverse text");
list = new JList(populateList());
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.addListSelectionListener(this);
Font font1 = new Font("SansSerif", Font.BOLD, 20);
list.setFont(font1);
tablePanel = new JPanel();
tablePanel.add(list);
JScrollPane scrollPane = new JScrollPane(list);
con.add(scrollPane, BorderLayout.NORTH);
// south panel
gridBagLayout = new GridBagLayout();
constraints = new GridBagConstraints();
textFieldPanel = new JPanel(gridBagLayout);
// cancelButton = new JButton("Cancel");
// dataPanel.add(cancelButton, BorderLayout.SOUTH);
frontTextLabel = new JLabel("Front Text");
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 0;
gridBagLayout.setConstraints(frontTextLabel, constraints);
textFieldPanel.add(frontTextLabel);
frontTextField = new JTextField();
frontTextField.setColumns(30);
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 1;
gridBagLayout.setConstraints(frontTextField, constraints);
textFieldPanel.add(frontTextField);
reverseTextLabel = new JLabel("Reverse Text");
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 2;
gridBagLayout.setConstraints(reverseTextLabel, constraints);
textFieldPanel.add(reverseTextLabel);
reverseTextArea = new JTextArea(3, 30);
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 3;
gridBagLayout.setConstraints(reverseTextArea, constraints);
textFieldPanel.add(reverseTextArea);
submitButton = new JButton("Submit");
constraints.ipadx = 1;
constraints.ipady = 1;
constraints.gridx = 0;
constraints.gridy = 4;
gridBagLayout.setConstraints(submitButton, constraints);
textFieldPanel.add(submitButton);
con.add(textFieldPanel, BorderLayout.CENTER);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
public Vector<Vector> populateList() {
//flashcardMasterVector = flashcardDB.getList();
//Vector<String> flashcardVector = new Vector<String>();
Integer temp = 0;
for(int i = 0; i <= 20; i++) {
Vector<String> flashcardVector = new Vector<String>();
flashcardVector.add(temp.toString());
flashcardVector.add(temp.toString());
flashcardVector.add(temp.toString());
masterVector.add(i, flashcardVector);
temp++;
}
return masterVector;
}
public static void main(String[] args) {
EditFlashcardGui gui = new EditFlashcardGui();
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (! e.getValueIsAdjusting())
{
System.out.print("id : " );
System.out.println(masterVector.get(list.getSelectedIndex()).get(0));
System.out.print("front text : ");
System.out.println(masterVector.get(list.getSelectedIndex()).get(1));
frontTextField.setText(masterVector.get(e.getFirstIndex())
.get(1).toString());
System.out.print("reverse text : ");
System.out.println(masterVector.get(list.getSelectedIndex()).get(2));
reverseTextArea.setText(masterVector.get(e.getFirstIndex())
.get(2).toString());
}
}
}
have to read Oracles tutorial about How to Use JList
you can't put Vector<Vector> to the JList directly,
put value and to use XxxListModel only, but in this case have to create crazy workaround for AbstractListModel, use simple array instead
JList is based on one dimensional array have to use Vector<Object (or String or Double...)>
don't complicate simple things put this array to the JTable (to the XxxTableModel), remove all synchronizations columns, remove JTableHeader if required, then output to the GUI looks like as JList
JTable.removeColumn remove only column from view, all data are still presented and stored into XxxTableModel without any changes
then selected (have to test for -1 == none of row is selected) row (have to convertViewToModel in the case that JTable is sorted or filtered) returns all required data from XxxTableModel
Use list.getSelectedIndex() instead of e.getFirstIndex() method.
Code :
frontTextField.setText( masterVector.get(list.getSelectedIndex() ).get(1).toString() );
reverseTextArea.setText(masterVector.get( list.getSelectedIndex()).get(2).toString() );
Clean Code:
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
Vector masterVec = masterVector.get( list.getSelectedIndex() );
System.out.print("id : ");
System.out.println(masterVec.get(0));
System.out.print("front text : ");
System.out.println(masterVec.get(1));
System.out.print("reverse text : ");
System.out.println(masterVec.get(2));
frontTextField.setText(masterVec.get(1).toString());
reverseTextArea.setText(masterVec.get(2).toString());;
}
}
I'm using an object of JTextArea in my application which deals with sending sms.
I've used a DocumentFilter so as to allow only 160 characters to be typed in the textarea but now, I want the size of the textarea to be constant. it goes on increasing if I keep writing on the same line without pressing 'enter' key or even when I keep on pressing only Enter key. I tried once using 'scrollbar' too but the problem remains same. Suggest me something over this. Below is my code. Please check it.
class Send_sms extends JPanel implements ActionListener,DocumentListener
{
JButton send;
JTextArea smst;
JLabel title,limit;
JPanel mainp,titlep,sendp,wrap,titlewrap,blankp1,blankp2,sendwrap;
JScrollPane scroll;
Border br,blackbr;
Boolean flag = false;
PlainDocument plane;
public static final int LINES = 4;
public static final int CHAR_PER_LINE = 40;
//character limit 160 for a sms
public Send_sms()
{
br = BorderFactory.createLineBorder(Color.RED);
blackbr = BorderFactory.createEtchedBorder(EtchedBorder.RAISED,Color.DARK_GRAY,Color.GRAY);
setBorder(blackbr);
title = new JLabel("Enter the text you want to send!");
title.setFont(new Font("",Font.BOLD,17));
limit = new JLabel(""+charCount+" Characters");
smst = new JTextArea(LINES,CHAR_PER_LINE);
smst.setSize(100,100);
plane = (PlainDocument)smst.getDocument();
//adding DocumentSizeFilter 2 keep track of characters entered
plane.setDocumentFilter(new DocumentSizeFilter(charCount));
plane.addDocumentListener(this);
send = new JButton("Send");
send.setToolTipText("Click Here To Send SMS");
send.addActionListener(this);
//scroll = new JScrollPane(smst);
//scroll.setPreferredSize(new Dimension(200,200));
//scroll.setVerticalScrollBarPolicy(null);
//scroll.setHorizontalScrollBarPolicy(null);
smst.setBorder(br);
blankp1 = new JPanel();
blankp2 = new JPanel();
titlep = new JPanel(new FlowLayout(FlowLayout.CENTER));
titlewrap = new JPanel(new GridLayout(2,1));
mainp = new JPanel(new BorderLayout());
sendwrap = new JPanel(new GridLayout(3,1));
sendp = new JPanel(new FlowLayout(FlowLayout.CENTER));
wrap = new JPanel(new BorderLayout());
titlep.add(title);
titlewrap.add(titlep);
titlewrap.add(blankp1);
sendp.add(send);
sendwrap.add(limit);
sendwrap.add(blankp2);
sendwrap.add(sendp);
wrap.add(smst,BorderLayout.CENTER);
mainp.add(titlewrap,BorderLayout.NORTH);
mainp.add(wrap,BorderLayout.CENTER);
mainp.add(sendwrap,BorderLayout.SOUTH);
add(mainp);
}
public void actionPerformed(ActionEvent e)
{
Vector<Vector<String>> info = new Vector<Vector<String>> ();
Vector<String> numbers = new Vector<String>();
if(e.getSource() == send)
{
//Call a function to send he message to all the clients using text
//charCount = 165;
String msg = smst.getText();
if(msg.length() == 0)
JOptionPane.showMessageDialog(null,"Please Enter Message","Error",JOptionPane.ERROR_MESSAGE);
else
{
// System.out.println("Message:"+msg);
Viewdata frame = new Viewdata(msg);
limit.setText(""+charCount+" Characters");
charCount = 160;
}
}
}
public void insertUpdate(DocumentEvent e)
{
System.out.println("The legth:(insert) "+e.getLength());
for(int i = 0;i<e.getLength(); i++)
{
if(charCount >0)
charCount--;
else
break;
}
limit.setText(""+charCount+" Characters");
}
public void removeUpdate(DocumentEvent e)
{
//System.out.println("The legth(remove): "+e.getLength());
for(int i = 0;i<e.getLength(); i++)
{
charCount++;
}
limit.setText(""+charCount+" Characters");
}
public void changedUpdate(DocumentEvent e)
{
//System.out.println("The legth(change): "+e.getLength());
}
}//end Send_sms
Sound like you are creating the text area using
JTextArea textArea = new JTextArea();
When using this format the text area doesn't have a preferred size so it keeps on growing. If you use:
JTextArea textArea = new JTextArea(2, 30);
JScrollPane scrollPane = new JScrollPane( textArea );
Then the text area will have a preferred size of 2 rows and (roughly) 30 columns. As you type when you exceed the preferred width the horizontal scrollbar will appear. Or if you turn on wrapping, then the text will wrap and a vertical scrollbar will appear.
you need to specify:
textArea.setColumns (160);
textArea.setLineWrap (true);
textArea.setWrapStyleWord (false); //default
But the real problem is that you allow to input more than 160 characters. You need to create some kind of validator which will skip all inputed characters when there are already 160 characters written.
Initialise the textArea with a document that extends PlainDocument and in the insertString method limit the characters to 160