Choosing between custom JPanel and JTable layout - java

I'm trying to set up a JPanel which will display lines and text horizontally. It will take a text file, and I'm trying to display the lines and text at the same time given the size of the file. Would it be more appropriate (being relatively new to coding) to use a JTable layout, or make my own layout on a JPanel?

Below is a very basic example on how you could use a JTextPane to display some text from a text file within a JFrame. If you want to do anything more then things like layoutmangers will come into play, but for simple text display this should be suitable:
public class SO{
public static void main(String[] args) throws IOException{
JFrame frame = new JFrame();
JTextPane pane = new JTextPane();
frame.add(pane);
BufferedReader br = new BufferedReader(new FileReader("D:\\Users\\user2777005\\Desktop\\test.txt"));
String everything = "";
try {
StringBuilder sbuild = new StringBuilder();
String line = br.readLine();
while (line != null) {
sbuild.append(line);
sbuild.append('\n');
line = br.readLine();
}
everything = sbuild.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
br.close();
}
pane.setFont(new Font("Segoe Print", Font.BOLD, 12));
pane.setText(everything);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
As shown a JTexPane does also allow for Font changes.
Good luck!

Related

How to overlap a JPanel(background) and a JTextField

I am creating a log in application for someones graduation, I need several text fields and a background, I have added the background and now need to add the text fields, the problem is that they won't seem to go on top of each other.
I have tried them each separately and without one another they both work perfectly but i can't get them to stack, I have seen several answers on this site to deal with a similar problem but for this application I need to put several text fields on the background as apposed to just one, here is what I have thus far...
//creates the frame with a title as a parameter
JFrame frame = new JFrame("Sign In Sheet");
//sets the size
frame.setSize(1000, 556);
//makes it so the application stops running when you close it
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//puts it in the center of the screen
frame.setLocationRelativeTo(null);
//makes it so you can't resize it
frame.setResizable(false);
//setting the background by looking for the image
try{
frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:/Users/Gabriel R. Warner/Desktop/clouds.png")))));
}catch(IOException e){
//and prints an error message if it's not found
System.out.println("well it didn't work");
}
//adding text fields with names apropriate to function
JTextField name1 = new JTextField();
name1.setPreferredSize(new Dimension(200, 15));
name1.setBackground(Color.WHITE);
frame.add(name1);
//makes frame visible
frame.setVisible(true);
Simply stated the text field won't show up with the background and all the results only offer answers for a single text field
The problem is in this line: frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:/Users/Gabriel R. Warner/Desktop/clouds.png")))));
In this line you set a JLabel as the content pane of your JFrame. Then, you frame.add(name1); So you are adding a JTextField to a JLabel...Well this does not seem right, right?
The answer would be to create a new JPanel, add the background image to this panel, set the panel as the content pane of the frame and finally add the textfield to the panel/contentpane.
An example:
#SuppressWarnings("serial")
public class FrameWithBackgroundImage extends JFrame {
public FrameWithBackgroundImage() {
super("Sign In Sheet");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
try {
Image bgImage = loadBackgroundImage();
JPanel backgroundImagePanel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bgImage, 0, 0, null);
}
};
setContentPane(backgroundImagePanel);
} catch (IOException e) {
e.printStackTrace();
}
JTextField textField = new JTextField(10);
add(textField);
}
private Image loadBackgroundImage() throws IOException {
File desktop = new File(System.getProperty("user.home"), "Desktop");
File image = new File(desktop, "img.jpg");
return ImageIO.read(image);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new FrameWithBackgroundImage().setVisible(true);
});
}
}
Preview:
Worth to read question: Simplest way to set image as JPanel background

How to read File and write content into JTextArea?

