public static void main(String[] args) throws IOException {
//cevir("ornek3.txt");
JFrame frame=new JFrame("Print");
JPanel input=new JPanel();
JPanel output=new JPanel(); output.setBackground(Color.black);
final JTextArea ita = new JTextArea(30, 40);
JScrollPane ijp = new JScrollPane(ita);
JTextArea ota = new JTextArea(30, 40);
JScrollPane ojp = new JScrollPane(ota);
JButton buton=new JButton("Print");
frame.setLayout(new FlowLayout());
buton.setSize(50, 20);
input.setBounds(0,0,500, 500);
output.setBounds(500, 0, 500, 450);
frame.setBounds(100, 50, 1000, 500);
input.add(ijp, BorderLayout.CENTER);
output.add(ojp, BorderLayout.EAST);
input.add(buton, BorderLayout.SOUTH);
frame.add(input);
frame.add(output);
buton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(String line: ita.getText().split("\\n"));
System.out.println(line);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
This is my code and i want to get the text that i wrote while the program running and print it to the console. Is it possible with JtextArea. This code prints null when i clicked the button to the console even if i write something to the textarea.
You have use the JtextArea#append method.
public void actionPerformed(ActionEvent e) {
for(String line: ita.getText().split("\\n"))
ota.append(line);
}
Also variables used inside the methods inner class should be final, so make ota as final
final JTextArea ota = new JTextArea(30, 40);
Related
I have this code bellow that is suppose to display some text but it don't and I can't find the reason why.
public class TestMLD extends JPanel{
TestMLD(){
init();
}
private void init() {
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
Font font = new Font(Font.MONOSPACED, Font.ITALIC, 100);
JLabel helloLabel = new JLabel("Hello World !");
helloLabel.setFont(font);
helloLabel.setForeground(Color.BLUE);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new TestMLD());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
new TestMLD();
}
}
Thanks in advance
The issue here is that you never actually add the JLabel helloLabel to your JPanel / TestMLD.
To do so, add this line of code at the end of your init() method:
add(helloLabel);
You also never actually set the layout you created to your panel
setLayout(flow);
Also, the second time you create a new TestMLD() object is redundant. You can omit that.
All together, the updated code should look something like this:
public class TestMLD extends JPanel {
TestMLD() {
init();
}
private void init() {
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
setLayout(flow);
Font font = new Font(Font.MONOSPACED, Font.ITALIC, 100);
JLabel helloLabel = new JLabel("Hello World !");
helloLabel.setFont(font);
helloLabel.setForeground(Color.BLUE);
add(helloLabel);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new TestMLD());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
I created a GUI using java swing and in a specific situation, the JButton is unresponsive and I have to click it twice. On the click, it takes the info in the textArea and sends it to a TextParser class to be parsed. If I type more stuff in the area after, and click the evaluateButton, it doesn't respond and I have to click it again to work. Does anyone know if this is a known bug or how I can fix this?
The code for the class is as follows.
/**
* Add the components to the GUI.
* #param pane - the pane for the GUI
*/
public static void addComponentsToPane(Container pane) {
pane.setLayout(new BorderLayout());
JPanel instructionsPanel = new JPanel();
JLabel instructions = new JLabel("Enter the email text below");
instructionsPanel.setBackground(Color.LIGHT_GRAY);
instructionsPanel.add(instructions);
pane.add(instructionsPanel, BorderLayout.NORTH);
JPanel textAreaPanel = new JPanel();
textAreaPanel.setBackground(Color.LIGHT_GRAY);
final JTextArea textArea = new JTextArea();
textArea.setBackground(Color.WHITE);
textArea.setMinimumSize(new Dimension(400,350));
textArea.setMaximumSize(new Dimension(400,350));
textArea.setPreferredSize(new Dimension(400,350));
textArea.setLineWrap(true);
Border border = BorderFactory.createLineBorder(Color.BLACK);
textArea.setBorder(border);
textArea.setMinimumSize(new Dimension(500, 200));
textArea.setFont(new Font("Serif", Font.PLAIN, 16));
textAreaPanel.add(textArea);
pane.add(textAreaPanel, BorderLayout.CENTER);
JPanel scoringPanel = new JPanel();
JButton evaluateButton = new JButton("Evaluate Email");
final JLabel scoreLabel = new JLabel("");
JButton uploadFileBtn = new JButton("Upload File");
JButton importTermsBtn = new JButton("Import Terms");
scoringPanel.add(evaluateButton);
scoringPanel.add(uploadFileBtn);
scoringPanel.add(importTermsBtn);
scoringPanel.add(scoreLabel);
pane.add(scoringPanel, BorderLayout.SOUTH);
evaluateButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
String email = textArea.getText();
TextParser textParser = new TextParser(email);
double score = textParser.parse();
scoreLabel.setText(score+"");
} catch (Exception ex) {
System.out.println(ex);
}
}
});
uploadFileBtn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
scoreLabel.setText("Feature not yet available.");
}
});
importTermsBtn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
DatabaseInput d = new DatabaseInput();
d.main(null);
}
});
}
/**
* Create the GUI and show it.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("EmailGUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setLocationRelativeTo(null);
frame.setPreferredSize(new Dimension(500,500));
frame.setTitle("Email Text Input");
frame.setResizable(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(screenSize.width, screenSize.height);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
My main method just calls createAndShowGUI(). I am new to StackOverflow so if I need to give more or less information in my post please let me know!
As Reimeus and Jason C said in the comments, I should have been using ActionListener which works perfectly.
I have a text file with a list of names in. I am trying to create a GUI and then read in the text from the file into the GUI and display it in a textfield/label/anything. I can create the GUI and read in the code, but do not know how to display the read in text in the GUI. Below is my code. When I run it displays the GUI but does not display the read in text.
public class ASSIGNMENT {
private JLabel lbl1;
private JTextField txt1;
private JPanel panel;
private JFrame frame;
public ASSIGNMENT(){
createGUI();
addLabels();
frame.add(panel);
frame.setVisible(true);
}
public void createGUI(){
frame = new JFrame();
frame.setTitle("Books");
frame.setSize(730, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(null);
panel.setBounds(10, 10, 10, 10);
panel.setBorder(BorderFactory.createLineBorder (Color.decode("#1854A2"), 2));
frame.add(panel);
}
public void addLabels(){
lbl1 = new JLabel(" ");
lbl1.setBounds(700, 450, 120, 25);
lbl1.setForeground(Color.white);
panel.add(lbl1);
}
public void books() throws IOException{
String result = "books2.txt";
String line;
LineNumberReader lnr = new LineNumberReader(new FileReader(new File("books2.txt")));
while((line = lnr.readLine()) != null){
result += line;
}
JLabel label1 = new JLabel(result);
panel.add(label1);
}
public static void main(String[] args) throws Exception{
new ASSIGNMENT();
}
}
Hello here is your code working. You basically need to set a Layout Manager properly. You have two options. Option one is to have NULL and layout manager. In this case you need to position all your components with setBounds().
Option number two is to use a more user friendly layout manager that does not require that like GridBagLayout. Bellow you can see your code corrected for GridBagLayout. I repeat having null as manager is possible, but you need to position your elements with coordinates with the help of setBounds
public class ASSIGNMENT3 {
private JLabel lbl1;
private JTextField txt1;
private JPanel panel;
private JFrame frame;
public ASSIGNMENT3() throws IOException{
createGUI();
addLabels();
books();
frame.add(panel);
frame.setVisible(true);
}
public void createGUI(){
frame = new JFrame();
frame.setTitle("Books");
frame.setSize(730, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setBounds(10, 10, 10, 10);
panel.setBorder(BorderFactory.createLineBorder (Color.decode("#1854A2"), 2));
frame.add(panel);
}
public void addLabels(){
lbl1 = new JLabel("Labe 1 ");
lbl1.setBounds(700, 450, 120, 25);
lbl1.setForeground(Color.white);
panel.add(lbl1);
}
public void books() throws IOException{
String result = "books2.txt";
String line;
// LineNumberReader lnr = new LineNumberReader(new FileReader(new File("books2.txt")));
// while((line = lnr.readLine()) != null){
// result += line;
// }
//
txt1 = new JTextField(20);
txt1.setText(result);
JLabel label1 = new JLabel(result);
panel.add(label1);
panel.add(txt1);
}
public static void main(String[] args) throws Exception{
new ASSIGNMENT3();
}
}
i have written a code to create a sms form and i want to add the ability to show error message when the text area is empty. i put JOptionpane in my code but diologe dose not appear when i run the program! here is my code
private void initialize() {
frame = new JFrame("?????? ? ????? ?????");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JOptionPane optionPane = new JOptionPane();
JPanel middlePanel = new JPanel();
txtPath = new JTextField();
txtPath.setBounds(150, 10, 200, 21);
frame.getContentPane().add(txtPath);
txtPath.setColumns(10);
txtPath2 = new JTextField();
txtPath2.setBounds(150, 65, 200, 21);
frame.getContentPane().add(txtPath2);
txtPath2.setColumns(20);
JButton btnBrowse = new JButton("?????");
btnBrowse.setBounds(5, 10, 87, 23);
frame.getContentPane().add(btnBrowse);
final JButton ok = new JButton("?????");
ok.setBounds(250, 230, 87, 23);
frame.getContentPane().add(ok);
JButton cancel = new JButton("???");
cancel.setBounds(110, 230, 87, 23);
frame.getContentPane().add(cancel);
final JTextArea textarea = new JTextArea();
textarea.setBounds(50, 100, 300, 100);
frame.getContentPane().add(textarea);
textarea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JProgressBar progressBar = new JProgressBar(0, 100);
progressBar.setSize(10, 1);
progressBar.setForeground(Color.blue);
frame.getContentPane().add(progressBar);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
// For Directory
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
// For File
//fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
int rVal = fileChooser.showOpenDialog(null);
if (rVal == JFileChooser.APPROVE_OPTION) {
txtPath.setText(fileChooser.getSelectedFile().toString());
fileChooser.setFileFilter(new FileNameExtensionFilter("Text Files", "txt", "rtf"));
}
}
});
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textarea.getLineCount()>=1)
{
test t=new test();
ReadTextFile readTextFile=new ReadTextFile();
t.testMethode(txtPath2.getText(), textarea.getText(),readTextFile.readFile(txtPath.getText()) );
}
else
JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
}
});
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
}
}
GUI's are event driven environments. Something happens, you respond to it.
You if-else statement will never be false because the time it is executed, the textarea will be blank (have no text).
You need to respond to some event (ie send for example) at which time you would make your check to valid the form.
Take a look at Creating a GUI with Swing for more details
Updated with example
public class Example {
public static void main(String[] args) {
new Example();
}
public Example() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private final JTextArea msg;
public TestPane() {
msg = new JTextArea(10, 20);
JButton send = new JButton("Send");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(new JScrollPane(msg), gbc);
add(send, gbc);
send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (msg.getText().trim().length() > 0) {
// Send msg
} else {
JOptionPane.showMessageDialog(TestPane.this, "Please write something (nice)", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
}
}
}
Updated based on changes to the answer by the OP
if(textarea.getLineCount()>=1) will always return true. Try using msg.getText().trim().length() > 0 instead to determine the JTextArea contains text or not...
Updated
mKobel has made an excellent point. You really should avoid using null layouts. You don't control what font size or screen DPI/resolution your application might need to work on. Layout managers take out the guess work.
You should try checking out A visual guide to layout managers and Using layout managers for more details
I am trying to add two buttons below the JTextArea using the Eclipse WindowBuilder, but I can't. I tried to change the layout, but I couldn't find a way to add buttons where I want and to re-size the JTextArea in an easy way.
public TestScrollPane03() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JTextArea textArea = new JTextArea(100, 50);
JScrollPane scrollPane = new JScrollPane(textArea);
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(scrollPane);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
How would I go about adding buttons below my original textArea?
You need to have two panels, one for your textArea, and one for your input (in this case buttons). I think something like this is what you are looking for:
public class Test
{
public static void createFrame()
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setOpaque(true);
JTextArea textArea = new JTextArea(15, 50);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
textArea.setFont(Font.getFont(Font.SANS_SERIF));
JScrollPane scroller = new JScrollPane(textArea);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
JPanel inputpanel = new JPanel();
inputpanel.setLayout(new FlowLayout());
JTextField input = new JTextField(20);
JButton button = new JButton("Enter");
DefaultCaret caret = (DefaultCaret) textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
panel.add(scroller);
inputpanel.add(input);
inputpanel.add(button);
panel.add(inputpanel);
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setResizable(false);
input.requestFocus();
}
});
}
public static void main(String... args)
{
createFrame();
}
}
If you want your frame to look more like those of the OS you are running on, you can add .setLookAndFeel() before you make the frame visible:
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
What adding the UIManager looks like (notably a bit smaller):