I want to create a Jtextarea in the first half of the below panel under tab2. I want to iterate and write the contents present in the test.txt file into this newly created Jtext area. The text.txt file is present in the location (C:\test.txt). Can someone suggest me how to achieve this for the below code.(Note: The below code is a JPane with three tabs tab1,tab2,tab3) and the tab 2 has been splited into two halves.)
I am new to the Jtextarea concept so it will be nice from understanding viewpoint if anyone can provide some suggestion code for my below code:
text.txt contents in my local disk is as below
username:test1
Password:test1
DataBasename: testDB
CODE:
import javax.swing.*;
import java.awt.*;
public class SplitPaneExp {
public static void main(String[] args){
Runnable r = new Runnable() {
public void run() {
JFrame frame = new JFrame("WELCOME");
// A better close operation..
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JTabbedPane tab = new JTabbedPane();
frame.add(tab, BorderLayout.CENTER);
JButton button = new JButton("1");
tab.add("tab1", button);
// this GridLayout will create a single row of components,
// with equal space for each component
JPanel tab2Panel = new JPanel(new GridLayout(0,1));
button = new JButton("2");
tab2Panel.add(button);
tab2Panel.add(new JButton("Second window"));
// add the panel containing two buttons to the tab
tab.add("tab2", tab2Panel);
button = new JButton("3");
tab.add("tab3", button);
// a better sizing method..
//frame.setSize(400,400);
frame.pack();
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class SplitPaneExp {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
JFrame frame = new JFrame("WELCOME");
// A better close operation..
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JTabbedPane tab = new JTabbedPane();
frame.add(tab, BorderLayout.CENTER);
JButton button = new JButton("1");
tab.add("tab1", button);
// this GridLayout will create a single row of components,
// with equal space for each component
JPanel tab2Panel = new JPanel(new GridLayout(0, 1));
// button = new JButton("2");
//Hi, I added a few things here!
String output = "";
try {
BufferedReader br = new BufferedReader(new FileReader(new File("C:\test.txt")));
String line = br.readLine();
while(line != null) {
if(output.length() > 0) {
output = output + "\n";
}
output = output + line;
line = br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
JTextArea jta = new JTextArea(output);
tab2Panel.add(jta);
// Done.
// tab2Panel.add(button);
tab2Panel.add(new JButton("Second window"));
// add the panel containing two buttons to the tab
tab.add("tab2", tab2Panel);
button = new JButton("3");
tab.add("tab3", button);
// a better sizing method..
//frame.setSize(400,400);
frame.pack();
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
Hope it helps.
Related
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class DiceFrame extends JFrame{
ImageIcon[] dice_im = new ImageIcon[7];
String score="start";
JPanel mainPanel= new JPanel();
JPanel scorePanel=new JPanel();
JPanel buttonPanel =new JPanel();
JLabel picLabel = new JLabel();
JTextArea scorefield = new JTextArea();
JButton roll= new JButton("roll the dice");
JButton save = new JButton("save");
ActionListener action;
ActionListener output;
public DiceFrame(){
super();
setSize(600, 600);
setTitle("Dice Program");
loadImage();
getContentPane().add(mainPanel, BorderLayout.CENTER);
getContentPane().add(scorePanel, BorderLayout.EAST);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
buttonPanel.add(save);
buttonPanel.add(roll);
mainPanel.add(picLabel);
picLabel.setIcon(dice_im[0]);
scorePanel.add(scorefield);
scorefield.setText(score);
action = new DiceActionListener();
roll.addActionListener(action);
}
private void loadImage(){
dice_im [0]= new ImageIcon("1.jpg");
dice_im[1] = new ImageIcon("2.jpg");
dice_im[2] = new ImageIcon("3.JPG");
dice_im[3] = new ImageIcon("4.JPG");
dice_im[4] = new ImageIcon("5.JPG");
dice_im[5] = new ImageIcon("6.JPG");
}
public static void main(String args[]){
DiceFrame frame = new DiceFrame();
frame.setDefaultLookAndFeelDecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
class DiceActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Random rg = new Random();
int k = rg.nextInt(6) + 1;
picLabel.setIcon(dice_im[k]);
}
}
class SaveActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) { //NEW code
String out_file_name = "dice_score.txt";
try {
File outputfile = new File(out_file_name);
PrintStream out = new PrintStream(
new FileOutputStream(outputfile));
out.println(score);
out.flush();`
out.close();
} catch (IOException y) {
System.out.println("IO problem.");
}
}
}
}
How can i make save button work by writing this code?
Whenever i run it roll button works but the save button doesn't work?
this is a program for the rolling the dice but i need to make the save button work, Can anyone please help with that?
how can i link dice_score.txt file to this program?
Action listener is not added to Save Button.
save.addActionListener(new SaveActionListener());
Add this at the end of DiceFrame():
save.addActionListener(new SaveActionListener());
See
action = new DiceActionListener();
roll.addActionListener(action);
well you have to follow this pattern and do
SaveActionListener action2 = new SaveActionListener ();
save.addActionListener(action2);
Although in reality it is not necessary to create a named instance and you can simply do
save.addActionListener (new SaveActionListener ());
hi i am trying to make java desktop application where i am trying to make jbutton bottom left i did following code i dont know where i am wrong my code is note working
here is my code
import java.awt.*;
import java.awt.event.*;
import javax.imageio.ImageIO;
import javax.swing.*;
new complete code
public class ApplicationCloseExample
{
private JButton[] buttons;
private void displayGUI()
{
final JFrame frame = new JFrame("Application Close Example");
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
for (int i = 5; i < 8; i++) {
buttons[i] = new JButton(Integer.toString(i));
bottomPanel.add(buttons[i]);
}
// JButton button = new JButton("Comment");
// bottomPanel.add(button);
// frame.getContentPane().add(contentPane, BorderLayout.CENTER);
frame.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ApplicationCloseExample().displayGUI();
}
});
}
}
How can i achieve this
I'm going to assume the null pointer exception is something to do with your buttons array. Check that you have initialised it properly.
private JButton[] buttons = new JButton[8];
I copied your code into a test project and ran it after some modifications:
public static void main(String[] args) {
final JFrame frame = new JFrame("Application Close Example");
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
for (int i = 5; i < 8; i++) {
buttons[i] = new JButton(Integer.toString(i));
bottomPanel.add(buttons[i]);
}
frame.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
This produced a frame with three buttons aligned to the bottom left of the window.
There is an elegant solution that I'll give you but maybe it serves. Use WindowsBuilder and adds several buttons and then you look like is placing code. So make yourself an idea of the pattern that follows a setLayout with Flow.
I am working on a project for my college course. I was just wondering if anyone knew how to add a scrollBar to a JTextArea. At present I have the GUI laid out correctly, the only thing missing is the scroll bar.
This is what the GUI looks like. As you can see on the second TextArea I would like to add the Scrollbar.
This is my code where I create the pane. But nothing seems to happen... t2 is the JTextArea I want to add it to.
scroll = new JScrollPane(t2);
scroll.setBounds(10,60,780,500);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
Any help would be great, thanks!
The Scroll Bar comes when your text goes beyond the bounds of your view area. Don't use Absolute Positioning, for such a small talk at hand, always prefer Layout Managers, do read the first para of the first link, to know the advantage of using a Layout Manager.
What you simply need to do is use this thingy :
JTextArea msgArea = new JTextArea(10, 10);
msgArea.setWrapStyleWord(true);
msgArea.setLineWrap(true);
JScrollPane msgScroller = new JScrollPane();
msgScroller.setBorder(
BorderFactory.createTitledBorder("Messages"));
msgScroller.setViewportView(msgArea);
panelObject.add(msgScroller);
Here is a small program for your understanding :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextAreaScroller
{
private JTextArea msgArea;
private JScrollPane msgScroller;
private JTextArea logArea;
private JScrollPane logScroller;
private JButton sendButton;
private JButton terminateButton;
private Timer timer;
private int counter = 0;
private String[] messages = {
"Hello there\n",
"How you doing ?\n",
"This is a very long text that might won't fit in a single line :-)\n",
"Okay just to occupy more space, it's another line.\n",
"Don't read too much of the messages, instead work on the solution.\n",
"Byee byee :-)\n",
"Cheers\n"
};
private ActionListener timerAction = new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
if (counter < messages.length)
msgArea.append(messages[counter++]);
else
counter = 0;
}
};
private void displayGUI()
{
JFrame frame = new JFrame("Chat Messenger Dummy");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(0, 1, 5, 5));
logArea = new JTextArea(10, 10);
logArea.setWrapStyleWord(true);
logArea.setLineWrap(true);
logScroller = new JScrollPane();
logScroller.setBorder(
BorderFactory.createTitledBorder("Chat Log"));
logScroller.setViewportView(logArea);
msgArea = new JTextArea(10, 10);
msgArea.setWrapStyleWord(true);
msgArea.setLineWrap(true);
msgScroller = new JScrollPane();
msgScroller.setBorder(
BorderFactory.createTitledBorder("Messages"));
msgScroller.setViewportView(msgArea);
centerPanel.add(logScroller);
centerPanel.add(msgScroller);
JPanel bottomPanel = new JPanel();
terminateButton = new JButton("Terminate Session");
terminateButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
if (timer.isRunning())
timer.stop();
else
timer.start();
}
});
sendButton = new JButton("Send");
bottomPanel.add(terminateButton);
bottomPanel.add(sendButton);
contentPane.add(centerPanel, BorderLayout.CENTER);
contentPane.add(bottomPanel, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
timer = new Timer(1000, timerAction);
timer.start();
}
public static void main(String... args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new JTextAreaScroller().displayGUI();
}
});
}
}
Here is the outcome of the same :
The scroll bar by default will only be shown when the content overfills the available viewable area
You can change this via the JScrollPane#setVerticalScrollBarPolicy method, passing it ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS
I have the following class which is a simple gui, and I would like to make it an applet so it can be displayed in the browser. I know how to embed the code into an html page(got that done)... but how can make my class an applet? Also, I assuming I don't need a web server just to display the applet in my browser...
package tester1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class PanelTest implements ActionListener {
JFrame frame;
JLabel inputLabel;
JLabel outputLabel;
JLabel outputHidden;
JTextField inputText;
JButton button;
JButton clear;
JButton about;
public PanelTest() {
frame = new JFrame("User Name");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3, 2, 10, 10));
//creating first row
JPanel row1 = new JPanel();
inputLabel = new JLabel("Your Name");
inputText = new JTextField(15);
// FlowLayout flow1 = new FlowLayout(FlowLayout.CENTER, 10, 10);
// row1.setLayout(flow1);
row1.add(inputLabel);
row1.add(inputText);
frame.add(row1);
//creating second row
JPanel row2 = new JPanel();
button = new JButton("Display");
clear = new JButton("Clear");
about = new JButton("About");
button.addActionListener(this);
clear.addActionListener(this);
about.addActionListener(new displayAbout());
row2.add(button);
row2.add(clear);
row2.add(about);
frame.add(row2);
//creating third row
JPanel row3 = new JPanel();
outputLabel = new JLabel("Output:", JLabel.LEFT);
outputHidden = new JLabel("", JLabel.RIGHT);
// FlowLayout flow2 = new FlowLayout(FlowLayout.CENTER, 10, 10);
// row3.setLayout(flow2);
row3.add(outputLabel);
row3.add(outputHidden);
frame.add(row3);
frame.pack();
frame.setVisible(true);
}
//same method listen for two different events
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("Display")) {
outputHidden.setText(inputText.getText());
}
if(command.equals("Clear")) {
outputHidden.setText("");
inputText.setText("");
}
}
//another way to listen for events
class displayAbout implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Username 1.1 \n by Jorge L. Vazquez");
}
}
public static void main(String[] args) {
PanelTest frameTest = new PanelTest();
}
}
Use a JApplet rather than a JFrame. Make sure you read the relevant Java Tutorial, which covers the applet lifecycle methods like init, start, stop, and destroy.
As a side note, you should not be building your UI outside of the event dispatch thread.
Use a JApplet instead of a JFrame like veer said, but you must also remove frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);, frame.pack();, and frame.setVisible(true);
Also, replace main(String[] args) with init().
I have a text editor with Netbeans where i load a text to a JtextPane. If text is too big u can read it with the help of an horizontal scroll.Is there any way to split the text into pages of 24 lines for example so that every page is visible without scrolling and use a next page button for changing page (like eBooks do)?
It is easier to use a JTextArea to do this because you can easily specify the number of lines to display each time you scroll to a new page.
The basic solution is to add a text area to a scroll pane than then hide the scrollbars. You can then use the defaults Actions of the vertical scrollbar to do the scrolling for you. The code below uses code from the Action Map Action blog entry to easily create an Action that you can add to a JButton:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class TextAreaScroll extends JPanel
{
private JTextArea textArea;
public TextAreaScroll()
{
setLayout( new BorderLayout() );
textArea = new JTextArea(10, 80);
textArea.setEditable( false );
JScrollPane scrollPane = new JScrollPane( textArea );
scrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_NEVER );
add(scrollPane);
JButton load = new JButton("Load TextAreaScroll.java");
load.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileReader reader = new FileReader( "TextAreaScroll.java" );
BufferedReader br = new BufferedReader(reader);
textArea.read( br, null );
br.close();
}
catch(Exception e2) { System.out.println(e2); }
}
});
add(load, BorderLayout.NORTH);
// Add buttons to do the scrolling
JScrollBar vertical = scrollPane.getVerticalScrollBar();
Action nextPage = new ActionMapAction("Next Page", vertical, "positiveBlockIncrement");
nextPage.putValue(AbstractAction.MNEMONIC_KEY, KeyEvent.VK_N);
JButton nextButton = new JButton(nextPage);
Action previousPage = new ActionMapAction("Previous Page", vertical, "negativeBlockIncrement");
previousPage.putValue(AbstractAction.MNEMONIC_KEY, KeyEvent.VK_N);
JButton previousButton = new JButton(previousPage);
JPanel south = new JPanel();
add(south, BorderLayout.SOUTH);
south.add( previousButton );
south.add( nextButton );
}
private static void createAndShowUI()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TextAreaScroll());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}