I want to transfer content from a text file into a JTextarea. I suppose my code just needs small adjustments but even through research. I am not able to find out, what is wrong. So far it is just displaying an empty JFrame instead of the text of the file.
this.setSize(this.width, this.height);
this.setVisible(true);
this.jScrollPane = new JScrollPane(this.jTextArea);
this.jPanel = new JPanel();
this.jPanel.setOpaque(true);
this.jTextArea.setVisible(true);
try {
this.jTextArea = new JTextArea();
this.jTextArea.read(new InputStreamReader(
getClass().getResourceAsStream("C:\\wrk\\SapCommerceCloud\\src\\SwingUni\\name")),
null);
} // catch
this.add(this.jScrollPane);
And the usage:
public static void main(String[] args) {
new TextFrame(new File("C:\\wrk\\SapCommerceCloud\\src\\SwingUni\\name"), 500, 500);
}
You have 2 important issues in this code:
You are creating jScrollPane this.jScrollPane = new JScrollPane(this.jTextArea); before reading the file content using jTextArea
The method does not work read(new InputStreamReader(
getClass().getResourceAsStream("C:\\wrk\\SapCommerceCloud\\src\\SwingUni\\name")), null); Use the one in the following example.
You have to catch the exception to solve the problems
public class TextAreaDemo extends JFrame {
private JScrollPane jScrollPane;
private JTextArea jTextArea ;
private static final String FILE_PATH="/Users/user/IdeaProjects/StackOverflowIssues/file.txt";
public TextAreaDemo() {
try {
jTextArea = new JTextArea(24, 31);
jTextArea.read(new BufferedReader(new FileReader(FILE_PATH)), null);
} catch (Exception e){
e.printStackTrace();
}
jScrollPane = new JScrollPane(this.jTextArea);
this.add(this.jScrollPane);
this.setVisible(true);
this.setSize(400, 200);
}
public static void main(String[] args) {
TextAreaDemo textAreaDemo = new TextAreaDemo();
}

typewriter effect with JTextArea and Scanner JAVA

I'm making a game with my teammate for a school project.
I have created a JTextArea where the lines of a text file would be printed.
I would like to add the typeWriter effect, therefore I searched for answers on this website.
I found some pretty information here :
java-add-typewriter-effect-to-jtextarea
using-timer-to-achieve-typewriter-effect-in-jtextarea
I tried the solutions above, without success.
I'll put my code :
public static void ui() {
Font baseText = new Font("Roboto", Font.PLAIN, 30);
JFrame mainWindow = new JFrame("Main Window");
JTextArea textArea = new JTextArea();
textArea.setFont(baseText);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
JPanel panelButton = new JPanel();
panelButton.setLayout(new FlowLayout());
JButton bContinue = new JButton("Continue");
bContinue.setFont(baseText);
Path path = FileSystems.getDefault().getPath("beginning.txt");
try {
Scanner sc = new Scanner(path);
while(sc.hasNextLine()){
slowDisplay(line, textArea);
}
} catch (IOException ex) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
}
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panelButton.add(bContinue);
mainWindow.add(textArea);
mainWindow.add(panelButton, BorderLayout.SOUTH);
mainWindow.setBounds(0, 0, 1920, 1080);
mainWindow.setVisible(true);
}
Here is the content of the slowDisplay Method :
public static void slowDisplay(String line, JTextArea textArea){
Timer timer = new Timer(500, null);
timer.addActionListener(new ActionListener(){
int index=0;
#Override
public void actionPerformed(ActionEvent e) {
if(index<line.length()){
textArea.append(String.valueOf(line.charAt(index++)));
}
else if(index==line.length()){
textArea.append("\n");
}
else{
timer.stop();
}
}
});
timer.start();
}
What it does is that it browses the columns of the text files and write the characters, it creates something awful, unreadable and I don't know why :
The thing
I'll put the content of my text file :
-Mmmh...
-I-I feel cold. Where am I?
-Huh? Is this thing where I'm lying is a human sized plant?!
I looked around, I saw nothing but trees, bushes, and plants.
-What the...
If someone can guide me please, I would be grateful.
I have also tried typewriter effect way long ago.
Instead i used Thread.sleep() function to perform this task.
So here is the method for it.
void typeEffect(String str,JTextArea textArea)throws Exception{
//loop through each character and append it to the JTextArea
for(int i==0;i<str.length();i++){
textArea.append(str.charAt(i)+"");
Thread.sleep(20);//stops for 20 milliseconds
}
}
This looks very simple.
EDIT 1:-
I Have this code which is working as required.
import javax.swing.*;
class DelayTest
{
public static void main(String args[])throws Exception
{
JFrame f=new JFrame("Main Frame");
JTextArea textA=new JTextArea();
f.setSize(720,600);
f.add(textA);
f.setVisible(true);
typeEffect("Hello This is a sample String",textA);
}
static void typeEffect(String str,JTextArea textArea)throws Exception{
//loop through each character and append it to the JTextArea
for(int i=0;i<str.length();i++){
textArea.append(str.charAt(i)+"");
Thread.sleep(100);//stops for 100 milliseconds
}//closing of loop
}//closing of method
}//closing of class
I have executed this code and found it working.

Reading text from file and putting it to the JLabel

