Reputation: 17
I am learning java, I have created a dice thrower - when i press the button it throws a dice - but the output is in the console. How can I output in the same frame with the buttons.
// sorry i am not native english speaking person, but i hope you get the idea.
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JTextArea;
public class Main {
public static void main(String s[]){
Random rand = new Random();
JFrame frame = new JFrame("Dice Thrower 2000");
JPanel panel=new JPanel();
panel.setLayout(new FlowLayout());
JLabel label = new JLabel("Throw dice");
JLabel label1 = new JLabel("You got : ");
JTextArea output = new JTextArea(" a ");
JButton buttond4 = new JButton();
buttond4.setText("d4");
buttond4.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
int n = rand.nextInt(4) + 1;
System.out.println("You threw d4 and got " + n);
}
});
JButton buttond6 = new JButton();
buttond6.setText("d6");
buttond6.addActionListener(new ActionListener() {...});
JButton buttond8 = new JButton();
buttond8.setText("d8");
buttond8.addActionListener(new ActionListener() {...});
JButton buttond10 = new JButton();
buttond10.setText("d10");
buttond10.addActionListener(new ActionListener() {...});
JButton buttond12 = new JButton();
buttond12.setText("d12");
buttond12.addActionListener(new ActionListener() {...});
JButton buttond20 = new JButton();
buttond20.setText("d20");
buttond20.addActionListener(new ActionListener() {...});
panel.add(label);
panel.add(buttond4);
panel.add(buttond6);
panel.add(buttond8);
panel.add(buttond10);
panel.add(buttond12);
panel.add(buttond20);
panel.add(label1);
frame.add(output);
frame.add(panel);
frame.setSize(500, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
I have provided buttons d4 - extended code, the code for rest buttons is almost identical.
Upvotes: 0
Views: 1334
Reputation: 938
A little bit overkill, but I hope it can help - JAVA CODE:
public class ConsolePanel {
public static void main(String[] args) {
panel(
21,
2,
3,
3,
Border.BOLD,
Border.DOUBLE,
Border.DOUBLE,
Border.THIN,
true,
true,
"My Title", "My First Topic text", "My Second Topic text"
);
}
public static void simplePanel(String... texts) {
panel(
21,
5,
1,
1,
Border.DOUBLE,
Border.DOUBLE,
Border.THIN,
Border.THIN,
true,
true,
texts
);
}
public static void simplePanelScalable(int scale, String... texts) {
panel(
scale,
5,
1,
1,
Border.DOUBLE,
Border.DOUBLE,
Border.THIN,
Border.THIN,
true,
true,
texts
);
}
public static void panel(
int scale,
int margin,
int upSpace,
int downSpace,
Border cornersFormat,
Border centerMarksFormat,
Border horizontalLinesFormat,
Border verticalLinesFormat,
boolean uppercaseTitle,
boolean centralizeTitle,
String... titleAndOthers) {
var estimatedAdjustmentFactor = 3;
var title = titleAndOthers[0];
var marginTitle = scale - (title.length() / 2) - estimatedAdjustmentFactor;
var formattedTexts =
Stream.of(titleAndOthers)
.map(item -> item.equals(title) && centralizeTitle ? " ".repeat(
marginTitle) + title : item)
.map(item -> item.equals(
title) && uppercaseTitle ? item.toUpperCase() : item)
.toArray();
var marginLimitedBySize = Math.min(margin, scale);
// scale + margin discrepacies eliminated
if (marginLimitedBySize % 2 != 0) -- marginLimitedBySize;
if (scale % 2 != 0) ++ scale;
int fullSize = (scale * 2) - marginLimitedBySize;
if (fullSize % 2 == 0) ++ fullSize;
else -- fullSize;
var whitespaceMargin = " ".repeat(marginLimitedBySize);
var externalUpSpaces = "\n".repeat(upSpace);
var externalBottomSpaces = "\n".repeat(downSpace);
var upperFace = upperLine(scale, cornersFormat, centerMarksFormat, horizontalLinesFormat);
var divider = middleLine(scale, cornersFormat, centerMarksFormat, horizontalLinesFormat);
var bottomFace = bottomLine(scale, cornersFormat, centerMarksFormat, horizontalLinesFormat);
var faceLine = faceLine(verticalLinesFormat);
var titleTextArea = String.valueOf(fullSize);
var textPreparation = new StringBuilder();
textPreparation.append(externalUpSpaces)
.append(upperFace)
.append(faceLine)
.append("%s%%-%ss".formatted(whitespaceMargin, titleTextArea))
.append(faceLine)
.append("\n")
.append(divider);
// "-1" Because the first element in the Array was used as title
// The discont-number in bodyTextArea/fullsize, subtract the size of "ordinal-ASC" and ") "
var bodyTextArea = String.valueOf(fullSize - 4);
var topicEnumeration = 0;
var ordinalSymbolEnumerator = '\u2070';
for (int i = formattedTexts.length - 1; i > 0; i--) {
++ topicEnumeration;
textPreparation.append(faceLine)
.append("%s%s%s) %%-%ss".formatted(
whitespaceMargin,
topicEnumeration,
ordinalSymbolEnumerator,
bodyTextArea
))
.append(faceLine)
.append("\n");
}
textPreparation.append(bottomFace)
.append(externalBottomSpaces);
System.out.printf(textPreparation.toString(), formattedTexts);
}
private static String generateLine(char baseChar, int scale, char BASE_LINE) {
return
String
.valueOf(baseChar)
.repeat(scale)
.replace(baseChar, BASE_LINE);
}
private static String upperLine(
int scale,
Border corner,
Border centerMark,
Border line) {
ArrayList<Character> borderStylingItems = new ArrayList<>();
switch (corner) {
case BOLD -> {
borderStylingItems.add(BoldFont.UPPER_LEFT_CORNER.code);
borderStylingItems.add(BoldFont.UPPER_RIGHT_CORNER.code);
}
case THIN -> {
borderStylingItems.add(ThinFont.UPPER_LEFT_CORNER.code);
borderStylingItems.add(ThinFont.UPPER_RIGHT_CORNER.code);
}
case DOUBLE -> {
borderStylingItems.add(DoubleFont.UPPER_LEFT_CORNER.code);
borderStylingItems.add(DoubleFont.UPPER_RIGHT_CORNER.code);
}
}
switch (centerMark) {
case BOLD -> borderStylingItems.add(BoldFont.BASE_LINE.code);
case THIN -> borderStylingItems.add(ThinFont.BASE_LINE.code);
case DOUBLE -> borderStylingItems.add(DoubleFont.BASE_LINE.code);
}
switch (line) {
case BOLD -> borderStylingItems.add(BoldFont.BASE_LINE.code);
case THIN -> borderStylingItems.add(ThinFont.BASE_LINE.code);
case DOUBLE -> borderStylingItems.add(DoubleFont.BASE_LINE.code);
}
var baseline = generateLine('_', scale, borderStylingItems.get(3));
return borderStylingItems.get(0) + baseline +
borderStylingItems.get(2) + baseline +
borderStylingItems.get(1) + "\n";
}
private static String middleLine(
int scale,
Border corner,
Border centerMark,
Border baseLine
) {
ArrayList<Character> borderStylingItems = new ArrayList<>();
switch (corner) {
case BOLD -> {
borderStylingItems.add(BoldFont.MIDDLE_LEFT.code);
borderStylingItems.add(BoldFont.MIDDLE_RIGHT.code);
}
case THIN -> {
borderStylingItems.add(ThinFont.MIDDLE_LEFT.code);
borderStylingItems.add(ThinFont.MIDDLE_RIGHT.code);
}
case DOUBLE -> {
borderStylingItems.add(DoubleFont.MIDDLE_LEFT.code);
borderStylingItems.add(DoubleFont.MIDDLE_RIGHT.code);
}
}
switch (centerMark) {
case BOLD -> borderStylingItems.add(BoldFont.BASE_LINE.code);
case THIN -> borderStylingItems.add(ThinFont.BASE_LINE.code);
case DOUBLE -> borderStylingItems.add(DoubleFont.BASE_LINE.code);
}
switch (baseLine) {
case BOLD -> borderStylingItems.add(BoldFont.BASE_LINE.code);
case THIN -> borderStylingItems.add(ThinFont.BASE_LINE.code);
case DOUBLE -> borderStylingItems.add(DoubleFont.BASE_LINE.code);
}
var divider = generateLine('_', scale, borderStylingItems.get(3));
return borderStylingItems.get(0) + divider +
borderStylingItems.get(2) + divider +
borderStylingItems.get(1) + "\n";
}
private static String bottomLine(
int scale,
Border corner,
Border centerMark,
Border baseLine) {
ArrayList<Character> borderStylingItems = new ArrayList<>();
switch (corner) {
case BOLD -> {
borderStylingItems.add(BoldFont.LOWER_LEFT_CORNER.code);
borderStylingItems.add(BoldFont.LOWER_RIGHT_CORNER.code);
}
case THIN -> {
borderStylingItems.add(ThinFont.LOWER_LEFT_CORNER.code);
borderStylingItems.add(ThinFont.LOWER_RIGHT_CORNER.code);
}
case DOUBLE -> {
borderStylingItems.add(DoubleFont.LOWER_LEFT_CORNER.code);
borderStylingItems.add(DoubleFont.LOWER_RIGHT_CORNER.code);
}
}
switch (centerMark) {
case BOLD -> borderStylingItems.add(BoldFont.BASE_LINE.code);
case THIN -> borderStylingItems.add(ThinFont.BASE_LINE.code);
case DOUBLE -> borderStylingItems.add(DoubleFont.BASE_LINE.code);
}
switch (baseLine) {
case BOLD -> borderStylingItems.add(BoldFont.BASE_LINE.code);
case THIN -> borderStylingItems.add(ThinFont.BASE_LINE.code);
case DOUBLE -> borderStylingItems.add(DoubleFont.BASE_LINE.code);
}
var baseline = generateLine('_', scale, borderStylingItems.get(3));
return borderStylingItems.get(0) + baseline +
borderStylingItems.get(2) + baseline +
borderStylingItems.get(1) + "\n";
}
private static Character faceLine(Border corner) {
return switch (corner) {
case BOLD -> BoldFont.FACE_LINE.code;
case THIN -> ThinFont.FACE_LINE.code;
case DOUBLE -> DoubleFont.FACE_LINE.code;
};
}
private enum BoldFont {
FACE_LINE('\u2503'),
BASE_LINE('\u2501'),
UPPER_LEFT_CORNER('\u250F'),
UPPER_RIGHT_CORNER('\u2513'),
MIDDLE_LEFT('\u2523'),
MIDDLE_RIGHT('\u252B'),
LOWER_LEFT_CORNER('\u2517'),
LOWER_RIGHT_CORNER('\u251B');
private final char code;
BoldFont(char code) {
this.code = code;
}
}
private enum ThinFont {
FACE_LINE('\u2502'),
BASE_LINE('\u2500'),
UPPER_LEFT_CORNER('\u250C'),
UPPER_RIGHT_CORNER('\u2510'),
MIDDLE_LEFT('\u252C'),
MIDDLE_RIGHT('\u2524'),
LOWER_LEFT_CORNER('\u2514'),
LOWER_RIGHT_CORNER('\u2518');
private final char code;
ThinFont(char code) {
this.code = code;
}
}
private enum DoubleFont {
FACE_LINE('\u2551'),
BASE_LINE('\u2550'),
UPPER_LEFT_CORNER('\u2554'),
UPPER_RIGHT_CORNER('\u2557'),
MIDDLE_LEFT('\u2560'),
MIDDLE_RIGHT('\u2563'),
LOWER_LEFT_CORNER('\u255A'),
LOWER_RIGHT_CORNER('\u255D');
private final char code;
DoubleFont(char code) {
this.code = code;
}
}
private enum Border {
BOLD, THIN, DOUBLE
}
}
Check It in: https://github.com/codegtd/tdd-log-panel
Upvotes: 0
Reputation: 938
Thats a code version in Dart/Flutter
Check It in: https://github.com/codegtd/tdd-log-panel-flutter-dart
// @formatter:off
void main() {
DartPanel().scalablePanel(
scale: 21,
texts: ["Simple Panel Scalable", "My First Topic"]);
DartPanel().simplePanel(
texts: ["Simple Panel", "My First Topic"]);
DartPanel().panel(
scale: 21,
margin: 2,
upSpace: 3,
downSpace: 3,
cornersFormat: _Border.BOLD,
centerMarksFormat: _Border.DOUBLE,
horizontalFacesFormat: _Border.DOUBLE,
lateralFacesFormat: _Border.THIN,
isUppercaseTitle: true,
isCentralizedTitle: true,
titleAndOthers: ["My Panel","First Topic","Second Topic"]);
}
class DartPanel {
void simplePanel({
required List<String> texts}) {
panel(
scale: 21,
margin: 5,
upSpace: 1,
downSpace: 1,
cornersFormat: _Border.DOUBLE,
centerMarksFormat: _Border.DOUBLE,
horizontalFacesFormat: _Border.THIN,
lateralFacesFormat: _Border.THIN,
isUppercaseTitle: true,
isCentralizedTitle: true,
titleAndOthers:texts);
}
void scalablePanel({
required int scale,
required List<String> texts}) {
panel(
scale: scale,
margin:5,
upSpace: 1,
downSpace: 1,
cornersFormat: _Border.DOUBLE,
centerMarksFormat: _Border.DOUBLE,
horizontalFacesFormat: _Border.THIN,
lateralFacesFormat: _Border.THIN,
isUppercaseTitle: true,
isCentralizedTitle: true,
titleAndOthers: texts);
}
void panel({
required int scale,
required int margin,
required int upSpace,
required int downSpace,
required _Border cornersFormat,
required _Border centerMarksFormat,
required _Border horizontalFacesFormat,
required _Border lateralFacesFormat,
required bool isUppercaseTitle,
required bool isCentralizedTitle,
required List<String> titleAndOthers,}
) {
var estimatedAdjustmentFactor = 3;
var title = titleAndOthers[0];
var marginTitle = scale - (title.length / 2).round() - estimatedAdjustmentFactor;
var titleAndTopics =
titleAndOthers
.map((item) => item == title && isCentralizedTitle ? (' ' * marginTitle) + title : item)
.map((item) => item == title && isUppercaseTitle ? item.toUpperCase() : item)
.toList();
var marginLimitedBySize = margin < scale ? margin : scale;
/*╔════════════════════════════════════════╗
║ scale + margin discrepacies eliminated ║
╚════════════════════════════════════════╝*/
if (marginLimitedBySize.isOdd) --marginLimitedBySize;
if (scale.isOdd) ++scale;
int fullSize = (scale * 2) - marginLimitedBySize;
if (fullSize.isEven) ++fullSize; else --fullSize;
var topicMargin = (' ' * marginLimitedBySize);
var externalUpSpaces = '\n' * upSpace;
var externalBottomSpaces = '\n' * downSpace;
var upperFace = _createUpperFace(
scale, cornersFormat, centerMarksFormat, horizontalFacesFormat);
var dividerFace = _createDividerFace(
scale, cornersFormat, centerMarksFormat, horizontalFacesFormat);
var bottomFace = _createBottomFace(
scale, cornersFormat, centerMarksFormat, horizontalFacesFormat);
var leftLateralFace = _createLateralFace(lateralFacesFormat);
var rightLateralFace = _createLateralFace(lateralFacesFormat);
var titleTextArea = ' ' * (fullSize - titleAndTopics[0].length - 2);
var textPreparation = StringBuffer()
..write(externalUpSpaces)
..write(upperFace)
..write(rightLateralFace)
..write('$topicMargin ${titleAndTopics[0]} $titleTextArea')
..write(leftLateralFace)
..write('\n')
..write(dividerFace);
/*╔═══════════════════════════════════════════════════════════════╗
║ "-1" Because the first element in the Array was used as title ║
║ The discont-number in fillUpSpaces/fullsize, subtract the size║
║ of "ordinal-ASC" and ") " ║
╚═══════════════════════════════════════════════════════════════╝*/
var topicEnumerator = 0;
var symbolEnumerator = '\u2070';
for (int i = titleAndTopics.length - 1; i > 0; i--) {
++topicEnumerator;
var fillUpSpaces = ' ' * (fullSize - titleAndTopics[topicEnumerator].length - 4);
textPreparation
..write(leftLateralFace)
..write(
'$topicMargin'
'$topicEnumerator'
'$symbolEnumerator) '
'${titleAndTopics[topicEnumerator]}'
'$fillUpSpaces')
..write(leftLateralFace)
..write('\n');
}
textPreparation
..write(bottomFace)
..write(externalBottomSpaces);
print('$textPreparation');
}
String _createLateralFace(_Border corner) {
switch (corner) {
case _Border.BOLD: return _BoldFont.FACE_LINE.code;
case _Border.THIN: return _ThinFont.FACE_LINE.code;
case _Border.DOUBLE: return _DoubleFont.FACE_LINE.code;
default: return '';
}
}
String _createUpperFace(
int scale,
_Border corner,
_Border centerMark,
_Border line) {
List<String> borderStylingItems = [];
switch (corner) {
case _Border.BOLD:
borderStylingItems.add(_BoldFont.UPPER_LEFT_CORNER.code);
borderStylingItems.add(_BoldFont.UPPER_RIGHT_CORNER.code); break;
case _Border.THIN:
borderStylingItems.add(_ThinFont.UPPER_LEFT_CORNER.code);
borderStylingItems.add(_ThinFont.UPPER_RIGHT_CORNER.code); break;
case _Border.DOUBLE:
borderStylingItems.add(_DoubleFont.UPPER_LEFT_CORNER.code);
borderStylingItems.add(_DoubleFont.UPPER_RIGHT_CORNER.code); break;
}
switch (centerMark) {
case _Border.BOLD:
borderStylingItems.add(_BoldFont.BASE_LINE.code); break;
case _Border.THIN:
borderStylingItems.add(_ThinFont.BASE_LINE.code); break;
case _Border.DOUBLE:
borderStylingItems.add(_DoubleFont.BASE_LINE.code); break;
}
switch (line) {
case _Border.BOLD:
borderStylingItems.add(_BoldFont.BASE_LINE.code); break;
case _Border.THIN:
borderStylingItems.add(_ThinFont.BASE_LINE.code); break;
case _Border.DOUBLE:
borderStylingItems.add(_DoubleFont.BASE_LINE.code); break;
}
String upperFace = _faceGenerator('_', ((scale * 2)+1), borderStylingItems[2]);
return borderStylingItems[0] + upperFace + borderStylingItems[1] + "\n";
}
String _createDividerFace(
int scale,
_Border corner,
_Border centerMark,
_Border baseLine) {
List<String> borderStylingItems = [];
switch (corner) {
case _Border.BOLD:
borderStylingItems.add(_BoldFont.MIDDLE_LEFT.code);
borderStylingItems.add(_BoldFont.MIDDLE_RIGHT.code); break;
case _Border.THIN:
borderStylingItems.add(_ThinFont.MIDDLE_LEFT.code);
borderStylingItems.add(_ThinFont.MIDDLE_RIGHT.code); break;
case _Border.DOUBLE:
borderStylingItems.add(_DoubleFont.MIDDLE_LEFT.code);
borderStylingItems.add(_DoubleFont.MIDDLE_RIGHT.code); break;
}
switch (centerMark) {
case _Border.BOLD:
borderStylingItems.add(_BoldFont.BASE_LINE.code); break;
case _Border.THIN:
borderStylingItems.add(_ThinFont.BASE_LINE.code); break;
case _Border.DOUBLE:
borderStylingItems.add(_DoubleFont.BASE_LINE.code); break;
}
switch (baseLine) {
case _Border.BOLD:
borderStylingItems.add(_BoldFont.BASE_LINE.code); break;
case _Border.THIN:
borderStylingItems.add(_ThinFont.BASE_LINE.code); break;
case _Border.DOUBLE:
borderStylingItems.add(_DoubleFont.BASE_LINE.code); break;
}
var panelDivider = _faceGenerator('_', scale, borderStylingItems[3]);
return
borderStylingItems[0] +
panelDivider +
borderStylingItems[2] +
panelDivider +
borderStylingItems[1] +
"\n";
}
String _createBottomFace(
int scale,
_Border corner,
_Border centerMark,
_Border baseLine,
) {
List<String> borderStylingItems = [];
switch (corner) {
case _Border.BOLD:
borderStylingItems.add(_BoldFont.LOWER_LEFT_CORNER.code);
borderStylingItems.add(_BoldFont.LOWER_RIGHT_CORNER.code); break;
case _Border.THIN:
borderStylingItems.add(_ThinFont.LOWER_LEFT_CORNER.code);
borderStylingItems.add(_ThinFont.LOWER_RIGHT_CORNER.code); break;
case _Border.DOUBLE:
borderStylingItems.add(_DoubleFont.LOWER_LEFT_CORNER.code);
borderStylingItems.add(_DoubleFont.LOWER_RIGHT_CORNER.code); break;
}
switch (centerMark) {
case _Border.BOLD:
borderStylingItems.add(_BoldFont.BASE_LINE.code); break;
case _Border.THIN:
borderStylingItems.add(_ThinFont.BASE_LINE.code); break;
case _Border.DOUBLE:
borderStylingItems.add(_DoubleFont.BASE_LINE.code); break;
}
switch (baseLine) {
case _Border.BOLD:
borderStylingItems.add(_BoldFont.BASE_LINE.code); break;
case _Border.THIN:
borderStylingItems.add(_ThinFont.BASE_LINE.code); break;
case _Border.DOUBLE:
borderStylingItems.add(_DoubleFont.BASE_LINE.code); break;
}
var bottonFace = _faceGenerator('_', scale, borderStylingItems[3]);
return
borderStylingItems[0] +
bottonFace +
borderStylingItems[2] +
bottonFace +
borderStylingItems[1] +
"\n";
}
String _faceGenerator(
String baseChar,
int scale,
String BASE_LINE) {
return (baseChar * scale).replaceAll(baseChar, BASE_LINE);
}
}
enum _BoldFont {
FACE_LINE('\u2503'),
BASE_LINE('\u2501'),
UPPER_LEFT_CORNER('\u250F'),
UPPER_RIGHT_CORNER('\u2513'),
MIDDLE_LEFT('\u2523'),
MIDDLE_RIGHT('\u252B'),
LOWER_LEFT_CORNER('\u2517'),
LOWER_RIGHT_CORNER('\u251B');
final String code;
const _BoldFont(this.code);
}
enum _ThinFont {
FACE_LINE('\u2502'),
BASE_LINE('\u2500'),
UPPER_LEFT_CORNER('\u250C'),
UPPER_RIGHT_CORNER('\u2510'),
MIDDLE_LEFT('\u252C'),
MIDDLE_RIGHT('\u2524'),
LOWER_LEFT_CORNER('\u2514'),
LOWER_RIGHT_CORNER('\u2518');
final String code;
const _ThinFont(this.code);
}
enum _DoubleFont {
FACE_LINE('\u2551'),
BASE_LINE('\u2550'),
UPPER_LEFT_CORNER('\u2554'),
UPPER_RIGHT_CORNER('\u2557'),
MIDDLE_LEFT('\u2560'),
MIDDLE_RIGHT('\u2563'),
LOWER_LEFT_CORNER('\u255A'),
LOWER_RIGHT_CORNER('\u255D');
final String code;
const _DoubleFont(this.code);
}
enum _Border { BOLD, THIN, DOUBLE }
// @formatter:on
Upvotes: 0
Reputation: 36611
Using System.out.println("You threw d4 and got " + n);
causes the print to the console.
You should use the JTextArea#append
method instead.
Your code would become:
final JTextArea output = new JTextArea(" a ");
JButton buttond4 = new JButton();
buttond4.setText("d4");
buttond4.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
int n = rand.nextInt(4) + 1;
output.append("You threw d4 and got " + n + "\n");
}
});
Edit:
You also need to add the output
to the JFrame
. You tried this by using
frame.add(output);
frame.add(panel);
but that won't work. The content pane of a JFrame
by default has a BorderLayout
, and calling add
will add the component in the BorderLayout#CENTER
. That area can only contain one component.
Now you have two options:
LayoutManager
. This is a good overview of the standard available LayoutManager
s.Keep the current LayoutManager
, and add the two components to different areas, e.g.
frame.add(output, BorderLayout.CENTER);
frame.add(panel, BorderLayout.SOUTH);
Upvotes: 4