Java Swing ComboBox not editabl *with MCVE* - java

I've come across a very weird problem. I had a JPanel which contains JTextFields and JComboBoxes. I can change the JComboBox's when the JPanel loads but as soon as I touch or edit one of the JTextFields it doesn't let me change any of the combobox's...
Here is an MCVE that works. You can use it straight away and you'll see the error.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Main extends JFrame{
private static JTextField s;
private static JTabbedPane tabbedPane;
private static JPanel config;
private static JComboBox<Object> dns;
private static JComboBox<Object> dnsmm;
private static JButton save;
private static String interval;
private static String dnsen;
private static String dnsm;
private static JPanel server;
static JPanel contentPane;
public static void main(String[] args) throws InterruptedException {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Main() throws IOException {
setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 655, 470);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(1, 1));
setContentPane(contentPane);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
contentPane.add(tabbedPane, BorderLayout.CENTER);
setResizable(false);
server = new JPanel();
server.setLayout(new BorderLayout(0, 0));
ServerPanel();
}
public static void ServerPanel() throws IOException{
tabbedPane.addTab("Manage Server", server);
InputStream in = new FileInputStream("config.dedserver");
Properties p = new Properties();
p.load(in);
in.close();
String saveInt = p.getProperty("saveInterval");
String dnse = p.getProperty("enableDns");
String dnsmo = p.getProperty("serverMode");
config = new JPanel();
server.add(config, BorderLayout.CENTER);
config.setLayout(new BoxLayout(config, BoxLayout.PAGE_AXIS));
//saveint
Panel panel_6 = new Panel();
config.add(panel_6);
JLabel sl = new JLabel("Save Interval (milliseconds): ");
panel_6.add(sl);
s = new JTextField(saveInt);
panel_6.add(s);
s.setColumns(10);
//dnsenabled
Panel panel_9 = new Panel();
config.add(panel_9);
JLabel dnsl = new JLabel("DNS Enabled: ");
panel_9.add(dnsl);
String[] dnsS = { "true", "false" };
dns = new JComboBox<Object>(dnsS);
dns.setSelectedItem(dnse);
dns.addActionListener(dns);
panel_9.add(dns);
//dnsmode
Panel panel_10 = new Panel();
config.add(panel_10);
JLabel dnsml = new JLabel("DNS Server Mode: ");
panel_10.add(dnsml);
String[] dnsm = { "local", "remote" };
dnsmm = new JComboBox<Object>(dnsm);
dnsmm.setSelectedItem(dnsmo);
dnsmm.addActionListener(dnsmm);
panel_10.add(dnsmm);
JPanel panel_7= new JPanel();
config.add(panel_7);
save = new JButton("Save");
panel_7.add(save);
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
errorCheck();
}
});
}
public static void errorCheck(){
interval = s.getText();
dnsen = (String) dns.getSelectedItem();
dnsm = (String) dnsmm.getSelectedItem();
interval = checkValues(interval, "60000", "save interval");
saveValues();
}
public static String checkValues(String value, String def, String name){
String val;
try{
Long.parseLong(value);
val = ""+value+"";
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "You did not enter a valid number for the "+ name + " field! It has been set to the default.");
val = def;
}
return val;
}
public static void saveValues(){
try {
Properties props = new Properties();
props.setProperty("saveInterval", interval);
props.setProperty("serverMode", dnsm);
props.setProperty("enableDns", dnsen);
File f = new File("config.dedserver");
OutputStream out = new FileOutputStream(f);
props.store(out, "");
JOptionPane.showMessageDialog(null, "Saved Config Values!");
}
catch (Exception e ) {
e.printStackTrace();
}
}
}
For it to work you will also need to make a config.dedserver in the root of the project and add the following stuff into it:
#
#Thu Jul 09 08:29:33 BST 2015
saveMethod=h2
startingGems=9999999999
enableDns=true
startingGold=9999999999
startingDarkElixir=9999999999
startingElixir=9999999999
serverMode=remote
saveInterval=30000
maxNameChanges=100
For the entire ServerPanel.java code it is here: http://pastebin.com/tvBENHQa
I'm not sure why this isn't working. Does anyone have any ideas?
Thank you!