I want to change my JLabel when I click a JButton. It sounds simple but can't really find a good piece of code.
Here is part of my code:
final JButton continueGame = new JButton();
continueGame.setPreferredSize(new Dimension(1000, 30));
continueGame.setLocation(95, 45);
continueGame.setText("<html>Continue</html>");
continueGame.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ev) {
panel.remove(continueGame);
SwingUtilities.updateComponentTreeUI(frameKontrastGame);
if(RandomNrJeden <= 50)
{
JOptionPane.showMessageDialog(frameKontrastGame, "Eggs are not supposed to be green.");
frameKontrastGame.setVisible(false);
JFrame frameScenario2 = new JFrame();
frameScenario2.setTitle("Scenario2");
frameScenario2.setSize(1000,700);
frameScenario2.setLocationRelativeTo(null);
frameScenario2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panelScenario = new JPanel ();
panel.setLayout(new GridLayout(2, 1));
final JLabel tekst = new JLabel ();
tekst.setText("<html>Część dialogu numer 1</html>");
//JTextField dialog = new JTextField(20);
//dialog.setText("<html>Eggs are not supposed to be green.</html>");
JButton OdpPierwsza = new JButton ();
OdpPierwsza.setText("<html>Opowiedź pierwsza</html>");
OdpPierwsza.addActionListener (new ActionListener(){
#Override
public void actionPerformed(ActionEvent ev) {
tekst.setText("<html>HERE I NEED A TEXT FROM FILE dialog.txt</html>");
}
});
//panelScenario.add(dialog);
panelScenario.add(tekst);
panelScenario.add(OdpPierwsza);
frameScenario2.getContentPane().add(panelScenario);
frameScenario2.setVisible(true);
}
(If the brackets are wrong that's because its not the whole code.)
So:
Where is the "HERE I NEED A TEXT FROM FILE dialog.txt" I need some kind of reader. The best one will be the one which reads text line by line. I just cant find how to write it.
I need to add the JLabel to the JPanel.
You can read your file into just one string using
BufferedReader br = new BufferedReader(new FileReader("your_file.txt"));
String line = br.readLine();
ArrayList<String> listOfStrings = new ArrayList<>();
listOfString.add(line);
while(line != null)
{
line = br.readLine();
listOfString.add(line);
}
And now do a for-loop to iterate over the JList and add text to the JLabel. Better is a JTextArea.

How do i write to a text file using java?

I have been using the "Learning Java 2nd Edtion" book to try make my java application write my input to a text file called properties. I have manipulated the text book example into my own code but still having problems trying to get it to work. I think i may need to hook it up to my submit button but this wasnt mentioned within the chapter.
Basically im trying to store the information in the text file and then use that text file within another location to read all of the property details.
Here is my code for the AddProperty Page so far any advice would be greatly appreciated.
At the moment iv hit the wall.
/**
*
* #author Graeme
*/
package Login;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.EmptyBorder;
public class AddProperty
{
public void AddProperty()
{
JFrame frame = new JFrame("AddPropertyFrame");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// having to set sizes of components is rare, and often a sign
// of problems with layouts.
//frame.setSize(800,600);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20,20));
// make it big like the original
panel.setBorder(new EmptyBorder(100,20,100,20));
frame.add(panel);
//panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
JLabel HouseNumber = new JLabel("House Number/Name");
panel.add(HouseNumber);
JTextField HouseNumber1 = new JTextField(10);
panel.add(HouseNumber1);
JLabel HousePrice = new JLabel("House Price");
panel.add(HousePrice);
JTextField HousePrice1 = new JTextField(10);
panel.add(HousePrice1);
JLabel HouseType = new JLabel("House Type");
panel.add(HouseType);
JTextField HouseType1 = new JTextField(10);
panel.add(HouseType1);
JLabel Location = new JLabel("Location");
panel.add(Location);
JTextField Location1 = new JTextField(10);
panel.add(Location1);
JButton submit = new JButton("Submit");
panel.add(submit);
submit.addActionListener(new Action());
// tell the GUI to assume its natural (minimum) size.
frame.pack();
}
static class Action implements ActionListener{
#Override
public void actionPerformed (ActionEvent e)
{
// this should probably be a modal JDialog or JOptionPane.
JOptionPane.showMessageDialog(null, "You have successfully submitted a property.");
}
static class propertyList
{
public static void main (String args[]) throws Exception {
File properties = new File(args[0]);
if (!properties.exists() || !properties.canRead() ) {
System.out.println("Cant read " + properties);
return;
}
if (properties.isDirectory()){
String [] properties1 = properties.list();
for (int i=0; i< properties1.length; i++)
System.out.println();
}
else
try {
FileReader fr = new FileReader (properties);
BufferedReader in = new BufferedReader (fr);
String line;
while ((line = in.readLine())!= null)
System.out.println(line);
}
catch (FileNotFoundException e){
System.out.println("Not Able To Find File");
}
}
}
}
}
in your Action performed you are not stating anything, for example in your action performed you could add.
public void actionPerformed(ActionEvent e)
{
houseNumber2 = houseNumber1.getText();
housePrice2 = housePrice1.getText();
town1 = town.getText();
comboBoxType2 = comboBoxType1.getSelectedItem();
inputData = housenumber2 + "," + housePrice2 + "," + town1 + "," + comboBoxType2;
FileName.Filewritermethod(inputData);
frame.setVisible(false);
}
});
This would strings to take the values of your JTexFields and pass them onto a textfile provided you have a FileWriter Class
Your action listener is not doing anything much right now.
Add code to add property in the following method:
public void actionPerformed (ActionEvent e)
{
//add your code here
}

Categories