A real MVCE would have been stripped down a lot further. It would also have included the properties instead of relying on an external file, e.g.
Properties p = new Properties();
p.put("saveMethod","h2");
p.put("startingGems","9999999999");
p.put("enableDns","true");
p.put("startingGold","9999999999");
p.put("startingDarkElixir","9999999999");
p.put("startingElixir","9999999999");
p.put("serverMode","remote");
p.put("saveInterval","30000");
p.put("maxNameChanges","100");
But apart from that, the code provided at least allowed us to reproduce the problem.
The problem is that you are mixing Swing components with AWT components. You have lines like
Panel panel_10 = new Panel();
in your program. Switch from a java.awt.Panel to a javax.swing.JPanel
JPanel panel_10 = new JPanel();
and your problem will be solved.

Related

Java, make JTabbedPane pop up

I would like my original window to close when someone enters the password and a new one to pop up, or if you have a better recommendation please tell me. Here is my code,
The main class,
package notebook;
import java.awt.EventQueue;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.CompoundBorder;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
public class mainPage extends JDialog {
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainPage frame = new mainPage();
frame.setVisible(true);
frame.setResizable(false);
Image icon = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB_PRE);
frame.setIconImage(icon);
frame.setTitle("Notebook");
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws IOException
*/
public mainPage() throws IOException {
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setBounds(100, 100, 560, 390);
JLabel contentPane = new JLabel(
new ImageIcon(
ImageIO.read(new File(
"C:\\Users\\Gianmarco\\workspace\\notebook\\src\\notebook\\cool_cat.jpg"))));
contentPane.setBorder(new CompoundBorder());
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblEnterPassword = new JLabel(" Enter Password");
lblEnterPassword.setForeground(Color.LIGHT_GRAY);
lblEnterPassword.setBackground(Color.DARK_GRAY);
lblEnterPassword.setOpaque(true);
lblEnterPassword.setBounds(230, 60, 100, 15);
contentPane.add(lblEnterPassword);
security sInfo = new security();
textField = new JPasswordField(10);
nbTab notebook = new nbTab();
Action action = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
String textFieldValue = textField.getText();
if (sInfo.checkPassword(textFieldValue)){
System.out.println("working");
notebook.setVisible(true);
//dispose();
}
}
};
JPanel panel = new JPanel();
textField.setBounds(230, 85, 100, 15);
contentPane.add(textField);
contentPane.add(panel);
textField.setColumns(10);
textField.addActionListener(action);
}
}
The password class,
package notebook;
public class security {
private String password = "kitten";
protected boolean checkPassword(String x){
if(x.length()<15 && x.equals(password)) return true;
return false;
}
}
The JTabbedPane class,
package notebook;
import javax.swing.JTabbedPane;
import javax.swing.JEditorPane;
import javax.swing.JList;
import javax.swing.JButton;
public class nbTab<E> extends JTabbedPane {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Create the panel.
*/
public nbTab() {
JEditorPane editorPane = new JEditorPane();
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(480, 345, 40, 30);
editorPane.add(btnNewButton);
editorPane.setBounds(80, 45, 400, 300);
addTab("New tab", null, editorPane, null);
JList<? extends E> list = new JList();
addTab("New tab", null, list, null);
}
}
In my main class, on lines 76 - 82 (where the action event listner is located) I would like to have my current window close and a new window of notebook to open. I used dispose() to close the password window. Then I try to open the JTabbedPane with setVisible(), setSelectedComponent, and setSelectedIndex however I am either using them incorrectly or there must be some better way to do this because it is not working. Any advice is appreciated guys thanks for all help.
As already suggested by MadProgrammer and Frakcool, the CardLayout layout manager is an interesting option in your case. A nice introduction to several Layout Managers for Swing is available here: A Visual Guide to Layout Managers.
You can use the code below to get an idea of how it could work. I have made a few modifications to your main application class:
The main class now extends from JFrame (instead of JDialog).
A few more panels and layout managers are used.
In Java class names usually start with a capital letter, so I have renamed your classes to MainPage, NotebookTab, and Security.
Here is the modified MainPage class:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class MainPage extends JFrame {
private static final String LOGIN_PANEL_ID = "Login panel";
private static final String NOTEBOOK_ID = "Notebook tabbed pane";
private JPanel mainPanel;
private CardLayout cardLayout;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainPage frame = new MainPage();
frame.setResizable(false);
Image icon = new BufferedImage(1, 1,
BufferedImage.TYPE_INT_ARGB_PRE);
frame.setIconImage(icon);
frame.setTitle("Notebook");
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws IOException
*/
public MainPage() throws IOException {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setBounds(100, 100, 560, 390);
cardLayout = new CardLayout();
mainPanel = new JPanel(cardLayout);
mainPanel.add(createLoginPanel(), LOGIN_PANEL_ID);
mainPanel.add(new NotebookTab(), NOTEBOOK_ID);
getContentPane().add(mainPanel);
}
private JPanel createLoginPanel() throws IOException {
JPanel loginPanel = new JPanel(new BorderLayout());
JPanel passwordPanel = new JPanel();
passwordPanel.setLayout(new BoxLayout(passwordPanel, BoxLayout.PAGE_AXIS));
JLabel lblEnterPassword = new JLabel("Enter Password");
lblEnterPassword.setForeground(Color.LIGHT_GRAY);
lblEnterPassword.setBackground(Color.DARK_GRAY);
lblEnterPassword.setOpaque(true);
lblEnterPassword.setHorizontalAlignment(SwingConstants.CENTER);
lblEnterPassword.setMaximumSize(new Dimension(100, 16));
lblEnterPassword.setAlignmentX(Component.CENTER_ALIGNMENT);
JTextField textField = new JPasswordField(10);
textField.setMaximumSize(new Dimension(100, 16));
textField.setAlignmentX(Component.CENTER_ALIGNMENT);
passwordPanel.add(Box.createRigidArea(new Dimension(0, 42)));
passwordPanel.add(lblEnterPassword);
passwordPanel.add(Box.createRigidArea(new Dimension(0, 10)));
passwordPanel.add(textField);
loginPanel.add(passwordPanel, BorderLayout.NORTH);
Action loginAction = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if (new Security().checkPassword(textField.getText())) {
System.out.println("working");
cardLayout.show(mainPanel, NOTEBOOK_ID);
}
}
};
textField.addActionListener(loginAction);
String imagePath = "C:\\Users\\Gianmarco\\workspace\\" +
"notebook\\src\\notebook\\cool_cat.jpg";
BufferedImage bufferedImage = ImageIO.read(new File(imagePath));
JLabel imageLabel = new JLabel(new ImageIcon(bufferedImage));
loginPanel.add(imageLabel, BorderLayout.CENTER);
return loginPanel;
}
}

How set size of specified String to JTextField?

JTextField in JPanel which in turn in JDialog doesn't take specified size. I tried to use BoxLayout and FlowLayout, but still have not achieved the desired size. I.E. I measure the size of String example and set this size to width of JTextField inputCat, but inputCat doesn't take this size, then I call it. How correctly set size of specified String to JTextField? Here is my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.util.Calendar;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JDesktopPane;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DemoJDialog {
static private JInternalFrame internal;
public static void main(String[] args) {
new DemoJDialog();
}
public DemoJDialog() {
EventQueue.invokeLater(new Runnable() {
#SuppressWarnings({ "rawtypes", "unchecked" })
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
internal = new JInternalFrame("Example", true, true, false, true);
internal.setLayout(new BorderLayout());
internal.setVisible(true);
JDesktopPane dp = new JDesktopPane();
dp.add(internal);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(dp);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
JTextField inputCat = new JTextField();
String example = new String("Some very-very-very-"
+ "very-very-very-very-very-very long string (really long )");
int heightInputCat = inputCat.getSize().height;
FontMetrics FN = internal.getFontMetrics(internal.getFont());
int widthInputCat = SwingUtilities.computeStringWidth(FN, example);
inputCat.setSize(widthInputCat, heightInputCat);
String[] comboString = { "Telecast", "Radiocast" };
JComboBox comboBox = new JComboBox(comboString);
Calendar now = Calendar.getInstance();
SpinnerModel modelSpinner = new SpinnerDateModel(now.getTime(),
null, null, Calendar.MONTH);
final JSpinner spinner = new JSpinner(modelSpinner);
spinner.setEditor(new JSpinner.DefaultEditor(spinner));
JPanel listPane = new JPanel();
listPane.setLayout(new BoxLayout(listPane, BoxLayout.X_AXIS));
listPane.add(comboBox);
listPane.add(Box.createHorizontalStrut(10));
listPane.add(inputCat);
listPane.add(Box.createHorizontalStrut(10));
listPane.add(spinner);
Object[] array = {
new JLabel ("Enter a new category:"),
listPane
};
JOptionPane pane = new JOptionPane(array, JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = pane.createDialog(internal, "Enter a new category:");
dialog.setVisible(true);
}
});
}
}
This works just fine here:
import java.awt.EventQueue;
import java.util.Calendar;
import javax.swing.*;
public class DemoJDialog {
public static void main(String[] args) {
new DemoJDialog();
}
public DemoJDialog() {
EventQueue.invokeLater(new Runnable() {
#SuppressWarnings({"rawtypes", "unchecked"})
#Override
public void run() {
String example = new String("Some very-very-very-"
+ "very-very-very-very-very-very "
+ "long string (really long)");
// create a textfield the size of the string!
JTextField inputCat = new JTextField(example);
inputCat.setCaretPosition(0);
String[] comboString = {"Telecast", "Radiocast"};
JComboBox comboBox = new JComboBox(comboString);
Calendar now = Calendar.getInstance();
SpinnerModel modelSpinner = new SpinnerDateModel(now.getTime(),
null, null, Calendar.MONTH);
final JSpinner spinner = new JSpinner(modelSpinner);
spinner.setEditor(new JSpinner.DefaultEditor(spinner));
JPanel listPane = new JPanel();
listPane.setLayout(new BoxLayout(listPane, BoxLayout.X_AXIS));
listPane.add(comboBox);
listPane.add(Box.createHorizontalStrut(10));
listPane.add(inputCat);
listPane.add(Box.createHorizontalStrut(10));
listPane.add(spinner);
Object[] array = {
new JLabel("Enter a new category:"),
listPane
};
JOptionPane pane = new JOptionPane(array, JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = pane.createDialog(listPane, "Enter a new category:");
dialog.setVisible(true);
}
});
}
}
But JTextField is filled by the example String. And I need empty JTextField with this width
Just use constructor which specifies desired colums Count:
JTextField inputCat = new JTextField(example.length());

Getting a JOptionPane to appear after clicking button

I have to create a Library for lending Media Items. So far I have the GUI to look how it should, but now I've hit a brick wall with what to do next. When the user clicks the 'Add' button, two prompts should open asking the user for the Title and then the Format, but I have no clue what to do to achieve it. Any help would be great!
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
public class FinalView extends JFrame{
private JButton add;
private JButton checkOut;
private JButton checkIn;
private JButton delete;
private JScrollPane display;
private JList jlist;
Scanner input = new Scanner(System.in);
public FinalView(){
setTitle("My Library");
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//change later for save feature per printout
setLocationRelativeTo(null);
setLayout(new BorderLayout());
JPanel buttonPanel = new JPanel();
add(buttonPanel, BorderLayout.SOUTH);
buttonPanel.setLayout(new GridLayout(1, 4, 8, 8));
add = new JButton("Add");
checkOut = new JButton("Check Out");
checkIn = new JButton("Check In");
delete = new JButton("Delete");
buttonPanel.add(add);
buttonPanel.add(checkOut);
buttonPanel.add(checkIn);
buttonPanel.add(delete);
String[] movie = {"Star Wars", "StarTrek"};
Library call = new Library();
jlist = new JList(movie);
jlist.setVisibleRowCount(4);
jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
add(new JScrollPane(jlist));
setVisible(true);
ActionListener listener = null;
add.addActionListener(listener);
}
public void actionPerformed(ActionEvent e) {
JOptionPane.showInputDialog("Title:");
String title = input.nextLine();
JOptionPane.showInputDialog("Format:");
String format = input.nextLine();
addNewItem(title, format);
}
private void addNewItem(String title, String format) {
MediaItem lib = new MediaItem(title, format);
// TODO Auto-generated method stub
}
public static void main(String[] args) {
new FinalView();
}
}

JScrollPane displays the content using only the horizontal scroll bar

I want to display a list of strings in a window and i tried to use a JPanel surounded by JScrollPane because the size of the strings list is unknown. The problem is that the window is displaying the text Horizontally and i want to be displayed line after line. How to fix this? This is the code i've written so far.
package interface_classes;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
public class ErrorMessageW {
private JFrame errorMessageW;
private ArrayList<String> errors;
private JPanel panel;
private JScrollPane scrollPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
final ArrayList<String> err = new ArrayList<>();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ErrorMessageW window = new ErrorMessageW(err);
window.errorMessageW.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ErrorMessageW(ArrayList<String> err) {
errors = err;
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
errorMessageW = new JFrame();
errorMessageW.setTitle("Unfilled forms");
errorMessageW.setBounds(100, 100, 367, 300);
errorMessageW.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnOk = new JButton("OK");
btnOk.setBounds(239, 208, 89, 23);
btnOk.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
errorMessageW.dispose();
}
});
errorMessageW.getContentPane().setLayout(null);
errorMessageW.getContentPane().add(btnOk);
scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBounds(10, 10, 330, 175);
errorMessageW.getContentPane().add(scrollPane);
panel = new JPanel();
for(String s : errors){
JTextArea text = new JTextArea(1,20);
text.setText(s);
text.setFont(new Font("Verdana",1,10));
text.setForeground(Color.RED);
panel.add(text);
}
scrollPane.setViewportView(panel);
}
public JFrame getErrorMessageW() {
return errorMessageW;
}
public void setErrorMessageW(JFrame errorMessageW) {
this.errorMessageW = errorMessageW;
}
}
This is what i get
This is what i want, but using the JScrollPane:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.ArrayList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class ErrorMessageW {
private JFrame errorMessageW;
private ArrayList<String> errors;
private JPanel panel;
private JScrollPane scrollPane;
private JTextArea errorMessage = new JTextArea(3, 30);
/**
* Launch the application.
*/
public static void main(String[] args) {
final ArrayList<String> err = new ArrayList<String>();
err.add("Short String");
err.add("A very very very very very very very very very very very "
+ "very very very very very very very very very very very "
+ "very very very very very very very very long String");
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ErrorMessageW window = new ErrorMessageW(err);
window.errorMessageW.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ErrorMessageW(ArrayList<String> err) {
errors = err;
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
errorMessageW = new JFrame();
JPanel contentPane = new JPanel(new BorderLayout(5, 15));
contentPane.setBorder(new EmptyBorder(10, 10, 10, 10));
errorMessage.setLineWrap(true);
errorMessage.setWrapStyleWord(true);
JScrollPane jsp = new JScrollPane(
errorMessage,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
);
contentPane.add(jsp, BorderLayout.PAGE_START);
errorMessageW.add(contentPane);
errorMessageW.setTitle("Unfilled forms");
errorMessageW.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JButton btnOk = new JButton("OK");
btnOk.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
errorMessageW.dispose();
}
});
JPanel btnConstrain = new JPanel(new FlowLayout(FlowLayout.TRAILING));
btnConstrain.add(btnOk);
contentPane.add(btnConstrain, BorderLayout.PAGE_END);
scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
contentPane.add(scrollPane, BorderLayout.CENTER);
DefaultListModel<String> listModel = new DefaultListModel<String>();
for (String s : errors) {
listModel.addElement(s);
}
final JList<String> errorList = new JList<String>(listModel);
Dimension preferredSize = new Dimension(errorMessage.getPreferredSize().width,200);
errorList.setPreferredSize(preferredSize);
ListSelectionListener errorSelect = new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
errorMessage.setText(errorList.getSelectedValue());
}
};
errorList.addListSelectionListener(errorSelect);
scrollPane.setViewportView(errorList);
errorMessageW.pack();
}
public JFrame getErrorMessageW() {
return errorMessageW;
}
public void setErrorMessageW(JFrame errorMessageW) {
this.errorMessageW = errorMessageW;
}
}
First of all, you could try, instead of creating multiple instances of JTextArea, using only one and appending each error to it like this:
JTextArea text = new JTextArea(1, 20);
text.setFont(new Font("Verdana",1,10));
text.setForeground(Color.RED);
for(String s : errors) {
text.append(s + "\n");
}
panel.add(text);
However, if you do need to create more than one JTextArea, you can use a BoxLayout like this:
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
You just need to write a function that adds a new line character as an element of your ArrayList after every other element in your ArrayList of errors. Below i did a test program that shows how that can be done. I also checked the oputput. Just paste the code and understand the working of code. All the best!
import java.util.ArrayList;
public class TestingArraylist {
static ArrayList<String> errors = new ArrayList<String>();
static final String[] warnings = new String[]{"Error 0 occured","Error 1 occured","Error 2 occured","Error 3 occured","Error 4 occured"};;
public static void addNewLineToArrayList(String[] elementofarraylist){
for(int i =0;i<elementofarraylist.length;i++){
errors.add(elementofarraylist[i]);
errors.add("\n"); //this is what you need to do!
}
}
public static void main(String[] args) {
addNewLineToArrayList(warnings);
//checking below if our work has really succeded or not!!
for(int j =0;j<errors.size();j++){
System.out.print(errors.get(j));
}
}
}

Applet not appearing full

I just created an applet
public class HomeApplet extends JApplet {
private static final long serialVersionUID = -7650916407386219367L;
//Called when this applet is loaded into the browser.
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
// setSize(400, 400);
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
private void createGUI() {
RconSection rconSection = new RconSection();
rconSection.setOpaque(true);
// CommandArea commandArea = new CommandArea();
// commandArea.setOpaque(true);
JTabbedPane tabbedPane = new JTabbedPane();
// tabbedPane.setSize(400, 400);
tabbedPane.addTab("Rcon Details", rconSection);
// tabbedPane.addTab("Commad Area", commandArea);
setContentPane(tabbedPane);
}
}
where the fisrt tab is:
package com.rcon;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.Bean.RconBean;
import com.util.Utility;
public class RconSection extends JPanel implements ActionListener{
/**
*
*/
private static final long serialVersionUID = -9021500288377975786L;
private static String TEST_COMMAND = "test";
private static String CLEAR_COMMAND = "clear";
private static JTextField ipText = new JTextField();
private static JTextField portText = new JTextField();
private static JTextField rPassText = new JTextField();
// private DynamicTree treePanel;
public RconSection() {
// super(new BorderLayout());
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
testButton.addActionListener(this);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
clearButton.addActionListener(this);
JPanel panel = new JPanel(new GridLayout(3,2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel panel1 = new JPanel(new GridLayout(1,3));
panel1.add(testButton);
panel1.add(clearButton);
add(panel);
add(panel1);
// add(panel, BorderLayout.NORTH);
// add(panel1, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getActionCommand().equals(TEST_COMMAND)){
String ip = ipText.getText().trim();
if(!Utility.checkIp(ip)){
ipText.requestFocusInWindow();
ipText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Ip!!!");
return;
}
String port = portText.getText().trim();
if(port.equals("") || !Utility.isIntNumber(port)){
portText.requestFocusInWindow();
portText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Port!!!");
return;
}
String pass = rPassText.getText().trim();
if(pass.equals("")){
rPassText.requestFocusInWindow();
rPassText.selectAll();
JOptionPane.showMessageDialog(this,"Enter Rcon Password!!!");
return;
}
RconBean rBean = RconBean.getBean();
rBean.setIp(ip);
rBean.setPassword(pass);
rBean.setPort(Integer.parseInt(port));
if(!Utility.testConnection()){
rPassText.requestFocusInWindow();
rPassText.selectAll();
JOptionPane.showMessageDialog(this,"Invalid Rcon!!!");
return;
}else{
JOptionPane.showMessageDialog(this,"Correct Rcon!!!");
return;
}
}
else if(arg0.getActionCommand().equals(CLEAR_COMMAND)){
ipText.setText("");
portText.setText("");
rPassText.setText("");
}
}
}
it appears as
is has cropped some data how to display it full and make the applet non resizable as well. i tried setSize(400, 400); but it didnt helped the inner area remains the same and outer boundaries increases
Here's another variation on your layout. Using #Andrew's tag-in-source method, it's easy to test from the command line:
$ /usr/bin/appletviewer HomeApplet.java
// <applet code='HomeApplet' width='400' height='200'></applet>
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class HomeApplet extends JApplet {
#Override
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
createGUI();
}
});
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
private void createGUI() {
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Rcon1", new RconSection());
tabbedPane.addTab("Rcon2", new RconSection());
this.add(tabbedPane);
}
private static class RconSection extends JPanel implements ActionListener {
private static final String TEST_COMMAND = "test";
private static final String CLEAR_COMMAND = "clear";
private JTextField ipText = new JTextField();
private JTextField portText = new JTextField();
private JTextField rPassText = new JTextField();
public RconSection() {
super(new BorderLayout());
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
testButton.addActionListener(this);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
clearButton.addActionListener(this);
JPanel panel = new JPanel(new GridLayout(3, 2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel buttons = new JPanel(); // default FlowLayout
buttons.add(testButton);
buttons.add(clearButton);
add(panel, BorderLayout.NORTH);
add(buttons, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e);
}
}
}
As I mentioned in a comment, this question is really about how to layout components in a container. This example presumes you wish to add the extra space to the text fields and labels. The size of the applet is set in the HTML.
200x130 200x150
/*
<applet
code='FixedSizeLayout'
width='200'
height='150'>
</applet>
*/
import java.awt.*;
import javax.swing.*;
public class FixedSizeLayout extends JApplet {
public void init() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
initGui();
}
});
}
private void initGui() {
JTabbedPane tb = new JTabbedPane();
tb.addTab("Rcon Details", new RconSection());
setContentPane(tb);
validate();
}
}
class RconSection extends JPanel {
private static String TEST_COMMAND = "test";
private static String CLEAR_COMMAND = "clear";
private static JTextField ipText = new JTextField();
private static JTextField portText = new JTextField();
private static JTextField rPassText = new JTextField();
public RconSection() {
super(new BorderLayout(3,3));
JLabel ip = new JLabel("IP");
JLabel port = new JLabel("Port");
JLabel rPass = new JLabel("Rcon Password");
JButton testButton = new JButton("Test");
testButton.setActionCommand(TEST_COMMAND);
JButton clearButton = new JButton("Clear");
clearButton.setActionCommand(CLEAR_COMMAND);
JPanel panel = new JPanel(new GridLayout(3,2));
panel.add(ip);
panel.add(ipText);
panel.add(port);
panel.add(portText);
panel.add(rPass);
panel.add(rPassText);
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER,5,5));
panel1.add(testButton);
panel1.add(clearButton);
add(panel, BorderLayout.CENTER);
add(panel1, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Container c = new RconSection();
JOptionPane.showMessageDialog(null, c);
}
});
}
}
Size of applet viewer does not depend on your code.
JApplet is not window, so in java code you can't write japplet dimensions. You have to change run settings. I don't know where exactly are in other ide's, but in Eclipse you can change dimensions in Project Properties -> Run/Debug settings -> click on your launch configurations file (for me there were only 1 - main class) -> edit -> Parameters. There you can choose width and height for your applet. save changes and you are good to go

Categories

Resources